@powersync/web 1.35.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 +1126 -1231
  2. package/dist/index.umd.js.map +1 -1
  3. package/dist/worker/SharedSyncImplementation.umd.js +599 -3086
  4. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
  5. package/dist/worker/WASQLiteDB.umd.js +860 -868
  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 -1878
  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 -401
  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 -490
  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,205 +2098,355 @@ 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
+ \***************************************************************/
2416
2105
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2417
2106
 
2418
2107
  __webpack_require__.r(__webpack_exports__);
2419
2108
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2420
- /* harmony export */ AsyncWASQLiteModuleFactory: () => (/* binding */ AsyncWASQLiteModuleFactory),
2421
- /* harmony export */ DEFAULT_MODULE_FACTORIES: () => (/* binding */ DEFAULT_MODULE_FACTORIES),
2422
- /* harmony export */ MultiCipherAsyncWASQLiteModuleFactory: () => (/* binding */ MultiCipherAsyncWASQLiteModuleFactory),
2423
- /* harmony export */ MultiCipherSyncWASQLiteModuleFactory: () => (/* binding */ MultiCipherSyncWASQLiteModuleFactory),
2424
- /* harmony export */ SyncWASQLiteModuleFactory: () => (/* binding */ SyncWASQLiteModuleFactory),
2425
- /* harmony export */ WASQLiteVFS: () => (/* binding */ WASQLiteVFS),
2426
- /* harmony export */ WASqliteConnection: () => (/* binding */ WASqliteConnection)
2109
+ /* harmony export */ ConcurrentSqliteConnection: () => (/* binding */ ConcurrentSqliteConnection),
2110
+ /* harmony export */ ConnectionLeaseToken: () => (/* binding */ ConnectionLeaseToken)
2427
2111
  /* 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
-
2112
+ /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
2433
2113
 
2434
2114
  /**
2435
- * List of currently tested virtual filesystems
2436
- */
2437
- var WASQLiteVFS;
2438
- (function (WASQLiteVFS) {
2439
- WASQLiteVFS["IDBBatchAtomicVFS"] = "IDBBatchAtomicVFS";
2440
- WASQLiteVFS["OPFSCoopSyncVFS"] = "OPFSCoopSyncVFS";
2441
- WASQLiteVFS["AccessHandlePoolVFS"] = "AccessHandlePoolVFS";
2442
- })(WASQLiteVFS || (WASQLiteVFS = {}));
2443
- /**
2444
- * @internal
2445
- */
2446
- const AsyncWASQLiteModuleFactory = async () => {
2447
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-cc5fcc").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs"));
2448
- return factory();
2449
- };
2450
- /**
2451
- * @internal
2452
- */
2453
- const MultiCipherAsyncWASQLiteModuleFactory = async () => {
2454
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-c99c07").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs"));
2455
- return factory();
2456
- };
2457
- /**
2458
- * @internal
2459
- */
2460
- const SyncWASQLiteModuleFactory = async () => {
2461
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite.mjs"));
2462
- return factory();
2463
- };
2464
- /**
2465
- * @internal
2466
- */
2467
- const MultiCipherSyncWASQLiteModuleFactory = async () => {
2468
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-b9c070").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs"));
2469
- return factory();
2470
- };
2471
- /**
2472
- * @internal
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.
2473
2122
  */
2474
- const DEFAULT_MODULE_FACTORIES = {
2475
- [WASQLiteVFS.IDBBatchAtomicVFS]: async (options) => {
2476
- let module;
2477
- if (options.encryptionKey) {
2478
- module = await MultiCipherAsyncWASQLiteModuleFactory();
2479
- }
2480
- else {
2481
- module = await AsyncWASQLiteModuleFactory();
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);
2482
2148
  }
2483
- const { IDBBatchAtomicVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-0df390").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js"));
2484
- return {
2485
- module,
2486
- // @ts-expect-error The types for this static method are missing upstream
2487
- vfs: await IDBBatchAtomicVFS.create(options.dbFileName, module, { lockPolicy: 'exclusive' })
2488
- };
2489
- },
2490
- [WASQLiteVFS.AccessHandlePoolVFS]: async (options) => {
2491
- let module;
2492
- if (options.encryptionKey) {
2493
- module = await MultiCipherSyncWASQLiteModuleFactory();
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
+ }
2494
2181
  }
2495
- else {
2496
- module = await SyncWASQLiteModuleFactory();
2182
+ catch (e) {
2183
+ returnMutex();
2184
+ throw e;
2497
2185
  }
2498
- // @ts-expect-error The types for this static method are missing upstream
2499
- const { AccessHandlePoolVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-151024").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js"));
2500
- return {
2501
- module,
2502
- vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)
2503
- };
2504
- },
2505
- [WASQLiteVFS.OPFSCoopSyncVFS]: async (options) => {
2506
- let module;
2507
- if (options.encryptionKey) {
2508
- module = await MultiCipherSyncWASQLiteModuleFactory();
2186
+ return token;
2187
+ }
2188
+ async close() {
2189
+ const returnMutex = await this.acquireMutex();
2190
+ try {
2191
+ await this.inner.close();
2509
2192
  }
2510
- else {
2511
- module = await SyncWASQLiteModuleFactory();
2193
+ finally {
2194
+ returnMutex();
2512
2195
  }
2513
- // @ts-expect-error The types for this static method are missing upstream
2514
- const { OPFSCoopSyncVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-c01ef0").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js"));
2515
- const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);
2516
- return {
2517
- module,
2518
- vfs
2519
- };
2520
2196
  }
2521
- };
2197
+ }
2522
2198
  /**
2523
- * @internal
2524
- * WA-SQLite connection which directly interfaces with WA-SQLite.
2525
- * This is usually instantiated inside a worker.
2199
+ * An instance representing temporary exclusive access to a {@link ConcurrentSqliteConnection}.
2526
2200
  */
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;
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
+ }
2536
2211
  /**
2537
- * Unique id for this specific connection. This is used to prevent broadcast table change
2538
- * notification loops.
2212
+ * Returns this lease, allowing another client to use the database connection.
2539
2213
  */
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;
2214
+ async returnLease() {
2215
+ await this.useMutex.runExclusive(async () => {
2216
+ if (!this.closed) {
2217
+ this.closed = true;
2218
+ this.returnMutex();
2219
+ }
2220
+ });
2554
2221
  }
2555
2222
  /**
2556
- * Gets the id for the current hold.
2557
- * This can be used to check for invalid states.
2223
+ * This should only be used internally, since the callback must not use the raw connection after resolving.
2558
2224
  */
2559
- get currentHoldId() {
2560
- return this._holdId;
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
+ });
2561
2232
  }
2562
- get sqliteAPI() {
2563
- if (!this._sqliteAPI) {
2564
- throw new Error(`Initialization has not completed`);
2565
- }
2566
- return this._sqliteAPI;
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
+ };
2567
2266
  }
2568
- get dbP() {
2569
- if (!this._dbP) {
2570
- throw new Error(`Initialization has not completed`);
2267
+ #pushTableUpdateToClients(changedTables) {
2268
+ for (const listener of this.#clientTableListeners) {
2269
+ listener.postMessage(changedTables);
2571
2270
  }
2572
- return this._dbP;
2271
+ }
2272
+ get #inner() {
2273
+ return this.#options.inner;
2274
+ }
2275
+ get #logger() {
2276
+ return this.#options.logger;
2573
2277
  }
2574
2278
  /**
2575
- * Checks if the database connection is in autocommit mode.
2576
- * @returns true if in autocommit mode, false if in a transaction
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.
2577
2283
  */
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));
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
+ }
2586
2294
  }
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}`);
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
+ });
2592
2327
  }
2593
- this._holdId = null;
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];
2594
2429
  }
2595
- async openDB() {
2596
- this._dbP = await this.sqliteAPI.open_v2(this.options.dbFilename);
2597
- return this._dbP;
2430
+ get isOpen() {
2431
+ return this.db != 0;
2598
2432
  }
2599
- async executeEncryptionPragma() {
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};`);
2600
2437
  if (this.options.encryptionKey) {
2601
- await this.executeSingleStatement(`PRAGMA key = "${this.options.encryptionKey}"`);
2438
+ const escapedKey = this.options.encryptionKey.replace("'", "''");
2439
+ await this.executeRaw(`PRAGMA key = '${escapedKey}'`);
2602
2440
  }
2603
- return;
2441
+ await this.executeRaw(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);
2442
+ await this.executeRaw(`SELECT powersync_update_hooks('install');`);
2604
2443
  }
2605
2444
  async openSQLiteAPI() {
2606
2445
  const { module, vfs } = await this._moduleFactory({
2607
2446
  dbFileName: this.options.dbFilename,
2608
2447
  encryptionKey: this.options.encryptionKey
2609
2448
  });
2610
- const sqlite3 = _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.Factory(module);
2449
+ const sqlite3 = (0,_journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.Factory)(module);
2611
2450
  sqlite3.vfs_register(vfs, true);
2612
2451
  /**
2613
2452
  * Register the PowerSync core SQLite extension
@@ -2624,211 +2463,208 @@ class WASqliteConnection extends _powersync_common__WEBPACK_IMPORTED_MODULE_1__.
2624
2463
  }
2625
2464
  return sqlite3;
2626
2465
  }
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
- });
2466
+ requireSqlite() {
2467
+ if (!this._sqliteAPI) {
2468
+ throw new Error(`Initialization has not completed`);
2672
2469
  }
2673
- this.updatedTables.clear();
2674
- this.iterateListeners((cb) => cb.tablesUpdated?.(event));
2470
+ return this._sqliteAPI;
2675
2471
  }
2676
2472
  /**
2677
- * This executes SQL statements in a batch.
2473
+ * Checks if the database connection is in autocommit mode.
2474
+ * @returns true if in autocommit mode, false if in a transaction
2678
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
+ }
2679
2483
  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
- };
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));
2720
2491
  }
2721
- const result = {
2722
- rowsAffected: affectedRows,
2723
- rows: { _array: [], length: 0 }
2724
- };
2725
- return result;
2726
- });
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
+ };
2727
2504
  }
2728
2505
  /**
2729
- * This executes single SQL statements inside a requested lock.
2506
+ * This executes a single statement using SQLite3 and returns the results as a {@link RawResultSet}.
2730
2507
  */
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
- });
2508
+ async executeSingleStatementRaw(sql, bindings) {
2509
+ const results = await this.executeRaw(sql, bindings);
2510
+ return results.length ? results[0] : undefined;
2736
2511
  }
2737
2512
  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
- });
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;
2753
2528
  }
2754
- async registerOnTableChange(callback) {
2755
- return this.registerListener({
2756
- tablesUpdated: (event) => callback(event)
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
+ }
2757
2535
  });
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);
2536
+ api.reset(stmt);
2537
+ if (bindings) {
2538
+ api.bind_collection(stmt, bindings);
2539
+ }
2771
2540
  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);
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);
2779
2545
  }
2780
2546
  }
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
- }
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
+ \**********************************************/
2565
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2566
+
2567
+ __webpack_require__.r(__webpack_exports__);
2568
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2569
+ /* harmony export */ AsyncWASQLiteModuleFactory: () => (/* binding */ AsyncWASQLiteModuleFactory),
2570
+ /* harmony export */ DEFAULT_MODULE_FACTORIES: () => (/* binding */ DEFAULT_MODULE_FACTORIES),
2571
+ /* harmony export */ MultiCipherAsyncWASQLiteModuleFactory: () => (/* binding */ MultiCipherAsyncWASQLiteModuleFactory),
2572
+ /* harmony export */ MultiCipherSyncWASQLiteModuleFactory: () => (/* binding */ MultiCipherSyncWASQLiteModuleFactory),
2573
+ /* harmony export */ SyncWASQLiteModuleFactory: () => (/* binding */ SyncWASQLiteModuleFactory),
2574
+ /* harmony export */ WASQLiteVFS: () => (/* binding */ WASQLiteVFS),
2575
+ /* harmony export */ vfsRequiresDedicatedWorkers: () => (/* binding */ vfsRequiresDedicatedWorkers)
2576
+ /* harmony export */ });
2577
+ /**
2578
+ * List of currently tested virtual filesystems
2579
+ */
2580
+ var WASQLiteVFS;
2581
+ (function (WASQLiteVFS) {
2582
+ WASQLiteVFS["IDBBatchAtomicVFS"] = "IDBBatchAtomicVFS";
2583
+ WASQLiteVFS["OPFSCoopSyncVFS"] = "OPFSCoopSyncVFS";
2584
+ WASQLiteVFS["AccessHandlePoolVFS"] = "AccessHandlePoolVFS";
2585
+ })(WASQLiteVFS || (WASQLiteVFS = {}));
2586
+ function vfsRequiresDedicatedWorkers(vfs) {
2587
+ return vfs != WASQLiteVFS.IDBBatchAtomicVFS;
2588
+ }
2589
+ /**
2590
+ * @internal
2591
+ */
2592
+ const AsyncWASQLiteModuleFactory = async () => {
2593
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-cc5fcc").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs"));
2594
+ return factory();
2595
+ };
2596
+ /**
2597
+ * @internal
2598
+ */
2599
+ const MultiCipherAsyncWASQLiteModuleFactory = async () => {
2600
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-c99c07").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs"));
2601
+ return factory();
2602
+ };
2603
+ /**
2604
+ * @internal
2605
+ */
2606
+ const SyncWASQLiteModuleFactory = async () => {
2607
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite.mjs"));
2608
+ return factory();
2609
+ };
2610
+ /**
2611
+ * @internal
2612
+ */
2613
+ const MultiCipherSyncWASQLiteModuleFactory = async () => {
2614
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-b9c070").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs"));
2615
+ return factory();
2616
+ };
2617
+ /**
2618
+ * @internal
2619
+ */
2620
+ const DEFAULT_MODULE_FACTORIES = {
2621
+ [WASQLiteVFS.IDBBatchAtomicVFS]: async (options) => {
2622
+ let module;
2623
+ if (options.encryptionKey) {
2624
+ module = await MultiCipherAsyncWASQLiteModuleFactory();
2625
+ }
2626
+ else {
2627
+ module = await AsyncWASQLiteModuleFactory();
2628
+ }
2629
+ const { IDBBatchAtomicVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-0df390").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js"));
2630
+ return {
2631
+ module,
2632
+ // @ts-expect-error The types for this static method are missing upstream
2633
+ vfs: await IDBBatchAtomicVFS.create(options.dbFileName, module, { lockPolicy: 'exclusive' })
2788
2634
  };
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
- }
2635
+ },
2636
+ [WASQLiteVFS.AccessHandlePoolVFS]: async (options) => {
2637
+ let module;
2638
+ if (options.encryptionKey) {
2639
+ module = await MultiCipherSyncWASQLiteModuleFactory();
2828
2640
  }
2829
- return results;
2641
+ else {
2642
+ module = await SyncWASQLiteModuleFactory();
2643
+ }
2644
+ // @ts-expect-error The types for this static method are missing upstream
2645
+ const { AccessHandlePoolVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-151024").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js"));
2646
+ return {
2647
+ module,
2648
+ vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)
2649
+ };
2650
+ },
2651
+ [WASQLiteVFS.OPFSCoopSyncVFS]: async (options) => {
2652
+ let module;
2653
+ if (options.encryptionKey) {
2654
+ module = await MultiCipherSyncWASQLiteModuleFactory();
2655
+ }
2656
+ else {
2657
+ module = await SyncWASQLiteModuleFactory();
2658
+ }
2659
+ // @ts-expect-error The types for this static method are missing upstream
2660
+ const { OPFSCoopSyncVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-c01ef0").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js"));
2661
+ const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);
2662
+ return {
2663
+ module,
2664
+ vfs
2665
+ };
2830
2666
  }
2831
- }
2667
+ };
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
  /***/ },
@@ -3015,6 +2825,8 @@ __webpack_require__.r(__webpack_exports__);
3015
2825
  /* harmony export */ CrudBatch: () => (/* binding */ CrudBatch),
3016
2826
  /* harmony export */ CrudEntry: () => (/* binding */ CrudEntry),
3017
2827
  /* harmony export */ CrudTransaction: () => (/* binding */ CrudTransaction),
2828
+ /* harmony export */ DBAdapterDefaultMixin: () => (/* binding */ DBAdapterDefaultMixin),
2829
+ /* harmony export */ DBGetUtilsDefaultMixin: () => (/* binding */ DBGetUtilsDefaultMixin),
3018
2830
  /* harmony export */ DEFAULT_CRUD_BATCH_LIMIT: () => (/* binding */ DEFAULT_CRUD_BATCH_LIMIT),
3019
2831
  /* harmony export */ DEFAULT_CRUD_UPLOAD_THROTTLE_MS: () => (/* binding */ DEFAULT_CRUD_UPLOAD_THROTTLE_MS),
3020
2832
  /* harmony export */ DEFAULT_INDEX_COLUMN_OPTIONS: () => (/* binding */ DEFAULT_INDEX_COLUMN_OPTIONS),
@@ -3050,6 +2862,7 @@ __webpack_require__.r(__webpack_exports__);
3050
2862
  /* harmony export */ MAX_AMOUNT_OF_COLUMNS: () => (/* binding */ MAX_AMOUNT_OF_COLUMNS),
3051
2863
  /* harmony export */ MAX_OP_ID: () => (/* binding */ MAX_OP_ID),
3052
2864
  /* harmony export */ MEMORY_TRIGGER_CLAIM_MANAGER: () => (/* binding */ MEMORY_TRIGGER_CLAIM_MANAGER),
2865
+ /* harmony export */ Mutex: () => (/* binding */ Mutex),
3053
2866
  /* harmony export */ OnChangeQueryProcessor: () => (/* binding */ OnChangeQueryProcessor),
3054
2867
  /* harmony export */ OpType: () => (/* binding */ OpType),
3055
2868
  /* harmony export */ OpTypeEnum: () => (/* binding */ OpTypeEnum),
@@ -3091,15 +2904,12 @@ __webpack_require__.r(__webpack_exports__);
3091
2904
  /* harmony export */ isStreamingSyncCheckpointPartiallyComplete: () => (/* binding */ isStreamingSyncCheckpointPartiallyComplete),
3092
2905
  /* harmony export */ isStreamingSyncData: () => (/* binding */ isStreamingSyncData),
3093
2906
  /* harmony export */ isSyncNewCheckpointRequest: () => (/* binding */ isSyncNewCheckpointRequest),
3094
- /* harmony export */ mutexRunExclusive: () => (/* binding */ mutexRunExclusive),
3095
2907
  /* harmony export */ parseQuery: () => (/* binding */ parseQuery),
3096
2908
  /* harmony export */ runOnSchemaChange: () => (/* binding */ runOnSchemaChange),
3097
2909
  /* harmony export */ sanitizeSQL: () => (/* binding */ sanitizeSQL),
3098
- /* harmony export */ sanitizeUUID: () => (/* binding */ sanitizeUUID)
2910
+ /* harmony export */ sanitizeUUID: () => (/* binding */ sanitizeUUID),
2911
+ /* harmony export */ timeoutSignal: () => (/* binding */ timeoutSignal)
3099
2912
  /* harmony export */ });
3100
- /* 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");
3101
-
3102
-
3103
2913
  // https://www.sqlite.org/lang_expr.html#castexpr
3104
2914
  var ColumnType;
3105
2915
  (function (ColumnType) {
@@ -3757,7 +3567,7 @@ class SyncingService {
3757
3567
  updatedAttachments.push(downloaded);
3758
3568
  break;
3759
3569
  case AttachmentState.QUEUED_DELETE:
3760
- const deleted = await this.deleteAttachment(attachment);
3570
+ const deleted = await this.deleteAttachment(attachment, context);
3761
3571
  updatedAttachments.push(deleted);
3762
3572
  break;
3763
3573
  }
@@ -3835,17 +3645,16 @@ class SyncingService {
3835
3645
  * On failure, defers to error handler or archives.
3836
3646
  *
3837
3647
  * @param attachment - The attachment record to delete
3648
+ * @param context - Attachment context for database operations
3838
3649
  * @returns Updated attachment record
3839
3650
  */
3840
- async deleteAttachment(attachment) {
3651
+ async deleteAttachment(attachment, context) {
3841
3652
  try {
3842
3653
  await this.remoteStorage.deleteFile(attachment);
3843
3654
  if (attachment.localUri) {
3844
3655
  await this.localStorage.deleteFile(attachment.localUri);
3845
3656
  }
3846
- await this.attachmentService.withContext(async (ctx) => {
3847
- await ctx.deleteAttachment(attachment.id);
3848
- });
3657
+ await context.deleteAttachment(attachment.id);
3849
3658
  return {
3850
3659
  ...attachment,
3851
3660
  state: AttachmentState.ARCHIVED
@@ -3883,32 +3692,108 @@ class SyncingService {
3883
3692
  }
3884
3693
 
3885
3694
  /**
3886
- * 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.
3887
3698
  */
3888
- async function mutexRunExclusive(mutex, callback, options) {
3889
- return new Promise((resolve, reject) => {
3890
- const timeout = options?.timeoutMs;
3891
- let timedOut = false;
3892
- const timeoutId = timeout
3893
- ? setTimeout(() => {
3894
- timedOut = true;
3895
- reject(new Error('Timeout waiting for lock'));
3896
- }, timeout)
3897
- : undefined;
3898
- mutex.runExclusive(async () => {
3899
- if (timeoutId) {
3900
- 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'));
3901
3737
  }
3902
- if (timedOut)
3903
- return;
3904
- try {
3905
- resolve(await callback());
3738
+ if (abort?.aborted) {
3739
+ return rejectAborted();
3906
3740
  }
3907
- catch (ex) {
3908
- 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);
3909
3776
  }
3910
3777
  });
3911
- });
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;
3912
3797
  }
3913
3798
 
3914
3799
  /**
@@ -3920,7 +3805,7 @@ class AttachmentService {
3920
3805
  db;
3921
3806
  logger;
3922
3807
  tableName;
3923
- mutex = new async_mutex__WEBPACK_IMPORTED_MODULE_0__.Mutex();
3808
+ mutex = new Mutex();
3924
3809
  context;
3925
3810
  constructor(db, logger, tableName = 'attachments', archivedCacheLimit = 100) {
3926
3811
  this.db = db;
@@ -3957,7 +3842,7 @@ class AttachmentService {
3957
3842
  * Executes a callback with exclusive access to the attachment context.
3958
3843
  */
3959
3844
  async withContext(callback) {
3960
- return mutexRunExclusive(this.mutex, async () => {
3845
+ return this.mutex.runExclusive(async () => {
3961
3846
  return callback(this.context);
3962
3847
  });
3963
3848
  }
@@ -3993,9 +3878,15 @@ class AttachmentQueue {
3993
3878
  tableName;
3994
3879
  /** Logger instance for diagnostic information */
3995
3880
  logger;
3996
- /** 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) */
3997
3883
  syncIntervalMs = 30 * 1000;
3998
- /** 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) */
3999
3890
  syncThrottleDuration;
4000
3891
  /** Whether to automatically download remote attachments. Default: true */
4001
3892
  downloadAttachments = true;
@@ -4019,8 +3910,8 @@ class AttachmentQueue {
4019
3910
  * @param options.watchAttachments - Callback for monitoring attachment changes in your data model
4020
3911
  * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'
4021
3912
  * @param options.logger - Logger instance. Defaults to db.logger
4022
- * @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000
4023
- * @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
4024
3915
  * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true
4025
3916
  * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100
4026
3917
  */
@@ -4781,6 +4672,49 @@ var Logger = /*@__PURE__*/getDefaultExportFromCjs(loggerExports);
4781
4672
  * Set of generic interfaces to allow PowerSync compatibility with
4782
4673
  * different SQLite DB implementations.
4783
4674
  */
4675
+ /**
4676
+ * Implements {@link DBGetUtils} on a {@link SqlRunner}.
4677
+ */
4678
+ function DBGetUtilsDefaultMixin(Base) {
4679
+ return class extends Base {
4680
+ async getAll(sql, parameters) {
4681
+ const res = await this.execute(sql, parameters);
4682
+ return res.rows?._array ?? [];
4683
+ }
4684
+ async getOptional(sql, parameters) {
4685
+ const res = await this.execute(sql, parameters);
4686
+ return res.rows?.item(0) ?? null;
4687
+ }
4688
+ async get(sql, parameters) {
4689
+ const res = await this.execute(sql, parameters);
4690
+ const first = res.rows?.item(0);
4691
+ if (!first) {
4692
+ throw new Error('Result set is empty');
4693
+ }
4694
+ return first;
4695
+ }
4696
+ async executeBatch(query, params = []) {
4697
+ // If this context can run batch statements natively, use that.
4698
+ // @ts-ignore
4699
+ if (super.executeBatch) {
4700
+ // @ts-ignore
4701
+ return super.executeBatch(query, params);
4702
+ }
4703
+ // Emulate executeBatch by running statements individually.
4704
+ let lastInsertId;
4705
+ let rowsAffected = 0;
4706
+ for (const set of params) {
4707
+ const result = await this.execute(query, set);
4708
+ lastInsertId = result.insertId;
4709
+ rowsAffected += result.rowsAffected;
4710
+ }
4711
+ return {
4712
+ rowsAffected,
4713
+ insertId: lastInsertId
4714
+ };
4715
+ }
4716
+ };
4717
+ }
4784
4718
  /**
4785
4719
  * Update table operation numbers from SQLite
4786
4720
  */
@@ -4790,6 +4724,89 @@ var RowUpdateType;
4790
4724
  RowUpdateType[RowUpdateType["SQLITE_DELETE"] = 9] = "SQLITE_DELETE";
4791
4725
  RowUpdateType[RowUpdateType["SQLITE_UPDATE"] = 23] = "SQLITE_UPDATE";
4792
4726
  })(RowUpdateType || (RowUpdateType = {}));
4727
+ /**
4728
+ * A mixin to implement {@link DBAdapter} by delegating to {@link ConnectionPool.readLock} and
4729
+ * {@link ConnectionPool.writeLock}.
4730
+ */
4731
+ function DBAdapterDefaultMixin(Base) {
4732
+ return class extends Base {
4733
+ readTransaction(fn, options) {
4734
+ return this.readLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);
4735
+ }
4736
+ writeTransaction(fn, options) {
4737
+ return this.writeLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);
4738
+ }
4739
+ getAll(sql, parameters) {
4740
+ return this.readLock((ctx) => ctx.getAll(sql, parameters));
4741
+ }
4742
+ getOptional(sql, parameters) {
4743
+ return this.readLock((ctx) => ctx.getOptional(sql, parameters));
4744
+ }
4745
+ get(sql, parameters) {
4746
+ return this.readLock((ctx) => ctx.get(sql, parameters));
4747
+ }
4748
+ execute(query, params) {
4749
+ return this.writeLock((ctx) => ctx.execute(query, params));
4750
+ }
4751
+ executeRaw(query, params) {
4752
+ return this.writeLock((ctx) => ctx.executeRaw(query, params));
4753
+ }
4754
+ executeBatch(query, params) {
4755
+ return this.writeTransaction((tx) => tx.executeBatch(query, params));
4756
+ }
4757
+ };
4758
+ }
4759
+ class BaseTransaction {
4760
+ inner;
4761
+ finalized = false;
4762
+ constructor(inner) {
4763
+ this.inner = inner;
4764
+ }
4765
+ async commit() {
4766
+ if (this.finalized) {
4767
+ return { rowsAffected: 0 };
4768
+ }
4769
+ this.finalized = true;
4770
+ return this.inner.execute('COMMIT');
4771
+ }
4772
+ async rollback() {
4773
+ if (this.finalized) {
4774
+ return { rowsAffected: 0 };
4775
+ }
4776
+ this.finalized = true;
4777
+ return this.inner.execute('ROLLBACK');
4778
+ }
4779
+ execute(query, params) {
4780
+ return this.inner.execute(query, params);
4781
+ }
4782
+ executeRaw(query, params) {
4783
+ return this.inner.executeRaw(query, params);
4784
+ }
4785
+ executeBatch(query, params) {
4786
+ return this.inner.executeBatch(query, params);
4787
+ }
4788
+ }
4789
+ class TransactionImplementation extends DBGetUtilsDefaultMixin(BaseTransaction) {
4790
+ static async runWith(ctx, fn) {
4791
+ let tx = new TransactionImplementation(ctx);
4792
+ try {
4793
+ await ctx.execute('BEGIN IMMEDIATE');
4794
+ const result = await fn(tx);
4795
+ await tx.commit();
4796
+ return result;
4797
+ }
4798
+ catch (ex) {
4799
+ try {
4800
+ await tx.rollback();
4801
+ }
4802
+ catch (ex2) {
4803
+ // In rare cases, a rollback may fail.
4804
+ // Safe to ignore.
4805
+ }
4806
+ throw ex;
4807
+ }
4808
+ }
4809
+ }
4793
4810
  function isBatchedUpdateNotification(update) {
4794
4811
  return 'tables' in update;
4795
4812
  }
@@ -13555,7 +13572,7 @@ function requireDist () {
13555
13572
 
13556
13573
  var distExports = requireDist();
13557
13574
 
13558
- var version = "1.48.0";
13575
+ var version = "1.50.0";
13559
13576
  var PACKAGE = {
13560
13577
  version: version};
13561
13578
 
@@ -15588,7 +15605,7 @@ class TriggerManagerImpl {
15588
15605
  }
15589
15606
  async createDiffTrigger(options) {
15590
15607
  await this.db.waitForReady();
15591
- const { source, destination, columns, when, hooks,
15608
+ const { source, destination, columns, when, hooks, setupContext,
15592
15609
  // Fall back to the provided default if not given on this level
15593
15610
  useStorage = this.defaultConfig.useStorageByDefault } = options;
15594
15611
  const operations = Object.keys(when);
@@ -15643,13 +15660,20 @@ class TriggerManagerImpl {
15643
15660
  * we need to ensure we can cleanup the created resources.
15644
15661
  * We unfortunately cannot rely on transaction rollback.
15645
15662
  */
15646
- const cleanup = async () => {
15663
+ const cleanup = async (options) => {
15664
+ const { context } = options ?? {};
15647
15665
  disposeWarningListener();
15648
- return this.db.writeLock(async (tx) => {
15666
+ const doCleanup = async (tx) => {
15649
15667
  await this.removeTriggers(tx, triggerIds);
15650
- await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
15668
+ await tx.execute(`DROP TABLE IF EXISTS ${destination};`);
15651
15669
  await releaseStorageClaim?.();
15652
- });
15670
+ };
15671
+ if (context) {
15672
+ await doCleanup(context);
15673
+ }
15674
+ else {
15675
+ await this.db.writeLock(doCleanup);
15676
+ }
15653
15677
  };
15654
15678
  const setup = async (tx) => {
15655
15679
  // Allow user code to execute in this lock context before the trigger is created.
@@ -15723,12 +15747,17 @@ class TriggerManagerImpl {
15723
15747
  }
15724
15748
  };
15725
15749
  try {
15726
- await this.db.writeLock(setup);
15750
+ if (setupContext) {
15751
+ await setup(setupContext);
15752
+ }
15753
+ else {
15754
+ await this.db.writeLock(setup);
15755
+ }
15727
15756
  return cleanup;
15728
15757
  }
15729
15758
  catch (error) {
15730
15759
  try {
15731
- await cleanup();
15760
+ await cleanup(setupContext ? { context: setupContext } : undefined);
15732
15761
  }
15733
15762
  catch (cleanupError) {
15734
15763
  throw new AggregateError([error, cleanupError], 'Error during operation and cleanup');
@@ -15935,7 +15964,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
15935
15964
  this._schema = schema;
15936
15965
  this.ready = false;
15937
15966
  this.sdkVersion = '';
15938
- this.runExclusiveMutex = new async_mutex__WEBPACK_IMPORTED_MODULE_0__.Mutex();
15967
+ this.runExclusiveMutex = new Mutex();
15939
15968
  // Start async init
15940
15969
  this.subscriptions = {
15941
15970
  firstStatusMatching: (predicate, abort) => this.waitForStatus(predicate, abort),
@@ -16400,6 +16429,10 @@ SELECT * FROM crud_entries;
16400
16429
  * Execute a SQL write (INSERT/UPDATE/DELETE) query
16401
16430
  * and optionally return results.
16402
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
+ *
16403
16436
  * @param sql The SQL query to execute
16404
16437
  * @param parameters Optional array of parameters to bind to the query
16405
16438
  * @returns The query result as an object with structured key-value pairs
@@ -16496,7 +16529,7 @@ SELECT * FROM crud_entries;
16496
16529
  async readTransaction(callback, lockTimeout = DEFAULT_LOCK_TIMEOUT_MS) {
16497
16530
  await this.waitForReady();
16498
16531
  return this.database.readTransaction(async (tx) => {
16499
- const res = await callback({ ...tx });
16532
+ const res = await callback(tx);
16500
16533
  await tx.rollback();
16501
16534
  return res;
16502
16535
  }, { timeoutMs: lockTimeout });
@@ -17652,9 +17685,7 @@ __webpack_require__.r(__webpack_exports__);
17652
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");
17653
17686
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
17654
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");
17655
- /* harmony import */ var _shared_navigator_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/navigator.js */ "./lib/src/shared/navigator.js");
17656
- /* harmony import */ var _SharedWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SharedWASQLiteConnection.js */ "./lib/src/worker/db/SharedWASQLiteConnection.js");
17657
- /* 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");
17658
17689
  /**
17659
17690
  * Supports both shared and dedicated workers, based on how the worker is constructed (new SharedWorker vs new Worker()).
17660
17691
  */
@@ -17662,67 +17693,28 @@ __webpack_require__.r(__webpack_exports__);
17662
17693
 
17663
17694
 
17664
17695
 
17665
-
17666
-
17667
17696
  const baseLogger = (0,_powersync_common__WEBPACK_IMPORTED_MODULE_1__.createBaseLogger)();
17668
17697
  baseLogger.useDefaults();
17669
17698
  const logger = (0,_powersync_common__WEBPACK_IMPORTED_MODULE_1__.createLogger)('db-worker');
17670
- const DBMap = new Map();
17671
- const OPEN_DB_LOCK = 'open-wasqlite-db';
17672
- let nextClientId = 1;
17673
- const openDBShared = async (options) => {
17674
- // Prevent multiple simultaneous opens from causing race conditions
17675
- return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_3__.getNavigatorLocks)().request(OPEN_DB_LOCK, async () => {
17676
- const clientId = nextClientId++;
17677
- const { dbFilename, logLevel } = options;
17678
- logger.setLevel(logLevel);
17679
- if (!DBMap.has(dbFilename)) {
17680
- const clientIds = new Set();
17681
- // This format returns proxy objects for function callbacks
17682
- const connection = new _WorkerWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_5__.WorkerWASQLiteConnection(options);
17683
- await connection.init();
17684
- connection.registerListener({
17685
- holdOverwritten: async () => {
17686
- /**
17687
- * The previous hold has been overwritten, without being released.
17688
- * we need to cleanup any resources associated with it.
17689
- * We can perform a rollback to release any potential transactions that were started.
17690
- */
17691
- await connection.execute('ROLLBACK').catch(() => { });
17692
- }
17693
- });
17694
- DBMap.set(dbFilename, {
17695
- clientIds,
17696
- db: connection
17697
- });
17698
- }
17699
- // Associates this clientId with the shared connection entry
17700
- const sharedConnection = new _SharedWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_4__.SharedWASQLiteConnection({
17701
- dbMap: DBMap,
17702
- dbFilename,
17703
- clientId,
17704
- logger
17705
- });
17706
- return comlink__WEBPACK_IMPORTED_MODULE_2__.proxy(sharedConnection);
17707
- });
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)
17708
17703
  };
17709
17704
  // Check if we're in a SharedWorker context
17710
- if (typeof SharedWorkerGlobalScope !== 'undefined') {
17705
+ if (_MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__.isSharedWorker) {
17711
17706
  const _self = self;
17712
17707
  _self.onconnect = function (event) {
17713
17708
  const port = event.ports[0];
17714
- comlink__WEBPACK_IMPORTED_MODULE_2__.expose(openDBShared, port);
17709
+ comlink__WEBPACK_IMPORTED_MODULE_2__.expose(exposedFunctions, port);
17715
17710
  };
17716
17711
  }
17717
17712
  else {
17718
17713
  // A dedicated worker can be shared externally
17719
- comlink__WEBPACK_IMPORTED_MODULE_2__.expose(openDBShared);
17714
+ comlink__WEBPACK_IMPORTED_MODULE_2__.expose(exposedFunctions);
17720
17715
  }
17721
17716
  addEventListener('unload', () => {
17722
- Array.from(DBMap.values()).forEach(async (dbConnection) => {
17723
- const { db } = dbConnection;
17724
- db.close?.();
17725
- });
17717
+ server.closeAll();
17726
17718
  });
17727
17719
 
17728
17720
  })();