@powersync/web 0.0.0-dev-20260311103504 → 0.0.0-dev-20260503073249

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 (121) hide show
  1. package/dist/2075a31bb151adbb9767.wasm +0 -0
  2. package/dist/3322bc84de986b63c2cd.wasm +0 -0
  3. package/dist/8e97452e297be23b5e50.wasm +0 -0
  4. package/dist/fbc178b70d530e8ce02b.wasm +0 -0
  5. package/dist/index.umd.js +5341 -1279
  6. package/dist/index.umd.js.map +1 -1
  7. package/dist/worker/SharedSyncImplementation.umd.js +1113 -3526
  8. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
  9. package/dist/worker/WASQLiteDB.umd.js +1397 -1332
  10. package/dist/worker/WASQLiteDB.umd.js.map +1 -1
  11. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-9af0a7.umd.js +31 -0
  12. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-9af0a7.umd.js.map +1 -0
  13. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-bbf5a9.umd.js +31 -0
  14. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-bbf5a9.umd.js.map +1 -0
  15. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-c26e0f.umd.js +31 -0
  16. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-cc5fcc.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-c26e0f.umd.js.map} +1 -1
  17. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +31 -0
  18. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map} +1 -1
  19. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-2fb422.umd.js +3562 -0
  20. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-2fb422.umd.js.map +1 -0
  21. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-0df390.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-96fb23.umd.js} +16 -16
  22. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-0df390.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-96fb23.umd.js.map} +1 -1
  23. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-151024.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-c89911.umd.js} +12 -12
  24. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-151024.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-c89911.umd.js.map} +1 -1
  25. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-c01ef0.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-ec4eb1.umd.js} +14 -14
  26. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-c01ef0.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-ec4eb1.umd.js.map} +1 -1
  27. package/lib/package.json +4 -5
  28. package/lib/src/db/PowerSyncDatabase.d.ts +2 -3
  29. package/lib/src/db/PowerSyncDatabase.js +3 -12
  30. package/lib/src/db/adapters/AsyncWebAdapter.d.ts +50 -0
  31. package/lib/src/db/adapters/AsyncWebAdapter.js +163 -0
  32. package/lib/src/db/adapters/SSRDBAdapter.d.ts +1 -2
  33. package/lib/src/db/adapters/SSRDBAdapter.js +5 -6
  34. package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.d.ts +56 -0
  35. package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js +121 -0
  36. package/lib/src/db/adapters/wa-sqlite/DatabaseClient.d.ts +54 -0
  37. package/lib/src/db/adapters/wa-sqlite/DatabaseClient.js +227 -0
  38. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.d.ts +47 -0
  39. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.js +145 -0
  40. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.d.ts +46 -0
  41. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js +147 -0
  42. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +28 -6
  43. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +104 -55
  44. package/lib/src/db/adapters/wa-sqlite/vfs.d.ts +50 -0
  45. package/lib/src/db/adapters/wa-sqlite/vfs.js +76 -0
  46. package/lib/src/db/adapters/web-sql-flags.d.ts +5 -0
  47. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.d.ts +5 -2
  48. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.js +6 -3
  49. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +4 -19
  50. package/lib/src/index.d.ts +1 -4
  51. package/lib/src/index.js +1 -4
  52. package/lib/src/shared/tab_close_signal.d.ts +11 -0
  53. package/lib/src/shared/tab_close_signal.js +26 -0
  54. package/lib/src/worker/db/MultiDatabaseServer.d.ts +17 -0
  55. package/lib/src/worker/db/MultiDatabaseServer.js +89 -0
  56. package/lib/src/worker/db/WASQLiteDB.worker.js +9 -48
  57. package/lib/src/worker/db/open-worker-database.d.ts +3 -3
  58. package/lib/src/worker/db/open-worker-database.js +2 -2
  59. package/lib/src/worker/sync/SharedSyncImplementation.d.ts +5 -6
  60. package/lib/src/worker/sync/SharedSyncImplementation.js +88 -54
  61. package/lib/tsconfig.tsbuildinfo +1 -1
  62. package/package.json +5 -6
  63. package/src/db/PowerSyncDatabase.ts +4 -12
  64. package/src/db/adapters/AsyncWebAdapter.ts +207 -0
  65. package/src/db/adapters/SSRDBAdapter.ts +7 -7
  66. package/src/db/adapters/wa-sqlite/ConcurrentConnection.ts +137 -0
  67. package/src/db/adapters/wa-sqlite/DatabaseClient.ts +325 -0
  68. package/src/db/adapters/wa-sqlite/DatabaseServer.ts +203 -0
  69. package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +194 -0
  70. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +152 -63
  71. package/src/db/adapters/wa-sqlite/vfs.ts +96 -0
  72. package/src/db/adapters/web-sql-flags.ts +6 -0
  73. package/src/db/sync/SSRWebStreamingSyncImplementation.ts +7 -3
  74. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +4 -20
  75. package/src/index.ts +1 -4
  76. package/src/shared/tab_close_signal.ts +28 -0
  77. package/src/worker/db/MultiDatabaseServer.ts +107 -0
  78. package/src/worker/db/WASQLiteDB.worker.ts +10 -57
  79. package/src/worker/db/open-worker-database.ts +4 -4
  80. package/src/worker/sync/SharedSyncImplementation.ts +114 -58
  81. package/dist/26d61ca9f5694d064635.wasm +0 -0
  82. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js +0 -1878
  83. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js.map +0 -1
  84. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js +0 -555
  85. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js.map +0 -1
  86. package/dist/b4c6283dc473b6b3fd24.wasm +0 -0
  87. package/dist/c78985091a0b22aaef03.wasm +0 -0
  88. package/dist/ca59e199e1138b553fad.wasm +0 -0
  89. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-b9c070.umd.js +0 -31
  90. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-b9c070.umd.js.map +0 -1
  91. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-c99c07.umd.js +0 -31
  92. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-c99c07.umd.js.map +0 -1
  93. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-cc5fcc.umd.js +0 -31
  94. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +0 -31
  95. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.d.ts +0 -17
  96. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.js +0 -33
  97. package/lib/src/db/adapters/AsyncDatabaseConnection.d.ts +0 -49
  98. package/lib/src/db/adapters/AsyncDatabaseConnection.js +0 -1
  99. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.d.ts +0 -109
  100. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.js +0 -401
  101. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.d.ts +0 -59
  102. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js +0 -147
  103. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.d.ts +0 -12
  104. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.js +0 -19
  105. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.d.ts +0 -155
  106. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js +0 -401
  107. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.d.ts +0 -32
  108. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.js +0 -49
  109. package/lib/src/worker/db/SharedWASQLiteConnection.d.ts +0 -42
  110. package/lib/src/worker/db/SharedWASQLiteConnection.js +0 -90
  111. package/lib/src/worker/db/WorkerWASQLiteConnection.d.ts +0 -9
  112. package/lib/src/worker/db/WorkerWASQLiteConnection.js +0 -12
  113. package/src/db/adapters/AbstractWebSQLOpenFactory.ts +0 -48
  114. package/src/db/adapters/AsyncDatabaseConnection.ts +0 -55
  115. package/src/db/adapters/LockedAsyncDatabaseAdapter.ts +0 -490
  116. package/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.ts +0 -201
  117. package/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.ts +0 -23
  118. package/src/db/adapters/wa-sqlite/WASQLiteConnection.ts +0 -497
  119. package/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.ts +0 -86
  120. package/src/worker/db/SharedWASQLiteConnection.ts +0 -131
  121. 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 ***!
@@ -695,9 +384,9 @@ function generateUUID() {
695
384
 
696
385
  /***/ },
697
386
 
698
- /***/ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js"
387
+ /***/ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js"
699
388
  /*!*******************************************************************************************************************!*\
700
- !*** ../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js ***!
389
+ !*** ../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js ***!
701
390
  \*******************************************************************************************************************/
702
391
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
703
392
 
@@ -938,7 +627,7 @@ __webpack_require__.r(__webpack_exports__);
938
627
  /* harmony export */ SQLITE_WARNING: () => (/* reexport safe */ _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__.SQLITE_WARNING),
939
628
  /* harmony export */ SQLiteError: () => (/* binding */ SQLiteError)
940
629
  /* harmony export */ });
941
- /* harmony import */ var _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sqlite-constants.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js");
630
+ /* harmony import */ var _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sqlite-constants.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js");
942
631
  // Copyright 2021 Roy T. Hashimoto. All Rights Reserved.
943
632
 
944
633
 
@@ -980,6 +669,7 @@ function Factory(Module) {
980
669
  /** @type {SQLiteAPI} */ const sqlite3 = {};
981
670
 
982
671
  Module.retryOps = [];
672
+ Module.pendingOps = [];
983
673
  const sqliteFreeAddress = Module._getSqliteFree();
984
674
 
985
675
  // Allocate some space for 32-bit returned values.
@@ -1835,7 +1525,7 @@ function Factory(Module) {
1835
1525
  // succeed.
1836
1526
  async function retry(f) {
1837
1527
  let rc;
1838
- do {
1528
+ for (let retryCount = 0; retryCount < 2; ++retryCount) {
1839
1529
  // Wait for all pending retry operations to complete. This is
1840
1530
  // normally empty on the first loop iteration.
1841
1531
  if (Module.retryOps.length) {
@@ -1847,9 +1537,20 @@ function Factory(Module) {
1847
1537
  }
1848
1538
 
1849
1539
  rc = await f();
1850
-
1851
- // Retry on failure with new pending retry operations.
1852
- } while (rc && Module.retryOps.length);
1540
+ if (rc === _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__.SQLITE_OK || Module.retryOps.length === 0) {
1541
+ if (Module.pendingOps.length) {
1542
+ try {
1543
+ await Promise.all(Module.pendingOps);
1544
+ } catch (e) {
1545
+ console.error('Error in pendingOps:', e);
1546
+ return e.code || _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__.SQLITE_ERROR;
1547
+ } finally {
1548
+ Module.pendingOps = [];
1549
+ }
1550
+ }
1551
+ return rc;
1552
+ }
1553
+ }
1853
1554
  return rc;
1854
1555
  }
1855
1556
 
@@ -1890,9 +1591,9 @@ function decl(s) {
1890
1591
 
1891
1592
  /***/ },
1892
1593
 
1893
- /***/ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js"
1594
+ /***/ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js"
1894
1595
  /*!*************************************************************************************************************************!*\
1895
- !*** ../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js ***!
1596
+ !*** ../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js ***!
1896
1597
  \*************************************************************************************************************************/
1897
1598
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
1898
1599
 
@@ -2409,205 +2110,354 @@ const SQLITE_PREPARE_NO_VTAB = 0x04;
2409
2110
 
2410
2111
  /***/ },
2411
2112
 
2412
- /***/ "./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js"
2413
- /*!*************************************************************!*\
2414
- !*** ./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js ***!
2415
- \*************************************************************/
2113
+ /***/ "./lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js"
2114
+ /*!***************************************************************!*\
2115
+ !*** ./lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js ***!
2116
+ \***************************************************************/
2416
2117
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2417
2118
 
2418
2119
  __webpack_require__.r(__webpack_exports__);
2419
2120
  /* 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)
2121
+ /* harmony export */ ConcurrentSqliteConnection: () => (/* binding */ ConcurrentSqliteConnection),
2122
+ /* harmony export */ ConnectionLeaseToken: () => (/* binding */ ConnectionLeaseToken)
2427
2123
  /* 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");
2124
+ /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
2431
2125
 
2432
-
2433
-
2434
- /**
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
2126
  /**
2472
- * @internal
2127
+ * A wrapper around a {@link RawSqliteConnection} allowing multiple tabs to access it.
2128
+ *
2129
+ * To allow potentially concurrent accesses from different clients, this requires a local mutex implementation here.
2130
+ *
2131
+ * Note that instances of this class are not safe to proxy across context boundaries with comlink! We need to be able to
2132
+ * rely on mutexes being returned reliably, so additional checks to detect say a client tab closing are required to
2133
+ * avoid deadlocks.
2473
2134
  */
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();
2135
+ class ConcurrentSqliteConnection {
2136
+ inner;
2137
+ /**
2138
+ * An outer mutex ensuring at most one {@link ConnectionLeaseToken} can exist for this connection at a time.
2139
+ *
2140
+ * If null, we'll use navigator locks instead.
2141
+ */
2142
+ leaseMutex;
2143
+ /**
2144
+ * @param needsNavigatorLocks Whether access to the database needs an additional navigator lock guard.
2145
+ *
2146
+ * While {@link ConcurrentSqliteConnection} prevents concurrent access to a database _connection_, it's possible we
2147
+ * might have multiple connections to the same physical database (e.g. if multiple tabs use dedicated workers).
2148
+ * In those setups, we use navigator locks instead of an internal mutex to guard access..
2149
+ */
2150
+ constructor(inner, needsNavigatorLocks) {
2151
+ this.inner = inner;
2152
+ this.leaseMutex = needsNavigatorLocks ? null : new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.Mutex();
2153
+ }
2154
+ get options() {
2155
+ return this.inner.options;
2156
+ }
2157
+ acquireMutex(abort) {
2158
+ if (this.leaseMutex) {
2159
+ return this.leaseMutex.acquire(abort);
2482
2160
  }
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();
2161
+ return new Promise((resolve, reject) => {
2162
+ const options = { signal: abort };
2163
+ navigator.locks
2164
+ .request(`db-lock-${this.options.dbFilename}`, options, (_) => {
2165
+ return new Promise((returnLock) => {
2166
+ return resolve(() => {
2167
+ returnLock();
2168
+ });
2169
+ });
2170
+ })
2171
+ .catch(reject);
2172
+ });
2173
+ }
2174
+ // Unsafe, unguarded access to the SQLite connection.
2175
+ unsafeUseInner() {
2176
+ return this.inner;
2177
+ }
2178
+ /**
2179
+ * @returns A {@link ConnectionLeaseToken}. Until that token is returned, no other client can use the database.
2180
+ */
2181
+ async acquireConnection(abort) {
2182
+ const returnMutex = await this.acquireMutex(abort);
2183
+ const token = new ConnectionLeaseToken(returnMutex, this.inner);
2184
+ try {
2185
+ // Assert that the inner connection is initialized at this point, fail early if it's not.
2186
+ this.inner.requireSqlite();
2187
+ // If a previous client was interrupted in the middle of a transaction AND this is a shared worker, it's possible
2188
+ // for the connection to still be in a transaction. To avoid inconsistent state, we roll back connection leases
2189
+ // that haven't been comitted.
2190
+ if (!this.inner.isAutoCommit()) {
2191
+ await this.inner.executeRaw('ROLLBACK');
2192
+ }
2494
2193
  }
2495
- else {
2496
- module = await SyncWASQLiteModuleFactory();
2194
+ catch (e) {
2195
+ returnMutex();
2196
+ throw e;
2497
2197
  }
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();
2198
+ return token;
2199
+ }
2200
+ async close() {
2201
+ const returnMutex = await this.acquireMutex();
2202
+ try {
2203
+ await this.inner.close();
2509
2204
  }
2510
- else {
2511
- module = await SyncWASQLiteModuleFactory();
2205
+ finally {
2206
+ returnMutex();
2512
2207
  }
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
2208
  }
2521
- };
2209
+ }
2522
2210
  /**
2523
- * @internal
2524
- * WA-SQLite connection which directly interfaces with WA-SQLite.
2525
- * This is usually instantiated inside a worker.
2211
+ * An instance representing temporary exclusive access to a {@link ConcurrentSqliteConnection}.
2526
2212
  */
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;
2213
+ class ConnectionLeaseToken {
2214
+ returnMutex;
2215
+ connection;
2216
+ /** Ensures that the client with access to this token can't run statements concurrently. */
2217
+ useMutex = new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.Mutex();
2218
+ closed = false;
2219
+ constructor(returnMutex, connection) {
2220
+ this.returnMutex = returnMutex;
2221
+ this.connection = connection;
2222
+ }
2536
2223
  /**
2537
- * Unique id for this specific connection. This is used to prevent broadcast table change
2538
- * notification loops.
2224
+ * Returns this lease, allowing another client to use the database connection.
2539
2225
  */
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;
2226
+ async returnLease() {
2227
+ await this.useMutex.runExclusive(async () => {
2228
+ if (!this.closed) {
2229
+ this.closed = true;
2230
+ this.returnMutex();
2231
+ }
2232
+ });
2554
2233
  }
2555
2234
  /**
2556
- * Gets the id for the current hold.
2557
- * This can be used to check for invalid states.
2235
+ * This should only be used internally, since the callback must not use the raw connection after resolving.
2558
2236
  */
2559
- get currentHoldId() {
2560
- return this._holdId;
2237
+ async use(callback) {
2238
+ return await this.useMutex.runExclusive(async () => {
2239
+ if (this.closed) {
2240
+ throw new Error('lease token has already been closed');
2241
+ }
2242
+ return await callback(this.connection);
2243
+ });
2561
2244
  }
2562
- get sqliteAPI() {
2563
- if (!this._sqliteAPI) {
2564
- throw new Error(`Initialization has not completed`);
2565
- }
2566
- return this._sqliteAPI;
2245
+ }
2246
+
2247
+
2248
+ /***/ },
2249
+
2250
+ /***/ "./lib/src/db/adapters/wa-sqlite/DatabaseServer.js"
2251
+ /*!*********************************************************!*\
2252
+ !*** ./lib/src/db/adapters/wa-sqlite/DatabaseServer.js ***!
2253
+ \*********************************************************/
2254
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2255
+
2256
+ __webpack_require__.r(__webpack_exports__);
2257
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2258
+ /* harmony export */ DatabaseServer: () => (/* binding */ DatabaseServer)
2259
+ /* harmony export */ });
2260
+ /**
2261
+ * Access to a WA-sqlite connection that can be shared with multiple clients sending queries over an RPC protocol built
2262
+ * with the Comlink package.
2263
+ */
2264
+ class DatabaseServer {
2265
+ #options;
2266
+ #nextClientId = 0;
2267
+ #activeClients = new Set();
2268
+ // TODO: Don't use a broadcast channel for connections managed by a shared worker.
2269
+ #updateBroadcastChannel;
2270
+ #clientTableListeners = new Set();
2271
+ constructor(options) {
2272
+ this.#options = options;
2273
+ const inner = options.inner;
2274
+ this.#updateBroadcastChannel = new BroadcastChannel(`${inner.options.dbFilename}-table-updates`);
2275
+ this.#updateBroadcastChannel.onmessage = ({ data }) => {
2276
+ this.#pushTableUpdateToClients(data);
2277
+ };
2567
2278
  }
2568
- get dbP() {
2569
- if (!this._dbP) {
2570
- throw new Error(`Initialization has not completed`);
2279
+ #pushTableUpdateToClients(changedTables) {
2280
+ for (const listener of this.#clientTableListeners) {
2281
+ listener.postMessage(changedTables);
2571
2282
  }
2572
- return this._dbP;
2283
+ }
2284
+ get #inner() {
2285
+ return this.#options.inner;
2286
+ }
2287
+ get #logger() {
2288
+ return this.#options.logger;
2573
2289
  }
2574
2290
  /**
2575
- * Checks if the database connection is in autocommit mode.
2576
- * @returns true if in autocommit mode, false if in a transaction
2291
+ * Called by clients when they wish to connect to this database.
2292
+ *
2293
+ * @param lockName A lock that is currently held by the client. When the lock is returned, we know the client is gone
2294
+ * and that we need to clean up resources.
2577
2295
  */
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));
2296
+ async connect(lockName) {
2297
+ let isOpen = true;
2298
+ const clientId = this.#nextClientId++;
2299
+ this.#activeClients.add(clientId);
2300
+ let connectionLeases = new Map();
2301
+ let currentTableListener;
2302
+ function requireOpen() {
2303
+ if (!isOpen) {
2304
+ throw new Error('Client has already been closed');
2305
+ }
2586
2306
  }
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}`);
2307
+ function requireOpenAndLease(lease) {
2308
+ requireOpen();
2309
+ const token = connectionLeases.get(lease);
2310
+ if (!token) {
2311
+ throw new Error('Attempted to use a connection lease that has already been returned.');
2312
+ }
2313
+ return token;
2592
2314
  }
2593
- this._holdId = null;
2315
+ const close = async () => {
2316
+ if (isOpen) {
2317
+ isOpen = false;
2318
+ if (currentTableListener) {
2319
+ this.#clientTableListeners.delete(currentTableListener);
2320
+ }
2321
+ // If the client holds a connection lease it hasn't returned, return that now.
2322
+ for (const { lease } of connectionLeases.values()) {
2323
+ this.#logger.debug(`Closing connection lease that hasn't been returned.`);
2324
+ await lease.returnLease();
2325
+ }
2326
+ this.#activeClients.delete(clientId);
2327
+ if (this.#activeClients.size == 0) {
2328
+ await this.forceClose();
2329
+ }
2330
+ else {
2331
+ this.#logger.debug('Keeping underlying connection active since its used by other clients.');
2332
+ }
2333
+ }
2334
+ };
2335
+ if (lockName) {
2336
+ navigator.locks.request(lockName, {}, () => {
2337
+ close();
2338
+ });
2339
+ }
2340
+ return {
2341
+ close,
2342
+ debugIsAutoCommit: async () => {
2343
+ return this.#inner.unsafeUseInner().isAutoCommit();
2344
+ },
2345
+ requestAccess: async (write, timeoutMs) => {
2346
+ requireOpen();
2347
+ const lease = await this.#inner.acquireConnection(timeoutMs != null ? AbortSignal.timeout(timeoutMs) : undefined);
2348
+ if (!isOpen) {
2349
+ // Race between requestAccess and close(), the connection was closed while we tried to acquire a lease.
2350
+ await lease.returnLease();
2351
+ return requireOpen();
2352
+ }
2353
+ const token = crypto.randomUUID();
2354
+ connectionLeases.set(token, { lease, write });
2355
+ return token;
2356
+ },
2357
+ completeAccess: async (token) => {
2358
+ const lease = requireOpenAndLease(token);
2359
+ connectionLeases.delete(token);
2360
+ try {
2361
+ if (lease.write) {
2362
+ // Collect update hooks invoked while the client had the write connection.
2363
+ const { resultSet } = await lease.lease.use((conn) => conn.execute(`SELECT powersync_update_hooks('get')`));
2364
+ if (resultSet) {
2365
+ const updatedTables = JSON.parse(resultSet.rows[0][0]);
2366
+ if (updatedTables.length) {
2367
+ this.#updateBroadcastChannel.postMessage(updatedTables);
2368
+ this.#pushTableUpdateToClients(updatedTables);
2369
+ }
2370
+ }
2371
+ }
2372
+ }
2373
+ finally {
2374
+ await lease.lease.returnLease();
2375
+ }
2376
+ },
2377
+ execute: async (token, sql, params) => {
2378
+ const { lease } = requireOpenAndLease(token);
2379
+ return await lease.use((db) => db.execute(sql, params));
2380
+ },
2381
+ executeBatch: async (token, sql, params) => {
2382
+ const { lease } = requireOpenAndLease(token);
2383
+ return await lease.use((db) => db.executeBatch(sql, params));
2384
+ },
2385
+ setUpdateListener: async (listener) => {
2386
+ requireOpen();
2387
+ if (currentTableListener) {
2388
+ this.#clientTableListeners.delete(currentTableListener);
2389
+ }
2390
+ currentTableListener = listener;
2391
+ if (listener) {
2392
+ this.#clientTableListeners.add(listener);
2393
+ }
2394
+ }
2395
+ };
2594
2396
  }
2595
- async openDB() {
2596
- this._dbP = await this.sqliteAPI.open_v2(this.options.dbFilename);
2597
- return this._dbP;
2397
+ async forceClose() {
2398
+ this.#logger.debug(`Closing connection to ${this.#inner.options}.`);
2399
+ const connection = this.#inner;
2400
+ this.#options.onClose();
2401
+ this.#updateBroadcastChannel.close();
2402
+ await connection.close();
2598
2403
  }
2599
- async executeEncryptionPragma() {
2404
+ }
2405
+
2406
+
2407
+ /***/ },
2408
+
2409
+ /***/ "./lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js"
2410
+ /*!**************************************************************!*\
2411
+ !*** ./lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js ***!
2412
+ \**************************************************************/
2413
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2414
+
2415
+ __webpack_require__.r(__webpack_exports__);
2416
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2417
+ /* harmony export */ RawSqliteConnection: () => (/* binding */ RawSqliteConnection)
2418
+ /* harmony export */ });
2419
+ /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
2420
+ /* harmony import */ var _vfs_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vfs.js */ "./lib/src/db/adapters/wa-sqlite/vfs.js");
2421
+
2422
+
2423
+ /**
2424
+ * A small wrapper around WA-sqlite to help with opening databases and running statements by preparing them internally.
2425
+ *
2426
+ * This is an internal class, and it must never be used directly. Wrappers are required to ensure raw connections aren't
2427
+ * used concurrently across tabs.
2428
+ */
2429
+ class RawSqliteConnection {
2430
+ options;
2431
+ _sqliteAPI = null;
2432
+ /**
2433
+ * The `sqlite3*` connection pointer.
2434
+ */
2435
+ db = 0;
2436
+ _moduleFactory;
2437
+ constructor(options) {
2438
+ this.options = options;
2439
+ this._moduleFactory = _vfs_js__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_MODULE_FACTORIES[this.options.vfs];
2440
+ }
2441
+ get isOpen() {
2442
+ return this.db != 0;
2443
+ }
2444
+ async init() {
2445
+ const api = (this._sqliteAPI = await this.openSQLiteAPI());
2446
+ this.db = await api.open_v2(this.options.dbFilename, this.options.isReadOnly ? 1 /* SQLITE_OPEN_READONLY */ : 6 /* SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE */);
2447
+ await this.executeRaw(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
2600
2448
  if (this.options.encryptionKey) {
2601
- await this.executeSingleStatement(`PRAGMA key = "${this.options.encryptionKey}"`);
2449
+ const escapedKey = this.options.encryptionKey.replace("'", "''");
2450
+ await this.executeRaw(`PRAGMA key = '${escapedKey}'`);
2602
2451
  }
2603
- return;
2452
+ await this.executeRaw(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);
2453
+ await this.executeRaw(`SELECT powersync_update_hooks('install');`);
2604
2454
  }
2605
2455
  async openSQLiteAPI() {
2606
2456
  const { module, vfs } = await this._moduleFactory({
2607
2457
  dbFileName: this.options.dbFilename,
2608
2458
  encryptionKey: this.options.encryptionKey
2609
2459
  });
2610
- const sqlite3 = _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.Factory(module);
2460
+ const sqlite3 = (0,_journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.Factory)(module);
2611
2461
  sqlite3.vfs_register(vfs, true);
2612
2462
  /**
2613
2463
  * Register the PowerSync core SQLite extension
@@ -2624,202 +2474,61 @@ class WASqliteConnection extends _powersync_common__WEBPACK_IMPORTED_MODULE_1__.
2624
2474
  }
2625
2475
  return sqlite3;
2626
2476
  }
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
- });
2477
+ requireSqlite() {
2478
+ if (!this._sqliteAPI) {
2479
+ throw new Error(`Initialization has not completed`);
2672
2480
  }
2673
- this.updatedTables.clear();
2674
- this.iterateListeners((cb) => cb.tablesUpdated?.(event));
2481
+ return this._sqliteAPI;
2675
2482
  }
2676
2483
  /**
2677
- * This executes SQL statements in a batch.
2484
+ * Checks if the database connection is in autocommit mode.
2485
+ * @returns true if in autocommit mode, false if in a transaction
2678
2486
  */
2679
- async executeBatch(sql, bindings) {
2680
- return this.acquireExecuteLock(async () => {
2681
- let affectedRows = 0;
2682
- try {
2683
- await this.executeSingleStatement('BEGIN TRANSACTION');
2684
- const wrappedBindings = bindings ? bindings : [];
2685
- for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {
2686
- if (stmt === null) {
2687
- return {
2688
- rowsAffected: 0,
2689
- rows: { _array: [], length: 0 }
2690
- };
2691
- }
2692
- //Prepare statement once
2693
- for (const binding of wrappedBindings) {
2694
- // TODO not sure why this is needed currently, but booleans break
2695
- for (let i = 0; i < binding.length; i++) {
2696
- const b = binding[i];
2697
- if (typeof b == 'boolean') {
2698
- binding[i] = b ? 1 : 0;
2699
- }
2700
- }
2701
- if (bindings) {
2702
- this.sqliteAPI.bind_collection(stmt, binding);
2703
- }
2704
- const result = await this.sqliteAPI.step(stmt);
2705
- if (result === _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.SQLITE_DONE) {
2706
- //The value returned by sqlite3_changes() immediately after an INSERT, UPDATE or DELETE statement run on a view is always zero.
2707
- affectedRows += this.sqliteAPI.changes(this.dbP);
2708
- }
2709
- this.sqliteAPI.reset(stmt);
2710
- }
2711
- }
2712
- await this.executeSingleStatement('COMMIT');
2713
- }
2714
- catch (err) {
2715
- await this.executeSingleStatement('ROLLBACK');
2716
- return {
2717
- rowsAffected: 0,
2718
- rows: { _array: [], length: 0 }
2719
- };
2720
- }
2721
- const result = {
2722
- rowsAffected: affectedRows,
2723
- rows: { _array: [], length: 0 }
2724
- };
2725
- return result;
2726
- });
2487
+ isAutoCommit() {
2488
+ return this.requireSqlite().get_autocommit(this.db) != 0;
2727
2489
  }
2728
- /**
2729
- * This executes single SQL statements inside a requested lock.
2730
- */
2731
2490
  async execute(sql, bindings) {
2732
- // Running multiple statements on the same connection concurrently should not be allowed
2733
- return this.acquireExecuteLock(async () => {
2734
- return this.executeSingleStatement(sql, bindings);
2735
- });
2736
- }
2737
- async executeRaw(sql, bindings) {
2738
- return this.acquireExecuteLock(async () => {
2739
- return this.executeSingleStatementRaw(sql, bindings);
2740
- });
2741
- }
2742
- async close() {
2743
- this.broadcastChannel?.close();
2744
- await this.acquireExecuteLock(async () => {
2745
- /**
2746
- * Running the close operation inside the same execute mutex prevents errors like:
2747
- * ```
2748
- * unable to close due to unfinalized statements or unfinished backups
2749
- * ```
2750
- */
2751
- await this.sqliteAPI.close(this.dbP);
2752
- });
2491
+ const resultSet = await this.executeSingleStatementRaw(sql, bindings);
2492
+ return this.wrapQueryResults(this.requireSqlite(), resultSet);
2753
2493
  }
2754
- async registerOnTableChange(callback) {
2755
- return this.registerListener({
2756
- tablesUpdated: (event) => callback(event)
2757
- });
2758
- }
2759
- /**
2760
- * This requests a lock for executing statements.
2761
- * Should only be used internally.
2762
- */
2763
- acquireExecuteLock = (callback) => {
2764
- return this.statementMutex.runExclusive(callback);
2765
- };
2766
- /**
2767
- * This executes a single statement using SQLite3.
2768
- */
2769
- async executeSingleStatement(sql, bindings) {
2770
- const results = await this._execute(sql, bindings);
2771
- const rows = [];
2772
- for (const resultSet of results) {
2773
- for (const row of resultSet.rows) {
2774
- const outRow = {};
2775
- resultSet.columns.forEach((key, index) => {
2776
- outRow[key] = row[index];
2777
- });
2778
- rows.push(outRow);
2494
+ async executeBatch(sql, bindings) {
2495
+ const results = [];
2496
+ const api = this.requireSqlite();
2497
+ for await (const stmt of api.statements(this.db, sql)) {
2498
+ let columns;
2499
+ for (const parameterSet of bindings) {
2500
+ const rs = await this.stepThroughStatement(api, stmt, parameterSet, columns, false);
2501
+ results.push(this.wrapQueryResults(api, rs));
2779
2502
  }
2503
+ // executeBatch can only use a single statement
2504
+ break;
2780
2505
  }
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
- }
2506
+ return results;
2507
+ }
2508
+ wrapQueryResults(api, rs) {
2509
+ return {
2510
+ changes: api.changes(this.db),
2511
+ lastInsertRowId: api.last_insert_id(this.db),
2512
+ autocommit: api.get_autocommit(this.db) != 0,
2513
+ resultSet: rs
2788
2514
  };
2789
- return result;
2790
2515
  }
2791
2516
  /**
2792
- * This executes a single statement using SQLite3 and returns the results as an array of arrays.
2517
+ * This executes a single statement using SQLite3 and returns the results as a {@link RawResultSet}.
2793
2518
  */
2794
2519
  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])));
2520
+ const results = await this.executeRaw(sql, bindings);
2521
+ return results.length ? results[0] : undefined;
2797
2522
  }
2798
- async _execute(sql, bindings) {
2523
+ async executeRaw(sql, bindings) {
2799
2524
  const results = [];
2800
- for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {
2525
+ const api = this.requireSqlite();
2526
+ for await (const stmt of api.statements(this.db, sql)) {
2801
2527
  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
- }
2528
+ const rs = await this.stepThroughStatement(api, stmt, bindings ?? [], columns);
2529
+ columns = rs.columns;
2530
+ if (columns.length) {
2531
+ results.push(rs);
2823
2532
  }
2824
2533
  // When binding parameters, only a single statement is executed.
2825
2534
  if (bindings) {
@@ -2828,159 +2537,255 @@ class WASqliteConnection extends _powersync_common__WEBPACK_IMPORTED_MODULE_1__.
2828
2537
  }
2829
2538
  return results;
2830
2539
  }
2831
- }
2832
-
2833
-
2834
- /***/ },
2835
-
2836
- /***/ "./lib/src/shared/navigator.js"
2837
- /*!*************************************!*\
2838
- !*** ./lib/src/shared/navigator.js ***!
2839
- \*************************************/
2840
- (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2841
-
2842
- __webpack_require__.r(__webpack_exports__);
2843
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2844
- /* harmony export */ getNavigatorLocks: () => (/* binding */ getNavigatorLocks)
2845
- /* harmony export */ });
2846
- const getNavigatorLocks = () => {
2847
- if ('locks' in navigator && navigator.locks) {
2848
- return navigator.locks;
2540
+ async stepThroughStatement(api, stmt, bindings, knownColumns, includeResults = true) {
2541
+ // TODO not sure why this is needed currently, but booleans break
2542
+ bindings.forEach((b, index, arr) => {
2543
+ if (typeof b == 'boolean') {
2544
+ arr[index] = b ? 1 : 0;
2545
+ }
2546
+ });
2547
+ api.reset(stmt);
2548
+ if (bindings) {
2549
+ api.bind_collection(stmt, bindings);
2550
+ }
2551
+ const rows = [];
2552
+ while ((await api.step(stmt)) === _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.SQLITE_ROW) {
2553
+ if (includeResults) {
2554
+ const row = api.row(stmt);
2555
+ rows.push(row);
2556
+ }
2557
+ }
2558
+ knownColumns ??= api.column_names(stmt);
2559
+ return { columns: knownColumns, rows };
2849
2560
  }
2850
- throw new Error('Navigator locks are not available in an insecure context. Use a secure context such as HTTPS or http://localhost.');
2851
- };
2561
+ async close() {
2562
+ if (this.isOpen) {
2563
+ await this.requireSqlite().close(this.db);
2564
+ this.db = 0;
2565
+ }
2566
+ }
2567
+ }
2852
2568
 
2853
2569
 
2854
2570
  /***/ },
2855
2571
 
2856
- /***/ "./lib/src/worker/db/SharedWASQLiteConnection.js"
2857
- /*!*******************************************************!*\
2858
- !*** ./lib/src/worker/db/SharedWASQLiteConnection.js ***!
2859
- \*******************************************************/
2572
+ /***/ "./lib/src/db/adapters/wa-sqlite/vfs.js"
2573
+ /*!**********************************************!*\
2574
+ !*** ./lib/src/db/adapters/wa-sqlite/vfs.js ***!
2575
+ \**********************************************/
2860
2576
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2861
2577
 
2862
2578
  __webpack_require__.r(__webpack_exports__);
2863
2579
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2864
- /* harmony export */ SharedWASQLiteConnection: () => (/* binding */ SharedWASQLiteConnection)
2580
+ /* harmony export */ DEFAULT_MODULE_FACTORIES: () => (/* binding */ DEFAULT_MODULE_FACTORIES),
2581
+ /* harmony export */ WASQLiteVFS: () => (/* binding */ WASQLiteVFS),
2582
+ /* harmony export */ vfsRequiresDedicatedWorkers: () => (/* binding */ vfsRequiresDedicatedWorkers)
2865
2583
  /* 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();
2584
+ /**
2585
+ * List of currently tested virtual filesystems
2586
+ */
2587
+ var WASQLiteVFS;
2588
+ (function (WASQLiteVFS) {
2589
+ WASQLiteVFS["IDBBatchAtomicVFS"] = "IDBBatchAtomicVFS";
2590
+ WASQLiteVFS["OPFSCoopSyncVFS"] = "OPFSCoopSyncVFS";
2591
+ WASQLiteVFS["AccessHandlePoolVFS"] = "AccessHandlePoolVFS";
2592
+ WASQLiteVFS["OPFSWriteAheadVFS"] = "OPFSWriteAheadVFS";
2593
+ })(WASQLiteVFS || (WASQLiteVFS = {}));
2594
+ function vfsRequiresDedicatedWorkers(vfs) {
2595
+ return vfs != WASQLiteVFS.IDBBatchAtomicVFS;
2596
+ }
2597
+ async function asyncModuleFactory(encryptionKey) {
2598
+ if (encryptionKey) {
2599
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-9af0a7").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs"));
2600
+ return factory();
2939
2601
  }
2940
- async execute(sql, params) {
2941
- return this.withClosing(() => this.connection.execute(sql, params));
2602
+ else {
2603
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-c26e0f").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs"));
2604
+ return factory();
2942
2605
  }
2943
- async executeRaw(sql, params) {
2944
- return this.withClosing(() => this.connection.executeRaw(sql, params));
2606
+ }
2607
+ async function syncModuleFactory(encryptionKey) {
2608
+ if (encryptionKey) {
2609
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-bbf5a9").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs"));
2610
+ return factory();
2945
2611
  }
2946
- executeBatch(sql, params) {
2947
- return this.withClosing(() => this.connection.executeBatch(sql, params));
2612
+ else {
2613
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_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.7.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite.mjs"));
2614
+ return factory();
2948
2615
  }
2949
- registerOnTableChange(callback) {
2950
- return this.connection.registerOnTableChange(callback);
2616
+ }
2617
+ /**
2618
+ * @internal
2619
+ */
2620
+ const DEFAULT_MODULE_FACTORIES = {
2621
+ [WASQLiteVFS.IDBBatchAtomicVFS]: async (options) => {
2622
+ const module = await asyncModuleFactory(options.encryptionKey);
2623
+ const { IDBBatchAtomicVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-96fb23").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js"));
2624
+ return {
2625
+ module,
2626
+ // @ts-expect-error The types for this static method are missing upstream
2627
+ vfs: await IDBBatchAtomicVFS.create(options.dbFileName, module, { lockPolicy: 'exclusive' })
2628
+ };
2629
+ },
2630
+ [WASQLiteVFS.AccessHandlePoolVFS]: async (options) => {
2631
+ const module = await syncModuleFactory(options.encryptionKey);
2632
+ // @ts-expect-error The types for this static method are missing upstream
2633
+ const { AccessHandlePoolVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-c89911").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js"));
2634
+ return {
2635
+ module,
2636
+ vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)
2637
+ };
2638
+ },
2639
+ [WASQLiteVFS.OPFSCoopSyncVFS]: async (options) => {
2640
+ const module = await syncModuleFactory(options.encryptionKey);
2641
+ // @ts-expect-error The types for this static method are missing upstream
2642
+ const { OPFSCoopSyncVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-ec4eb1").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js"));
2643
+ const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);
2644
+ return {
2645
+ module,
2646
+ vfs
2647
+ };
2648
+ },
2649
+ [WASQLiteVFS.OPFSWriteAheadVFS]: async (options) => {
2650
+ const module = await syncModuleFactory(options.encryptionKey);
2651
+ // @ts-expect-error The types for this static method are missing upstream
2652
+ const { OPFSWriteAheadVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-2fb422").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/OPFSWriteAheadVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSWriteAheadVFS.js"));
2653
+ const vfs = await OPFSWriteAheadVFS.create(options.dbFileName, module, {});
2654
+ return {
2655
+ module,
2656
+ vfs
2657
+ };
2951
2658
  }
2952
- getConfig() {
2953
- return this.connection.getConfig();
2659
+ };
2660
+
2661
+
2662
+ /***/ },
2663
+
2664
+ /***/ "./lib/src/shared/navigator.js"
2665
+ /*!*************************************!*\
2666
+ !*** ./lib/src/shared/navigator.js ***!
2667
+ \*************************************/
2668
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2669
+
2670
+ __webpack_require__.r(__webpack_exports__);
2671
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2672
+ /* harmony export */ getNavigatorLocks: () => (/* binding */ getNavigatorLocks)
2673
+ /* harmony export */ });
2674
+ const getNavigatorLocks = () => {
2675
+ if ('locks' in navigator && navigator.locks) {
2676
+ return navigator.locks;
2954
2677
  }
2955
- }
2678
+ throw new Error('Navigator locks are not available in an insecure context. Use a secure context such as HTTPS or http://localhost.');
2679
+ };
2956
2680
 
2957
2681
 
2958
2682
  /***/ },
2959
2683
 
2960
- /***/ "./lib/src/worker/db/WorkerWASQLiteConnection.js"
2961
- /*!*******************************************************!*\
2962
- !*** ./lib/src/worker/db/WorkerWASQLiteConnection.js ***!
2963
- \*******************************************************/
2684
+ /***/ "./lib/src/worker/db/MultiDatabaseServer.js"
2685
+ /*!**************************************************!*\
2686
+ !*** ./lib/src/worker/db/MultiDatabaseServer.js ***!
2687
+ \**************************************************/
2964
2688
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2965
2689
 
2966
2690
  __webpack_require__.r(__webpack_exports__);
2967
2691
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2968
- /* harmony export */ WorkerWASQLiteConnection: () => (/* binding */ WorkerWASQLiteConnection)
2692
+ /* harmony export */ MultiDatabaseServer: () => (/* binding */ MultiDatabaseServer),
2693
+ /* harmony export */ isSharedWorker: () => (/* binding */ isSharedWorker)
2969
2694
  /* harmony export */ });
2970
2695
  /* 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");
2696
+ /* 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");
2697
+ /* harmony import */ var _shared_navigator_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../shared/navigator.js */ "./lib/src/shared/navigator.js");
2698
+ /* 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");
2699
+ /* 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");
2700
+
2972
2701
 
2973
2702
 
2703
+
2704
+
2705
+ const OPEN_DB_LOCK = 'open-wasqlite-db';
2974
2706
  /**
2975
- * A Small proxy wrapper around the WASqliteConnection.
2976
- * This ensures that certain return types are properly proxied.
2707
+ * Shared state to manage multiple database connections hosted by a worker.
2977
2708
  */
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));
2709
+ class MultiDatabaseServer {
2710
+ logger;
2711
+ activeDatabases = new Map();
2712
+ constructor(logger) {
2713
+ this.logger = logger;
2714
+ }
2715
+ async handleConnection(options) {
2716
+ this.logger.setLevel(options.logLevel);
2717
+ return comlink__WEBPACK_IMPORTED_MODULE_0__.proxy(await this.openConnectionLocally(options, options.lockName));
2718
+ }
2719
+ async connectToExisting(name, lockName) {
2720
+ return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_2__.getNavigatorLocks)().request(OPEN_DB_LOCK, async () => {
2721
+ const server = this.activeDatabases.get(name);
2722
+ if (server == null) {
2723
+ throw new Error(`connectToExisting(${name}) failed because the worker doesn't own a database with that name.`);
2724
+ }
2725
+ return comlink__WEBPACK_IMPORTED_MODULE_0__.proxy(await server.connect(lockName));
2726
+ });
2727
+ }
2728
+ async openConnectionLocally(options, lockName) {
2729
+ // Especially on Firefox, we're sometimes seeing "NoModificationAllowedError"s when opening OPFS databases we can
2730
+ // work around by retrying.
2731
+ const maxAttempts = 3;
2732
+ let server;
2733
+ for (let count = 0; count < maxAttempts - 1; count++) {
2734
+ try {
2735
+ server = await this.databaseOpenAttempt(options);
2736
+ }
2737
+ catch (ex) {
2738
+ this.logger.warn(`Attempt ${count + 1} of ${maxAttempts} to open database failed, retrying in 1 second...`, ex);
2739
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2740
+ }
2741
+ }
2742
+ // Final attempt if we haven't been able to open the server - rethrow errors if we still can't open.
2743
+ server ??= await this.databaseOpenAttempt(options);
2744
+ return server.connect(lockName);
2745
+ }
2746
+ async databaseOpenAttempt(options) {
2747
+ return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_2__.getNavigatorLocks)().request(OPEN_DB_LOCK, async () => {
2748
+ const { dbFilename } = options;
2749
+ let server = this.activeDatabases.get(dbFilename);
2750
+ if (server == null) {
2751
+ // We don't need navigator locks for shared workers because all queries run in this shared worker exclusively.
2752
+ // For read-only connections, we use a VFS that supports concurrent reads (so a single lock on the connection is
2753
+ // fine).
2754
+ const needsNavigatorLocks = !(isSharedWorker || options.isReadOnly);
2755
+ const connection = new _db_adapters_wa_sqlite_RawSqliteConnection_js__WEBPACK_IMPORTED_MODULE_3__.RawSqliteConnection(options);
2756
+ const withSafeConcurrency = new _db_adapters_wa_sqlite_ConcurrentConnection_js__WEBPACK_IMPORTED_MODULE_4__.ConcurrentSqliteConnection(connection, needsNavigatorLocks);
2757
+ // Initializing the RawSqliteConnection will run some pragmas that might write to the database file, so we want
2758
+ // to do that in an exclusive lock. Note that OPEN_DB_LOCK is not enough for that, as another tab might have
2759
+ // already created a connection (and is thus outside of OPEN_DB_LOCK) while currently writing to it.
2760
+ const returnLease = await withSafeConcurrency.acquireMutex();
2761
+ try {
2762
+ await connection.init();
2763
+ }
2764
+ catch (e) {
2765
+ returnLease();
2766
+ await connection.close();
2767
+ throw e;
2768
+ }
2769
+ returnLease();
2770
+ const onClose = () => this.activeDatabases.delete(dbFilename);
2771
+ server = new _db_adapters_wa_sqlite_DatabaseServer_js__WEBPACK_IMPORTED_MODULE_1__.DatabaseServer({
2772
+ inner: withSafeConcurrency,
2773
+ logger: this.logger,
2774
+ onClose
2775
+ });
2776
+ this.activeDatabases.set(dbFilename, server);
2777
+ }
2778
+ return server;
2779
+ });
2780
+ }
2781
+ closeAll() {
2782
+ const existingDatabases = [...this.activeDatabases.values()];
2783
+ return Promise.all(existingDatabases.map((db) => {
2784
+ db.forceClose();
2785
+ }));
2982
2786
  }
2983
2787
  }
2788
+ const isSharedWorker = 'SharedWorkerGlobalScope' in globalThis;
2984
2789
 
2985
2790
 
2986
2791
  /***/ },
@@ -3015,6 +2820,8 @@ __webpack_require__.r(__webpack_exports__);
3015
2820
  /* harmony export */ CrudBatch: () => (/* binding */ CrudBatch),
3016
2821
  /* harmony export */ CrudEntry: () => (/* binding */ CrudEntry),
3017
2822
  /* harmony export */ CrudTransaction: () => (/* binding */ CrudTransaction),
2823
+ /* harmony export */ DBAdapterDefaultMixin: () => (/* binding */ DBAdapterDefaultMixin),
2824
+ /* harmony export */ DBGetUtilsDefaultMixin: () => (/* binding */ DBGetUtilsDefaultMixin),
3018
2825
  /* harmony export */ DEFAULT_CRUD_BATCH_LIMIT: () => (/* binding */ DEFAULT_CRUD_BATCH_LIMIT),
3019
2826
  /* harmony export */ DEFAULT_CRUD_UPLOAD_THROTTLE_MS: () => (/* binding */ DEFAULT_CRUD_UPLOAD_THROTTLE_MS),
3020
2827
  /* harmony export */ DEFAULT_INDEX_COLUMN_OPTIONS: () => (/* binding */ DEFAULT_INDEX_COLUMN_OPTIONS),
@@ -3022,7 +2829,6 @@ __webpack_require__.r(__webpack_exports__);
3022
2829
  /* harmony export */ DEFAULT_LOCK_TIMEOUT_MS: () => (/* binding */ DEFAULT_LOCK_TIMEOUT_MS),
3023
2830
  /* harmony export */ DEFAULT_POWERSYNC_CLOSE_OPTIONS: () => (/* binding */ DEFAULT_POWERSYNC_CLOSE_OPTIONS),
3024
2831
  /* harmony export */ DEFAULT_POWERSYNC_DB_OPTIONS: () => (/* binding */ DEFAULT_POWERSYNC_DB_OPTIONS),
3025
- /* harmony export */ DEFAULT_PRESSURE_LIMITS: () => (/* binding */ DEFAULT_PRESSURE_LIMITS),
3026
2832
  /* harmony export */ DEFAULT_REMOTE_LOGGER: () => (/* binding */ DEFAULT_REMOTE_LOGGER),
3027
2833
  /* harmony export */ DEFAULT_REMOTE_OPTIONS: () => (/* binding */ DEFAULT_REMOTE_OPTIONS),
3028
2834
  /* harmony export */ DEFAULT_RETRY_DELAY_MS: () => (/* binding */ DEFAULT_RETRY_DELAY_MS),
@@ -3033,7 +2839,6 @@ __webpack_require__.r(__webpack_exports__);
3033
2839
  /* harmony export */ DEFAULT_TABLE_OPTIONS: () => (/* binding */ DEFAULT_TABLE_OPTIONS),
3034
2840
  /* harmony export */ DEFAULT_WATCH_QUERY_OPTIONS: () => (/* binding */ DEFAULT_WATCH_QUERY_OPTIONS),
3035
2841
  /* harmony export */ DEFAULT_WATCH_THROTTLE_MS: () => (/* binding */ DEFAULT_WATCH_THROTTLE_MS),
3036
- /* harmony export */ DataStream: () => (/* binding */ DataStream),
3037
2842
  /* harmony export */ DiffTriggerOperation: () => (/* binding */ DiffTriggerOperation),
3038
2843
  /* harmony export */ DifferentialQueryProcessor: () => (/* binding */ DifferentialQueryProcessor),
3039
2844
  /* harmony export */ EMPTY_DIFFERENTIAL: () => (/* binding */ EMPTY_DIFFERENTIAL),
@@ -3050,6 +2855,7 @@ __webpack_require__.r(__webpack_exports__);
3050
2855
  /* harmony export */ MAX_AMOUNT_OF_COLUMNS: () => (/* binding */ MAX_AMOUNT_OF_COLUMNS),
3051
2856
  /* harmony export */ MAX_OP_ID: () => (/* binding */ MAX_OP_ID),
3052
2857
  /* harmony export */ MEMORY_TRIGGER_CLAIM_MANAGER: () => (/* binding */ MEMORY_TRIGGER_CLAIM_MANAGER),
2858
+ /* harmony export */ Mutex: () => (/* binding */ Mutex),
3053
2859
  /* harmony export */ OnChangeQueryProcessor: () => (/* binding */ OnChangeQueryProcessor),
3054
2860
  /* harmony export */ OpType: () => (/* binding */ OpType),
3055
2861
  /* harmony export */ OpTypeEnum: () => (/* binding */ OpTypeEnum),
@@ -3058,6 +2864,7 @@ __webpack_require__.r(__webpack_exports__);
3058
2864
  /* harmony export */ PowerSyncControlCommand: () => (/* binding */ PowerSyncControlCommand),
3059
2865
  /* harmony export */ RowUpdateType: () => (/* binding */ RowUpdateType),
3060
2866
  /* harmony export */ Schema: () => (/* binding */ Schema),
2867
+ /* harmony export */ Semaphore: () => (/* binding */ Semaphore),
3061
2868
  /* harmony export */ SqliteBucketStorage: () => (/* binding */ SqliteBucketStorage),
3062
2869
  /* harmony export */ SyncClientImplementation: () => (/* binding */ SyncClientImplementation),
3063
2870
  /* harmony export */ SyncDataBatch: () => (/* binding */ SyncDataBatch),
@@ -3091,15 +2898,12 @@ __webpack_require__.r(__webpack_exports__);
3091
2898
  /* harmony export */ isStreamingSyncCheckpointPartiallyComplete: () => (/* binding */ isStreamingSyncCheckpointPartiallyComplete),
3092
2899
  /* harmony export */ isStreamingSyncData: () => (/* binding */ isStreamingSyncData),
3093
2900
  /* harmony export */ isSyncNewCheckpointRequest: () => (/* binding */ isSyncNewCheckpointRequest),
3094
- /* harmony export */ mutexRunExclusive: () => (/* binding */ mutexRunExclusive),
3095
2901
  /* harmony export */ parseQuery: () => (/* binding */ parseQuery),
3096
2902
  /* harmony export */ runOnSchemaChange: () => (/* binding */ runOnSchemaChange),
3097
2903
  /* harmony export */ sanitizeSQL: () => (/* binding */ sanitizeSQL),
3098
- /* harmony export */ sanitizeUUID: () => (/* binding */ sanitizeUUID)
2904
+ /* harmony export */ sanitizeUUID: () => (/* binding */ sanitizeUUID),
2905
+ /* harmony export */ timeoutSignal: () => (/* binding */ timeoutSignal)
3099
2906
  /* 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
2907
  // https://www.sqlite.org/lang_expr.html#castexpr
3104
2908
  var ColumnType;
3105
2909
  (function (ColumnType) {
@@ -3757,7 +3561,7 @@ class SyncingService {
3757
3561
  updatedAttachments.push(downloaded);
3758
3562
  break;
3759
3563
  case AttachmentState.QUEUED_DELETE:
3760
- const deleted = await this.deleteAttachment(attachment);
3564
+ const deleted = await this.deleteAttachment(attachment, context);
3761
3565
  updatedAttachments.push(deleted);
3762
3566
  break;
3763
3567
  }
@@ -3835,17 +3639,16 @@ class SyncingService {
3835
3639
  * On failure, defers to error handler or archives.
3836
3640
  *
3837
3641
  * @param attachment - The attachment record to delete
3642
+ * @param context - Attachment context for database operations
3838
3643
  * @returns Updated attachment record
3839
3644
  */
3840
- async deleteAttachment(attachment) {
3645
+ async deleteAttachment(attachment, context) {
3841
3646
  try {
3842
3647
  await this.remoteStorage.deleteFile(attachment);
3843
3648
  if (attachment.localUri) {
3844
3649
  await this.localStorage.deleteFile(attachment.localUri);
3845
3650
  }
3846
- await this.attachmentService.withContext(async (ctx) => {
3847
- await ctx.deleteAttachment(attachment.id);
3848
- });
3651
+ await context.deleteAttachment(attachment.id);
3849
3652
  return {
3850
3653
  ...attachment,
3851
3654
  state: AttachmentState.ARCHIVED
@@ -3883,32 +3686,198 @@ class SyncingService {
3883
3686
  }
3884
3687
 
3885
3688
  /**
3886
- * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.
3689
+ * A simple fixed-capacity queue implementation.
3690
+ *
3691
+ * Unlike a naive queue implemented by `array.push()` and `array.shift()`, this avoids moving array elements around
3692
+ * and is `O(1)` for {@link addLast} and {@link removeFirst}.
3693
+ */
3694
+ class Queue {
3695
+ table;
3696
+ // Index of the first element in the table.
3697
+ head;
3698
+ // Amount of items currently in the queue.
3699
+ _length;
3700
+ constructor(initialItems) {
3701
+ this.table = [...initialItems];
3702
+ this.head = 0;
3703
+ this._length = this.table.length;
3704
+ }
3705
+ get isEmpty() {
3706
+ return this.length == 0;
3707
+ }
3708
+ get length() {
3709
+ return this._length;
3710
+ }
3711
+ removeFirst() {
3712
+ if (this.isEmpty) {
3713
+ throw new Error('Queue is empty');
3714
+ }
3715
+ const result = this.table[this.head];
3716
+ this._length--;
3717
+ this.table[this.head] = undefined;
3718
+ this.head = (this.head + 1) % this.table.length;
3719
+ return result;
3720
+ }
3721
+ addLast(element) {
3722
+ if (this.length == this.table.length) {
3723
+ throw new Error('Queue is full');
3724
+ }
3725
+ this.table[(this.head + this._length) % this.table.length] = element;
3726
+ this._length++;
3727
+ }
3728
+ }
3729
+
3730
+ /**
3731
+ * An asynchronous semaphore implementation with associated items per lease.
3732
+ *
3733
+ * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
3887
3734
  */
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);
3735
+ class Semaphore {
3736
+ // Available items that are not currently assigned to a waiter.
3737
+ available;
3738
+ size;
3739
+ // Linked list of waiters. We don't expect the wait list to become particularly large, and this allows removing
3740
+ // aborted waiters from the middle of the list efficiently.
3741
+ firstWaiter;
3742
+ lastWaiter;
3743
+ constructor(elements) {
3744
+ this.available = new Queue(elements);
3745
+ this.size = this.available.length;
3746
+ }
3747
+ addWaiter(requestedItems, onAcquire) {
3748
+ const node = {
3749
+ isActive: true,
3750
+ acquiredItems: [],
3751
+ remainingItems: requestedItems,
3752
+ onAcquire,
3753
+ prev: this.lastWaiter
3754
+ };
3755
+ if (this.lastWaiter) {
3756
+ this.lastWaiter.next = node;
3757
+ this.lastWaiter = node;
3758
+ }
3759
+ else {
3760
+ // First waiter
3761
+ this.lastWaiter = this.firstWaiter = node;
3762
+ }
3763
+ return node;
3764
+ }
3765
+ deactivateWaiter(waiter) {
3766
+ const { prev, next } = waiter;
3767
+ waiter.isActive = false;
3768
+ if (prev)
3769
+ prev.next = next;
3770
+ if (next)
3771
+ next.prev = prev;
3772
+ if (waiter == this.firstWaiter)
3773
+ this.firstWaiter = next;
3774
+ if (waiter == this.lastWaiter)
3775
+ this.lastWaiter = prev;
3776
+ }
3777
+ requestPermits(amount, abort) {
3778
+ if (amount <= 0 || amount > this.size) {
3779
+ throw new Error(`Invalid amount of items requested (${amount}), must be between 1 and ${this.size}`);
3780
+ }
3781
+ return new Promise((resolve, reject) => {
3782
+ function rejectAborted() {
3783
+ reject(abort?.reason ?? new Error('Semaphore acquire aborted'));
3901
3784
  }
3902
- if (timedOut)
3903
- return;
3904
- try {
3905
- resolve(await callback());
3785
+ if (abort?.aborted) {
3786
+ return rejectAborted();
3906
3787
  }
3907
- catch (ex) {
3908
- reject(ex);
3788
+ let waiter;
3789
+ const markCompleted = () => {
3790
+ const items = waiter.acquiredItems;
3791
+ waiter.acquiredItems = []; // Avoid releasing items twice.
3792
+ for (const element of items) {
3793
+ // Give to next waiter, if possible.
3794
+ const nextWaiter = this.firstWaiter;
3795
+ if (nextWaiter) {
3796
+ nextWaiter.acquiredItems.push(element);
3797
+ nextWaiter.remainingItems--;
3798
+ if (nextWaiter.remainingItems == 0) {
3799
+ nextWaiter.onAcquire();
3800
+ }
3801
+ }
3802
+ else {
3803
+ // No pending waiter, return lease into pool.
3804
+ this.available.addLast(element);
3805
+ }
3806
+ }
3807
+ };
3808
+ const onAbort = () => {
3809
+ abort?.removeEventListener('abort', onAbort);
3810
+ if (waiter.isActive) {
3811
+ this.deactivateWaiter(waiter);
3812
+ rejectAborted();
3813
+ }
3814
+ };
3815
+ const resolvePromise = () => {
3816
+ this.deactivateWaiter(waiter);
3817
+ abort?.removeEventListener('abort', onAbort);
3818
+ const items = waiter.acquiredItems;
3819
+ resolve({ items, release: markCompleted });
3820
+ };
3821
+ waiter = this.addWaiter(amount, resolvePromise);
3822
+ // If there are items in the pool that haven't been assigned, we can pull them into this waiter. Note that this is
3823
+ // only the case if we're the first waiter (otherwise, items would have been assigned to an earlier waiter).
3824
+ while (!this.available.isEmpty && waiter.remainingItems > 0) {
3825
+ waiter.acquiredItems.push(this.available.removeFirst());
3826
+ waiter.remainingItems--;
3827
+ }
3828
+ if (waiter.remainingItems == 0) {
3829
+ return resolvePromise();
3909
3830
  }
3831
+ abort?.addEventListener('abort', onAbort);
3910
3832
  });
3911
- });
3833
+ }
3834
+ /**
3835
+ * Requests a single item from the pool.
3836
+ *
3837
+ * The returned `release` callback must be invoked to return the item into the pool.
3838
+ */
3839
+ async requestOne(abort) {
3840
+ const { items, release } = await this.requestPermits(1, abort);
3841
+ return { release, item: items[0] };
3842
+ }
3843
+ /**
3844
+ * Requests access to all items from the pool.
3845
+ *
3846
+ * The returned `release` callback must be invoked to return items into the pool.
3847
+ */
3848
+ requestAll(abort) {
3849
+ return this.requestPermits(this.size, abort);
3850
+ }
3851
+ }
3852
+ /**
3853
+ * An asynchronous mutex implementation.
3854
+ *
3855
+ * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
3856
+ */
3857
+ class Mutex {
3858
+ inner = new Semaphore([null]);
3859
+ async acquire(abort) {
3860
+ const { release } = await this.inner.requestOne(abort);
3861
+ return release;
3862
+ }
3863
+ async runExclusive(fn, abort) {
3864
+ const returnMutex = await this.acquire(abort);
3865
+ try {
3866
+ return await fn();
3867
+ }
3868
+ finally {
3869
+ returnMutex();
3870
+ }
3871
+ }
3872
+ }
3873
+ function timeoutSignal(timeout) {
3874
+ if (timeout == null)
3875
+ return;
3876
+ if ('timeout' in AbortSignal)
3877
+ return AbortSignal.timeout(timeout);
3878
+ const controller = new AbortController();
3879
+ setTimeout(() => controller.abort(new Error('Timeout waiting for lock')), timeout);
3880
+ return controller.signal;
3912
3881
  }
3913
3882
 
3914
3883
  /**
@@ -3920,7 +3889,7 @@ class AttachmentService {
3920
3889
  db;
3921
3890
  logger;
3922
3891
  tableName;
3923
- mutex = new async_mutex__WEBPACK_IMPORTED_MODULE_0__.Mutex();
3892
+ mutex = new Mutex();
3924
3893
  context;
3925
3894
  constructor(db, logger, tableName = 'attachments', archivedCacheLimit = 100) {
3926
3895
  this.db = db;
@@ -3957,7 +3926,7 @@ class AttachmentService {
3957
3926
  * Executes a callback with exclusive access to the attachment context.
3958
3927
  */
3959
3928
  async withContext(callback) {
3960
- return mutexRunExclusive(this.mutex, async () => {
3929
+ return this.mutex.runExclusive(async () => {
3961
3930
  return callback(this.context);
3962
3931
  });
3963
3932
  }
@@ -3993,9 +3962,15 @@ class AttachmentQueue {
3993
3962
  tableName;
3994
3963
  /** Logger instance for diagnostic information */
3995
3964
  logger;
3996
- /** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */
3965
+ /** Interval in milliseconds between periodic sync operations. Acts as a polling timer to retry
3966
+ * failed uploads/downloads, especially after the app goes offline. Default: 30000 (30 seconds) */
3997
3967
  syncIntervalMs = 30 * 1000;
3998
- /** Duration in milliseconds to throttle sync operations */
3968
+ /** Throttle duration in milliseconds for the reactive watch query on the attachments table.
3969
+ * When attachment records change, a watch query detects the change and triggers a sync.
3970
+ * This throttle prevents the sync from firing too rapidly when many changes happen in
3971
+ * quick succession (e.g., bulk inserts). This is distinct from syncIntervalMs — it controls
3972
+ * how quickly the queue reacts to changes, while syncIntervalMs controls how often it polls
3973
+ * for retries. Default: 30 (from DEFAULT_WATCH_THROTTLE_MS) */
3999
3974
  syncThrottleDuration;
4000
3975
  /** Whether to automatically download remote attachments. Default: true */
4001
3976
  downloadAttachments = true;
@@ -4019,8 +3994,8 @@ class AttachmentQueue {
4019
3994
  * @param options.watchAttachments - Callback for monitoring attachment changes in your data model
4020
3995
  * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'
4021
3996
  * @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
3997
+ * @param options.syncIntervalMs - Periodic polling interval in milliseconds for retrying failed uploads/downloads. Default: 30000
3998
+ * @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
3999
  * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true
4025
4000
  * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100
4026
4001
  */
@@ -4327,6 +4302,8 @@ var EncodingType;
4327
4302
  EncodingType["Base64"] = "base64";
4328
4303
  })(EncodingType || (EncodingType = {}));
4329
4304
 
4305
+ const symbolAsyncIterator = Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');
4306
+
4330
4307
  function getDefaultExportFromCjs (x) {
4331
4308
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
4332
4309
  }
@@ -4407,7 +4384,7 @@ function requireEventIterator () {
4407
4384
  this.removeCallback();
4408
4385
  });
4409
4386
  }
4410
- [Symbol.asyncIterator]() {
4387
+ [symbolAsyncIterator]() {
4411
4388
  return {
4412
4389
  next: (value) => {
4413
4390
  const result = this.pushQueue.shift();
@@ -4454,7 +4431,7 @@ function requireEventIterator () {
4454
4431
  queue.eventHandlers[event] = fn;
4455
4432
  },
4456
4433
  }) || (() => { });
4457
- this[Symbol.asyncIterator] = () => queue[Symbol.asyncIterator]();
4434
+ this[symbolAsyncIterator] = () => queue[symbolAsyncIterator]();
4458
4435
  Object.freeze(this);
4459
4436
  }
4460
4437
  }
@@ -4781,6 +4758,49 @@ var Logger = /*@__PURE__*/getDefaultExportFromCjs(loggerExports);
4781
4758
  * Set of generic interfaces to allow PowerSync compatibility with
4782
4759
  * different SQLite DB implementations.
4783
4760
  */
4761
+ /**
4762
+ * Implements {@link DBGetUtils} on a {@link SqlRunner}.
4763
+ */
4764
+ function DBGetUtilsDefaultMixin(Base) {
4765
+ return class extends Base {
4766
+ async getAll(sql, parameters) {
4767
+ const res = await this.execute(sql, parameters);
4768
+ return res.rows?._array ?? [];
4769
+ }
4770
+ async getOptional(sql, parameters) {
4771
+ const res = await this.execute(sql, parameters);
4772
+ return res.rows?.item(0) ?? null;
4773
+ }
4774
+ async get(sql, parameters) {
4775
+ const res = await this.execute(sql, parameters);
4776
+ const first = res.rows?.item(0);
4777
+ if (!first) {
4778
+ throw new Error('Result set is empty');
4779
+ }
4780
+ return first;
4781
+ }
4782
+ async executeBatch(query, params = []) {
4783
+ // If this context can run batch statements natively, use that.
4784
+ // @ts-ignore
4785
+ if (super.executeBatch) {
4786
+ // @ts-ignore
4787
+ return super.executeBatch(query, params);
4788
+ }
4789
+ // Emulate executeBatch by running statements individually.
4790
+ let lastInsertId;
4791
+ let rowsAffected = 0;
4792
+ for (const set of params) {
4793
+ const result = await this.execute(query, set);
4794
+ lastInsertId = result.insertId;
4795
+ rowsAffected += result.rowsAffected;
4796
+ }
4797
+ return {
4798
+ rowsAffected,
4799
+ insertId: lastInsertId
4800
+ };
4801
+ }
4802
+ };
4803
+ }
4784
4804
  /**
4785
4805
  * Update table operation numbers from SQLite
4786
4806
  */
@@ -4790,6 +4810,89 @@ var RowUpdateType;
4790
4810
  RowUpdateType[RowUpdateType["SQLITE_DELETE"] = 9] = "SQLITE_DELETE";
4791
4811
  RowUpdateType[RowUpdateType["SQLITE_UPDATE"] = 23] = "SQLITE_UPDATE";
4792
4812
  })(RowUpdateType || (RowUpdateType = {}));
4813
+ /**
4814
+ * A mixin to implement {@link DBAdapter} by delegating to {@link ConnectionPool.readLock} and
4815
+ * {@link ConnectionPool.writeLock}.
4816
+ */
4817
+ function DBAdapterDefaultMixin(Base) {
4818
+ return class extends Base {
4819
+ readTransaction(fn, options) {
4820
+ return this.readLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);
4821
+ }
4822
+ writeTransaction(fn, options) {
4823
+ return this.writeLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);
4824
+ }
4825
+ getAll(sql, parameters) {
4826
+ return this.readLock((ctx) => ctx.getAll(sql, parameters));
4827
+ }
4828
+ getOptional(sql, parameters) {
4829
+ return this.readLock((ctx) => ctx.getOptional(sql, parameters));
4830
+ }
4831
+ get(sql, parameters) {
4832
+ return this.readLock((ctx) => ctx.get(sql, parameters));
4833
+ }
4834
+ execute(query, params) {
4835
+ return this.writeLock((ctx) => ctx.execute(query, params));
4836
+ }
4837
+ executeRaw(query, params) {
4838
+ return this.writeLock((ctx) => ctx.executeRaw(query, params));
4839
+ }
4840
+ executeBatch(query, params) {
4841
+ return this.writeTransaction((tx) => tx.executeBatch(query, params));
4842
+ }
4843
+ };
4844
+ }
4845
+ class BaseTransaction {
4846
+ inner;
4847
+ finalized = false;
4848
+ constructor(inner) {
4849
+ this.inner = inner;
4850
+ }
4851
+ async commit() {
4852
+ if (this.finalized) {
4853
+ return { rowsAffected: 0 };
4854
+ }
4855
+ this.finalized = true;
4856
+ return this.inner.execute('COMMIT');
4857
+ }
4858
+ async rollback() {
4859
+ if (this.finalized) {
4860
+ return { rowsAffected: 0 };
4861
+ }
4862
+ this.finalized = true;
4863
+ return this.inner.execute('ROLLBACK');
4864
+ }
4865
+ execute(query, params) {
4866
+ return this.inner.execute(query, params);
4867
+ }
4868
+ executeRaw(query, params) {
4869
+ return this.inner.executeRaw(query, params);
4870
+ }
4871
+ executeBatch(query, params) {
4872
+ return this.inner.executeBatch(query, params);
4873
+ }
4874
+ }
4875
+ class TransactionImplementation extends DBGetUtilsDefaultMixin(BaseTransaction) {
4876
+ static async runWith(ctx, fn) {
4877
+ let tx = new TransactionImplementation(ctx);
4878
+ try {
4879
+ await ctx.execute('BEGIN IMMEDIATE');
4880
+ const result = await fn(tx);
4881
+ await tx.commit();
4882
+ return result;
4883
+ }
4884
+ catch (ex) {
4885
+ try {
4886
+ await tx.rollback();
4887
+ }
4888
+ catch (ex2) {
4889
+ // In rare cases, a rollback may fail.
4890
+ // Safe to ignore.
4891
+ }
4892
+ throw ex;
4893
+ }
4894
+ }
4895
+ }
4793
4896
  function isBatchedUpdateNotification(update) {
4794
4897
  return 'tables' in update;
4795
4898
  }
@@ -4932,16 +5035,12 @@ class SyncStatus {
4932
5035
  *
4933
5036
  * This returns null when the database is currently being opened and we don't have reliable information about all
4934
5037
  * included streams yet.
4935
- *
4936
- * @experimental Sync streams are currently in alpha.
4937
5038
  */
4938
5039
  get syncStreams() {
4939
5040
  return this.options.dataFlow?.internalStreamSubscriptions?.map((core) => new SyncStreamStatusView(this, core));
4940
5041
  }
4941
5042
  /**
4942
5043
  * If the `stream` appears in {@link syncStreams}, returns the current status for that stream.
4943
- *
4944
- * @experimental Sync streams are currently in alpha.
4945
5044
  */
4946
5045
  forStream(stream) {
4947
5046
  const asJson = JSON.stringify(stream.parameters);
@@ -5210,15 +5309,6 @@ class ControlledExecutor {
5210
5309
  }
5211
5310
  }
5212
5311
 
5213
- /**
5214
- * A ponyfill for `Symbol.asyncIterator` that is compatible with the
5215
- * [recommended polyfill](https://github.com/Azure/azure-sdk-for-js/blob/%40azure/core-asynciterator-polyfill_1.0.2/sdk/core/core-asynciterator-polyfill/src/index.ts#L4-L6)
5216
- * we recommend for React Native.
5217
- *
5218
- * As long as we use this symbol (instead of `for await` and `async *`) in this package, we can be compatible with async
5219
- * iterators without requiring them.
5220
- */
5221
- const symbolAsyncIterator = Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');
5222
5312
  /**
5223
5313
  * Throttle a function to be called at most once every "wait" milliseconds,
5224
5314
  * on the trailing edge.
@@ -13545,187 +13635,20 @@ function requireDist () {
13545
13635
  __exportStar(requireErrors(), exports$1);
13546
13636
  __exportStar(requireFrames(), exports$1);
13547
13637
  __exportStar(requireRSocket(), exports$1);
13548
- __exportStar(requireRSocketConnector(), exports$1);
13549
- __exportStar(requireRSocketServer(), exports$1);
13550
- __exportStar(requireTransport(), exports$1);
13551
-
13552
- } (dist));
13553
- return dist;
13554
- }
13555
-
13556
- var distExports = requireDist();
13557
-
13558
- var version = "1.48.0";
13559
- var PACKAGE = {
13560
- version: version};
13561
-
13562
- const DEFAULT_PRESSURE_LIMITS = {
13563
- highWater: 10,
13564
- lowWater: 0
13565
- };
13566
- /**
13567
- * A very basic implementation of a data stream with backpressure support which does not use
13568
- * native JS streams or async iterators.
13569
- * This is handy for environments such as React Native which need polyfills for the above.
13570
- */
13571
- class DataStream extends BaseObserver {
13572
- options;
13573
- dataQueue;
13574
- isClosed;
13575
- processingPromise;
13576
- notifyDataAdded;
13577
- logger;
13578
- mapLine;
13579
- constructor(options) {
13580
- super();
13581
- this.options = options;
13582
- this.processingPromise = null;
13583
- this.isClosed = false;
13584
- this.dataQueue = [];
13585
- this.mapLine = options?.mapLine ?? ((line) => line);
13586
- this.logger = options?.logger ?? Logger.get('DataStream');
13587
- if (options?.closeOnError) {
13588
- const l = this.registerListener({
13589
- error: (ex) => {
13590
- l?.();
13591
- this.close();
13592
- }
13593
- });
13594
- }
13595
- }
13596
- get highWatermark() {
13597
- return this.options?.pressure?.highWaterMark ?? DEFAULT_PRESSURE_LIMITS.highWater;
13598
- }
13599
- get lowWatermark() {
13600
- return this.options?.pressure?.lowWaterMark ?? DEFAULT_PRESSURE_LIMITS.lowWater;
13601
- }
13602
- get closed() {
13603
- return this.isClosed;
13604
- }
13605
- async close() {
13606
- this.isClosed = true;
13607
- await this.processingPromise;
13608
- this.iterateListeners((l) => l.closed?.());
13609
- // Discard any data in the queue
13610
- this.dataQueue = [];
13611
- this.listeners.clear();
13612
- }
13613
- /**
13614
- * Enqueues data for the consumers to read
13615
- */
13616
- enqueueData(data) {
13617
- if (this.isClosed) {
13618
- throw new Error('Cannot enqueue data into closed stream.');
13619
- }
13620
- this.dataQueue.push(data);
13621
- this.notifyDataAdded?.();
13622
- this.processQueue();
13623
- }
13624
- /**
13625
- * Reads data once from the data stream
13626
- * @returns a Data payload or Null if the stream closed.
13627
- */
13628
- async read() {
13629
- if (this.closed) {
13630
- return null;
13631
- }
13632
- // Wait for any pending processing to complete first.
13633
- // This ensures we register our listener before calling processQueue(),
13634
- // avoiding a race where processQueue() sees no reader and returns early.
13635
- if (this.processingPromise) {
13636
- await this.processingPromise;
13637
- }
13638
- // Re-check after await - stream may have closed while we were waiting
13639
- if (this.closed) {
13640
- return null;
13641
- }
13642
- return new Promise((resolve, reject) => {
13643
- const l = this.registerListener({
13644
- data: async (data) => {
13645
- resolve(data);
13646
- // Remove the listener
13647
- l?.();
13648
- },
13649
- closed: () => {
13650
- resolve(null);
13651
- l?.();
13652
- },
13653
- error: (ex) => {
13654
- reject(ex);
13655
- l?.();
13656
- }
13657
- });
13658
- this.processQueue();
13659
- });
13660
- }
13661
- /**
13662
- * Executes a callback for each data item in the stream
13663
- */
13664
- forEach(callback) {
13665
- if (this.dataQueue.length <= this.lowWatermark) {
13666
- this.iterateAsyncErrored(async (l) => l.lowWater?.());
13667
- }
13668
- return this.registerListener({
13669
- data: callback
13670
- });
13671
- }
13672
- processQueue() {
13673
- if (this.processingPromise) {
13674
- return;
13675
- }
13676
- const promise = (this.processingPromise = this._processQueue());
13677
- promise.finally(() => {
13678
- this.processingPromise = null;
13679
- });
13680
- return promise;
13681
- }
13682
- hasDataReader() {
13683
- return Array.from(this.listeners.values()).some((l) => !!l.data);
13684
- }
13685
- async _processQueue() {
13686
- /**
13687
- * Allow listeners to mutate the queue before processing.
13688
- * This allows for operations such as dropping or compressing data
13689
- * on high water or requesting more data on low water.
13690
- */
13691
- if (this.dataQueue.length >= this.highWatermark) {
13692
- await this.iterateAsyncErrored(async (l) => l.highWater?.());
13693
- }
13694
- if (this.isClosed || !this.hasDataReader()) {
13695
- return;
13696
- }
13697
- if (this.dataQueue.length) {
13698
- const data = this.dataQueue.shift();
13699
- const mapped = this.mapLine(data);
13700
- await this.iterateAsyncErrored(async (l) => l.data?.(mapped));
13701
- }
13702
- if (this.dataQueue.length <= this.lowWatermark) {
13703
- const dataAdded = new Promise((resolve) => {
13704
- this.notifyDataAdded = resolve;
13705
- });
13706
- await Promise.race([this.iterateAsyncErrored(async (l) => l.lowWater?.()), dataAdded]);
13707
- this.notifyDataAdded = null;
13708
- }
13709
- if (this.dataQueue.length > 0) {
13710
- setTimeout(() => this.processQueue());
13711
- }
13712
- }
13713
- async iterateAsyncErrored(cb) {
13714
- // Important: We need to copy the listeners, as calling a listener could result in adding another
13715
- // listener, resulting in infinite loops.
13716
- const listeners = Array.from(this.listeners.values());
13717
- for (let i of listeners) {
13718
- try {
13719
- await cb(i);
13720
- }
13721
- catch (ex) {
13722
- this.logger.error(ex);
13723
- this.iterateListeners((l) => l.error?.(ex));
13724
- }
13725
- }
13726
- }
13638
+ __exportStar(requireRSocketConnector(), exports$1);
13639
+ __exportStar(requireRSocketServer(), exports$1);
13640
+ __exportStar(requireTransport(), exports$1);
13641
+
13642
+ } (dist));
13643
+ return dist;
13727
13644
  }
13728
13645
 
13646
+ var distExports = requireDist();
13647
+
13648
+ var version = "1.52.0";
13649
+ var PACKAGE = {
13650
+ version: version};
13651
+
13729
13652
  var WebsocketDuplexConnection = {};
13730
13653
 
13731
13654
  var hasRequiredWebsocketDuplexConnection;
@@ -13888,8 +13811,215 @@ class WebsocketClientTransport {
13888
13811
  }
13889
13812
  }
13890
13813
 
13814
+ const doneResult = { done: true, value: undefined };
13815
+ function valueResult(value) {
13816
+ return { done: false, value };
13817
+ }
13818
+ /**
13819
+ * A variant of {@link Array.map} for async iterators.
13820
+ */
13821
+ function map(source, map) {
13822
+ return {
13823
+ next: async () => {
13824
+ const value = await source.next();
13825
+ if (value.done) {
13826
+ return value;
13827
+ }
13828
+ else {
13829
+ return { value: map(value.value) };
13830
+ }
13831
+ }
13832
+ };
13833
+ }
13834
+ /**
13835
+ * Expands a source async iterator by allowing to inject events asynchronously.
13836
+ *
13837
+ * The resulting iterator will emit all events from its source. Additionally though, events can be injected. These
13838
+ * events are dropped once the main iterator completes, but are otherwise forwarded.
13839
+ *
13840
+ * The iterator completes when its source completes, and it supports backpressure by only calling `next()` on the source
13841
+ * in response to a `next()` call from downstream if no pending injected events can be dispatched.
13842
+ */
13843
+ function injectable(source) {
13844
+ let sourceIsDone = false;
13845
+ let waiter = undefined; // An active, waiting next() call.
13846
+ // A pending upstream event that couldn't be dispatched because inject() has been called before it was resolved.
13847
+ let pendingSourceEvent = null;
13848
+ let pendingInjectedEvents = [];
13849
+ const consumeWaiter = () => {
13850
+ const pending = waiter;
13851
+ waiter = undefined;
13852
+ return pending;
13853
+ };
13854
+ const fetchFromSource = () => {
13855
+ const resolveWaiter = (propagate) => {
13856
+ const active = consumeWaiter();
13857
+ if (active) {
13858
+ propagate(active);
13859
+ }
13860
+ else {
13861
+ pendingSourceEvent = propagate;
13862
+ }
13863
+ };
13864
+ const nextFromSource = source.next();
13865
+ nextFromSource.then((value) => {
13866
+ sourceIsDone = value.done == true;
13867
+ resolveWaiter((w) => w.resolve(value));
13868
+ }, (error) => {
13869
+ resolveWaiter((w) => w.reject(error));
13870
+ });
13871
+ };
13872
+ return {
13873
+ next: () => {
13874
+ return new Promise((resolve, reject) => {
13875
+ // First priority: Dispatch ready upstream events.
13876
+ if (sourceIsDone) {
13877
+ return resolve(doneResult);
13878
+ }
13879
+ if (pendingSourceEvent) {
13880
+ pendingSourceEvent({ resolve, reject });
13881
+ pendingSourceEvent = null;
13882
+ return;
13883
+ }
13884
+ // Second priority: Dispatch injected events
13885
+ if (pendingInjectedEvents.length) {
13886
+ return resolve(valueResult(pendingInjectedEvents.shift()));
13887
+ }
13888
+ // Nothing pending? Fetch from source
13889
+ waiter = { resolve, reject };
13890
+ return fetchFromSource();
13891
+ });
13892
+ },
13893
+ inject: (event) => {
13894
+ const pending = consumeWaiter();
13895
+ if (pending != null) {
13896
+ pending.resolve(valueResult(event));
13897
+ }
13898
+ else {
13899
+ pendingInjectedEvents.push(event);
13900
+ }
13901
+ }
13902
+ };
13903
+ }
13904
+ /**
13905
+ * Splits a byte stream at line endings, emitting each line as a string.
13906
+ */
13907
+ function extractJsonLines(source, decoder) {
13908
+ let buffer = '';
13909
+ const pendingLines = [];
13910
+ let isFinalEvent = false;
13911
+ return {
13912
+ next: async () => {
13913
+ while (true) {
13914
+ if (isFinalEvent) {
13915
+ return doneResult;
13916
+ }
13917
+ {
13918
+ const first = pendingLines.shift();
13919
+ if (first) {
13920
+ return { done: false, value: first };
13921
+ }
13922
+ }
13923
+ const { done, value } = await source.next();
13924
+ if (done) {
13925
+ const remaining = buffer.trim();
13926
+ if (remaining.length != 0) {
13927
+ isFinalEvent = true;
13928
+ return { done: false, value: remaining };
13929
+ }
13930
+ return doneResult;
13931
+ }
13932
+ const data = decoder.decode(value, { stream: true });
13933
+ buffer += data;
13934
+ const lines = buffer.split('\n');
13935
+ for (let i = 0; i < lines.length - 1; i++) {
13936
+ const l = lines[i].trim();
13937
+ if (l.length > 0) {
13938
+ pendingLines.push(l);
13939
+ }
13940
+ }
13941
+ buffer = lines[lines.length - 1];
13942
+ }
13943
+ }
13944
+ };
13945
+ }
13946
+ /**
13947
+ * Splits a concatenated stream of BSON objects by emitting individual objects.
13948
+ */
13949
+ function extractBsonObjects(source) {
13950
+ // Fully read but not emitted yet.
13951
+ const completedObjects = [];
13952
+ // Whether source has returned { done: true }. We do the same once completed objects have been emitted.
13953
+ let isDone = false;
13954
+ const lengthBuffer = new DataView(new ArrayBuffer(4));
13955
+ let objectBody = null;
13956
+ // If we're parsing the length field, a number between 1 and 4 (inclusive) describing remaining bytes in the header.
13957
+ // If we're consuming a document, the bytes remaining.
13958
+ let remainingLength = 4;
13959
+ return {
13960
+ async next() {
13961
+ while (true) {
13962
+ // Before fetching new data from upstream, return completed objects.
13963
+ if (completedObjects.length) {
13964
+ return valueResult(completedObjects.shift());
13965
+ }
13966
+ if (isDone) {
13967
+ return doneResult;
13968
+ }
13969
+ const upstreamEvent = await source.next();
13970
+ if (upstreamEvent.done) {
13971
+ isDone = true;
13972
+ if (objectBody || remainingLength != 4) {
13973
+ throw new Error('illegal end of stream in BSON object');
13974
+ }
13975
+ return doneResult;
13976
+ }
13977
+ const chunk = upstreamEvent.value;
13978
+ for (let i = 0; i < chunk.length;) {
13979
+ const availableInData = chunk.length - i;
13980
+ if (objectBody) {
13981
+ // We're in the middle of reading a BSON document.
13982
+ const bytesToRead = Math.min(availableInData, remainingLength);
13983
+ const copySource = new Uint8Array(chunk.buffer, chunk.byteOffset + i, bytesToRead);
13984
+ objectBody.set(copySource, objectBody.length - remainingLength);
13985
+ i += bytesToRead;
13986
+ remainingLength -= bytesToRead;
13987
+ if (remainingLength == 0) {
13988
+ completedObjects.push(objectBody);
13989
+ // Prepare to read another document, starting with its length
13990
+ objectBody = null;
13991
+ remainingLength = 4;
13992
+ }
13993
+ }
13994
+ else {
13995
+ // Copy up to 4 bytes into lengthBuffer, depending on how many we still need.
13996
+ const bytesToRead = Math.min(availableInData, remainingLength);
13997
+ for (let j = 0; j < bytesToRead; j++) {
13998
+ lengthBuffer.setUint8(4 - remainingLength + j, chunk[i + j]);
13999
+ }
14000
+ i += bytesToRead;
14001
+ remainingLength -= bytesToRead;
14002
+ if (remainingLength == 0) {
14003
+ // Transition from reading length header to reading document. Subtracting 4 because the length of the
14004
+ // header is included in length.
14005
+ const length = lengthBuffer.getInt32(0, true /* little endian */);
14006
+ remainingLength = length - 4;
14007
+ if (remainingLength < 1) {
14008
+ throw new Error(`invalid length for bson: ${length}`);
14009
+ }
14010
+ objectBody = new Uint8Array(length);
14011
+ new DataView(objectBody.buffer).setInt32(0, length, true);
14012
+ }
14013
+ }
14014
+ }
14015
+ }
14016
+ }
14017
+ };
14018
+ }
14019
+
13891
14020
  const POWERSYNC_TRAILING_SLASH_MATCH = /\/+$/;
13892
14021
  const POWERSYNC_JS_VERSION = PACKAGE.version;
14022
+ const SYNC_QUEUE_REQUEST_HIGH_WATER = 10;
13893
14023
  const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
13894
14024
  // Keep alive message is sent every period
13895
14025
  const KEEP_ALIVE_MS = 20_000;
@@ -14069,13 +14199,14 @@ class AbstractRemote {
14069
14199
  return new WebSocket(url);
14070
14200
  }
14071
14201
  /**
14072
- * Returns a data stream of sync line data.
14202
+ * Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.
14203
+ *
14204
+ * The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.
14073
14205
  *
14074
- * @param map Maps received payload frames to the typed event value.
14075
14206
  * @param bson A BSON encoder and decoder. When set, the data stream will be requested with a BSON payload
14076
14207
  * (required for compatibility with older sync services).
14077
14208
  */
14078
- async socketStreamRaw(options, map, bson) {
14209
+ async socketStreamRaw(options, bson) {
14079
14210
  const { path, fetchStrategy = FetchStrategy.Buffered } = options;
14080
14211
  const mimeType = bson == null ? 'application/json' : 'application/bson';
14081
14212
  function toBuffer(js) {
@@ -14090,52 +14221,55 @@ class AbstractRemote {
14090
14221
  }
14091
14222
  const syncQueueRequestSize = fetchStrategy == FetchStrategy.Buffered ? 10 : 1;
14092
14223
  const request = await this.buildRequest(path);
14224
+ const url = this.options.socketUrlTransformer(request.url);
14093
14225
  // Add the user agent in the setup payload - we can't set custom
14094
14226
  // headers with websockets on web. The browser userAgent is however added
14095
14227
  // automatically as a header.
14096
14228
  const userAgent = this.getUserAgent();
14097
- const stream = new DataStream({
14098
- logger: this.logger,
14099
- pressure: {
14100
- lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER
14101
- },
14102
- mapLine: map
14103
- });
14229
+ // While we're connecting (a process that can't be aborted in RSocket), the WebSocket instance to close if we wanted
14230
+ // to abort the connection.
14231
+ let pendingSocket = null;
14232
+ let keepAliveTimeout;
14233
+ let rsocket = null;
14234
+ let queue = null;
14235
+ let didClose = false;
14236
+ const abortRequest = () => {
14237
+ if (didClose) {
14238
+ return;
14239
+ }
14240
+ didClose = true;
14241
+ clearTimeout(keepAliveTimeout);
14242
+ if (pendingSocket) {
14243
+ pendingSocket.close();
14244
+ }
14245
+ if (rsocket) {
14246
+ rsocket.close();
14247
+ }
14248
+ if (queue) {
14249
+ queue.stop();
14250
+ }
14251
+ };
14104
14252
  // Handle upstream abort
14105
- if (options.abortSignal?.aborted) {
14253
+ if (options.abortSignal.aborted) {
14106
14254
  throw new AbortOperation('Connection request aborted');
14107
14255
  }
14108
14256
  else {
14109
- options.abortSignal?.addEventListener('abort', () => {
14110
- stream.close();
14111
- }, { once: true });
14257
+ options.abortSignal.addEventListener('abort', abortRequest);
14112
14258
  }
14113
- let keepAliveTimeout;
14114
14259
  const resetTimeout = () => {
14115
14260
  clearTimeout(keepAliveTimeout);
14116
14261
  keepAliveTimeout = setTimeout(() => {
14117
14262
  this.logger.error(`No data received on WebSocket in ${SOCKET_TIMEOUT_MS}ms, closing connection.`);
14118
- stream.close();
14263
+ abortRequest();
14119
14264
  }, SOCKET_TIMEOUT_MS);
14120
14265
  };
14121
14266
  resetTimeout();
14122
- // Typescript complains about this being `never` if it's not assigned here.
14123
- // This is assigned in `wsCreator`.
14124
- let disposeSocketConnectionTimeout = () => { };
14125
- const url = this.options.socketUrlTransformer(request.url);
14126
14267
  const connector = new distExports.RSocketConnector({
14127
14268
  transport: new WebsocketClientTransport({
14128
14269
  url,
14129
14270
  wsCreator: (url) => {
14130
- const socket = this.createSocket(url);
14131
- disposeSocketConnectionTimeout = stream.registerListener({
14132
- closed: () => {
14133
- // Allow closing the underlying WebSocket if the stream was closed before the
14134
- // RSocket connect completed. This should effectively abort the request.
14135
- socket.close();
14136
- }
14137
- });
14138
- socket.addEventListener('message', (event) => {
14271
+ const socket = (pendingSocket = this.createSocket(url));
14272
+ socket.addEventListener('message', () => {
14139
14273
  resetTimeout();
14140
14274
  });
14141
14275
  return socket;
@@ -14155,43 +14289,40 @@ class AbstractRemote {
14155
14289
  }
14156
14290
  }
14157
14291
  });
14158
- let rsocket;
14159
14292
  try {
14160
14293
  rsocket = await connector.connect();
14161
14294
  // The connection is established, we no longer need to monitor the initial timeout
14162
- disposeSocketConnectionTimeout();
14295
+ pendingSocket = null;
14163
14296
  }
14164
14297
  catch (ex) {
14165
14298
  this.logger.error(`Failed to connect WebSocket`, ex);
14166
- clearTimeout(keepAliveTimeout);
14167
- if (!stream.closed) {
14168
- await stream.close();
14169
- }
14299
+ abortRequest();
14170
14300
  throw ex;
14171
14301
  }
14172
14302
  resetTimeout();
14173
- let socketIsClosed = false;
14174
- const closeSocket = () => {
14175
- clearTimeout(keepAliveTimeout);
14176
- if (socketIsClosed) {
14177
- return;
14178
- }
14179
- socketIsClosed = true;
14180
- rsocket.close();
14181
- };
14182
14303
  // Helps to prevent double close scenarios
14183
- rsocket.onClose(() => (socketIsClosed = true));
14184
- // We initially request this amount and expect these to arrive eventually
14185
- let pendingEventsCount = syncQueueRequestSize;
14186
- const disposeClosedListener = stream.registerListener({
14187
- closed: () => {
14188
- closeSocket();
14189
- disposeClosedListener();
14190
- }
14191
- });
14192
- const socket = await new Promise((resolve, reject) => {
14304
+ rsocket.onClose(() => (rsocket = null));
14305
+ return await new Promise((resolve, reject) => {
14193
14306
  let connectionEstablished = false;
14194
- const res = rsocket.requestStream({
14307
+ let pendingEventsCount = syncQueueRequestSize;
14308
+ let paused = false;
14309
+ let res = null;
14310
+ function requestMore() {
14311
+ const delta = syncQueueRequestSize - pendingEventsCount;
14312
+ if (!paused && delta > 0) {
14313
+ res?.request(delta);
14314
+ pendingEventsCount = syncQueueRequestSize;
14315
+ }
14316
+ }
14317
+ const events = new domExports.EventIterator((q) => {
14318
+ queue = q;
14319
+ q.on('highWater', () => (paused = true));
14320
+ q.on('lowWater', () => {
14321
+ paused = false;
14322
+ requestMore();
14323
+ });
14324
+ }, { highWaterMark: SYNC_QUEUE_REQUEST_HIGH_WATER, lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER })[symbolAsyncIterator]();
14325
+ res = rsocket.requestStream({
14195
14326
  data: toBuffer(options.data),
14196
14327
  metadata: toBuffer({
14197
14328
  path
@@ -14216,7 +14347,7 @@ class AbstractRemote {
14216
14347
  }
14217
14348
  // RSocket will close the RSocket stream automatically
14218
14349
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
14219
- stream.close();
14350
+ abortRequest();
14220
14351
  // Handles cases where the connection failed e.g. auth error or connection error
14221
14352
  if (!connectionEstablished) {
14222
14353
  reject(e);
@@ -14226,41 +14357,40 @@ class AbstractRemote {
14226
14357
  // The connection is active
14227
14358
  if (!connectionEstablished) {
14228
14359
  connectionEstablished = true;
14229
- resolve(res);
14360
+ resolve(events);
14230
14361
  }
14231
14362
  const { data } = payload;
14363
+ if (data) {
14364
+ queue.push(data);
14365
+ }
14232
14366
  // Less events are now pending
14233
14367
  pendingEventsCount--;
14234
- if (!data) {
14235
- return;
14236
- }
14237
- stream.enqueueData(data);
14368
+ // Request another event (unless the downstream consumer is paused).
14369
+ requestMore();
14238
14370
  },
14239
14371
  onComplete: () => {
14240
- stream.close();
14372
+ abortRequest(); // this will also emit a done event
14241
14373
  },
14242
14374
  onExtension: () => { }
14243
14375
  });
14244
14376
  });
14245
- const l = stream.registerListener({
14246
- lowWater: async () => {
14247
- // Request to fill up the queue
14248
- const required = syncQueueRequestSize - pendingEventsCount;
14249
- if (required > 0) {
14250
- socket.request(syncQueueRequestSize - pendingEventsCount);
14251
- pendingEventsCount = syncQueueRequestSize;
14252
- }
14253
- },
14254
- closed: () => {
14255
- l();
14256
- }
14257
- });
14258
- return stream;
14259
14377
  }
14260
14378
  /**
14261
- * Connects to the sync/stream http endpoint, mapping and emitting each received string line.
14379
+ * @returns Whether the HTTP implementation on this platform can receive streamed binary responses. This is true on
14380
+ * all platforms except React Native (who would have guessed...), where we must not request BSON responses.
14381
+ *
14382
+ * @see https://github.com/react-native-community/fetch?tab=readme-ov-file#motivation
14383
+ */
14384
+ get supportsStreamingBinaryResponses() {
14385
+ return true;
14386
+ }
14387
+ /**
14388
+ * Posts a `/sync/stream` request, asserts that it completes successfully and returns the streaming response as an
14389
+ * async iterator of byte blobs.
14390
+ *
14391
+ * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
14262
14392
  */
14263
- async postStreamRaw(options, mapLine) {
14393
+ async fetchStreamRaw(options) {
14264
14394
  const { data, path, headers, abortSignal } = options;
14265
14395
  const request = await this.buildRequest(path);
14266
14396
  /**
@@ -14272,119 +14402,94 @@ class AbstractRemote {
14272
14402
  * Aborting the active fetch request while it is being consumed seems to throw
14273
14403
  * an unhandled exception on the window level.
14274
14404
  */
14275
- if (abortSignal?.aborted) {
14276
- throw new AbortOperation('Abort request received before making postStreamRaw request');
14405
+ if (abortSignal.aborted) {
14406
+ throw new AbortOperation('Abort request received before making fetchStreamRaw request');
14277
14407
  }
14278
14408
  const controller = new AbortController();
14279
- let requestResolved = false;
14280
- abortSignal?.addEventListener('abort', () => {
14281
- if (!requestResolved) {
14409
+ let reader = null;
14410
+ abortSignal.addEventListener('abort', () => {
14411
+ const reason = abortSignal.reason ??
14412
+ new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.');
14413
+ if (reader == null) {
14282
14414
  // Only abort via the abort controller if the request has not resolved yet
14283
- controller.abort(abortSignal.reason ??
14284
- new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.'));
14415
+ controller.abort(reason);
14416
+ }
14417
+ else {
14418
+ reader.cancel(reason).catch(() => {
14419
+ // Cancelling the reader might rethrow an exception we would have handled by throwing in next(). So we can
14420
+ // ignore it here.
14421
+ });
14285
14422
  }
14286
14423
  });
14287
- const res = await this.fetch(request.url, {
14288
- method: 'POST',
14289
- headers: { ...headers, ...request.headers },
14290
- body: JSON.stringify(data),
14291
- signal: controller.signal,
14292
- cache: 'no-store',
14293
- ...(this.options.fetchOptions ?? {}),
14294
- ...options.fetchOptions
14295
- }).catch((ex) => {
14424
+ let res;
14425
+ let responseIsBson = false;
14426
+ try {
14427
+ const ndJson = 'application/x-ndjson';
14428
+ const bson = 'application/vnd.powersync.bson-stream';
14429
+ res = await this.fetch(request.url, {
14430
+ method: 'POST',
14431
+ headers: {
14432
+ ...headers,
14433
+ ...request.headers,
14434
+ accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
14435
+ },
14436
+ body: JSON.stringify(data),
14437
+ signal: controller.signal,
14438
+ cache: 'no-store',
14439
+ ...(this.options.fetchOptions ?? {}),
14440
+ ...options.fetchOptions
14441
+ });
14442
+ if (!res.ok || !res.body) {
14443
+ const text = await res.text();
14444
+ this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
14445
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
14446
+ error.status = res.status;
14447
+ throw error;
14448
+ }
14449
+ const contentType = res.headers.get('content-type');
14450
+ responseIsBson = contentType == bson;
14451
+ }
14452
+ catch (ex) {
14296
14453
  if (ex.name == 'AbortError') {
14297
14454
  throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
14298
14455
  }
14299
14456
  throw ex;
14300
- });
14301
- if (!res) {
14302
- throw new Error('Fetch request was aborted');
14303
- }
14304
- requestResolved = true;
14305
- if (!res.ok || !res.body) {
14306
- const text = await res.text();
14307
- this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
14308
- const error = new Error(`HTTP ${res.statusText}: ${text}`);
14309
- error.status = res.status;
14310
- throw error;
14311
14457
  }
14312
- // Create a new stream splitting the response at line endings while also handling cancellations
14313
- // by closing the reader.
14314
- const reader = res.body.getReader();
14315
- let readerReleased = false;
14316
- // This will close the network request and read stream
14317
- const closeReader = async () => {
14318
- try {
14319
- readerReleased = true;
14320
- await reader.cancel();
14321
- }
14322
- catch (ex) {
14323
- // an error will throw if the reader hasn't been used yet
14324
- }
14325
- reader.releaseLock();
14326
- };
14327
- const stream = new DataStream({
14328
- logger: this.logger,
14329
- mapLine: mapLine,
14330
- pressure: {
14331
- highWaterMark: 20,
14332
- lowWaterMark: 10
14333
- }
14334
- });
14335
- abortSignal?.addEventListener('abort', () => {
14336
- closeReader();
14337
- stream.close();
14338
- });
14339
- const decoder = this.createTextDecoder();
14340
- let buffer = '';
14341
- const consumeStream = async () => {
14342
- while (!stream.closed && !abortSignal?.aborted && !readerReleased) {
14343
- const { done, value } = await reader.read();
14344
- if (done) {
14345
- const remaining = buffer.trim();
14346
- if (remaining.length != 0) {
14347
- stream.enqueueData(remaining);
14348
- }
14349
- stream.close();
14350
- await closeReader();
14351
- return;
14458
+ reader = res.body.getReader();
14459
+ const stream = {
14460
+ next: async () => {
14461
+ if (controller.signal.aborted) {
14462
+ return doneResult;
14352
14463
  }
14353
- const data = decoder.decode(value, { stream: true });
14354
- buffer += data;
14355
- const lines = buffer.split('\n');
14356
- for (var i = 0; i < lines.length - 1; i++) {
14357
- var l = lines[i].trim();
14358
- if (l.length > 0) {
14359
- stream.enqueueData(l);
14360
- }
14464
+ try {
14465
+ return await reader.read();
14361
14466
  }
14362
- buffer = lines[lines.length - 1];
14363
- // Implement backpressure by waiting for the low water mark to be reached
14364
- if (stream.dataQueue.length > stream.highWatermark) {
14365
- await new Promise((resolve) => {
14366
- const dispose = stream.registerListener({
14367
- lowWater: async () => {
14368
- resolve();
14369
- dispose();
14370
- },
14371
- closed: () => {
14372
- resolve();
14373
- dispose();
14374
- }
14375
- });
14376
- });
14467
+ catch (ex) {
14468
+ if (controller.signal.aborted) {
14469
+ // .read() completes with an error if we cancel the reader, which we do to disconnect. So this is just
14470
+ // things working as intended, we can return a done event and consider the exception handled.
14471
+ return doneResult;
14472
+ }
14473
+ throw ex;
14377
14474
  }
14378
14475
  }
14379
14476
  };
14380
- consumeStream().catch(ex => this.logger.error('Error consuming stream', ex));
14381
- const l = stream.registerListener({
14382
- closed: () => {
14383
- closeReader();
14384
- l?.();
14385
- }
14386
- });
14387
- return stream;
14477
+ return { isBson: responseIsBson, stream };
14478
+ }
14479
+ /**
14480
+ * Posts a `/sync/stream` request.
14481
+ *
14482
+ * Depending on the `Content-Type` of the response, this returns strings for sync lines or encoded BSON documents as
14483
+ * {@link Uint8Array}s.
14484
+ */
14485
+ async fetchStream(options) {
14486
+ const { isBson, stream } = await this.fetchStreamRaw(options);
14487
+ if (isBson) {
14488
+ return extractBsonObjects(stream);
14489
+ }
14490
+ else {
14491
+ return extractJsonLines(stream, this.createTextDecoder());
14492
+ }
14388
14493
  }
14389
14494
  }
14390
14495
 
@@ -14519,6 +14624,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
14519
14624
  streamingSyncPromise;
14520
14625
  logger;
14521
14626
  activeStreams;
14627
+ connectionMayHaveChanged = false;
14522
14628
  isUploadingCrud = false;
14523
14629
  notifyCompletedUploads;
14524
14630
  handleActiveStreamsChange;
@@ -14798,6 +14904,11 @@ The next upload iteration will be delayed.`);
14798
14904
  shouldDelayRetry = false;
14799
14905
  // A disconnect was requested, we should not delay since there is no explicit retry
14800
14906
  }
14907
+ else if (this.connectionMayHaveChanged && ex.message?.indexOf('No iteration is active') >= 0) {
14908
+ this.connectionMayHaveChanged = false;
14909
+ this.logger.info('Sync error after changed connection, retrying immediately');
14910
+ shouldDelayRetry = false;
14911
+ }
14801
14912
  else {
14802
14913
  this.logger.error(ex);
14803
14914
  }
@@ -14828,6 +14939,15 @@ The next upload iteration will be delayed.`);
14828
14939
  // Mark as disconnected if here
14829
14940
  this.updateSyncStatus({ connected: false, connecting: false });
14830
14941
  }
14942
+ markConnectionMayHaveChanged() {
14943
+ // By setting this field, we'll immediately retry if the next sync event causes an error triggered by us not having
14944
+ // an active sync iteration on the connection in use.
14945
+ this.connectionMayHaveChanged = true;
14946
+ // This triggers a `powersync_control` invocation if a sync iteration is currently active. This is a cheap call to
14947
+ // make when no subscriptions have actually changed, we're mainly interested in this immediately throwing if no
14948
+ // iteration is active. That allows us to reconnect ASAP, instead of having to wait for the next sync line.
14949
+ this.handleActiveStreamsChange?.();
14950
+ }
14831
14951
  async collectLocalBucketState() {
14832
14952
  const bucketEntries = await this.options.adapter.getBucketStates();
14833
14953
  const req = bucketEntries.map((entry) => ({
@@ -14892,6 +15012,19 @@ The next upload iteration will be delayed.`);
14892
15012
  }
14893
15013
  });
14894
15014
  }
15015
+ async receiveSyncLines(data) {
15016
+ const { options, connection, bson } = data;
15017
+ const remote = this.options.remote;
15018
+ if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
15019
+ return await remote.fetchStream(options);
15020
+ }
15021
+ else {
15022
+ return await this.options.remote.socketStreamRaw({
15023
+ ...options,
15024
+ ...{ fetchStrategy: connection.fetchStrategy }
15025
+ }, bson);
15026
+ }
15027
+ }
14895
15028
  async legacyStreamingSyncIteration(signal, resolvedOptions) {
14896
15029
  const rawTables = resolvedOptions.serializedSchema?.raw_tables;
14897
15030
  if (rawTables != null && rawTables.length) {
@@ -14921,42 +15054,27 @@ The next upload iteration will be delayed.`);
14921
15054
  client_id: clientId
14922
15055
  }
14923
15056
  };
14924
- let stream;
14925
- if (resolvedOptions?.connectionMethod == SyncStreamConnectionMethod.HTTP) {
14926
- stream = await this.options.remote.postStreamRaw(syncOptions, (line) => {
14927
- if (typeof line == 'string') {
14928
- return JSON.parse(line);
14929
- }
14930
- else {
14931
- // Directly enqueued by us
14932
- return line;
14933
- }
14934
- });
14935
- }
14936
- else {
14937
- const bson = await this.options.remote.getBSON();
14938
- stream = await this.options.remote.socketStreamRaw({
14939
- ...syncOptions,
14940
- ...{ fetchStrategy: resolvedOptions.fetchStrategy }
14941
- }, (payload) => {
14942
- if (payload instanceof Uint8Array) {
14943
- return bson.deserialize(payload);
14944
- }
14945
- else {
14946
- // Directly enqueued by us
14947
- return payload;
14948
- }
14949
- }, bson);
14950
- }
15057
+ const bson = await this.options.remote.getBSON();
15058
+ const source = await this.receiveSyncLines({
15059
+ options: syncOptions,
15060
+ connection: resolvedOptions,
15061
+ bson
15062
+ });
15063
+ const stream = injectable(map(source, (line) => {
15064
+ if (typeof line == 'string') {
15065
+ return JSON.parse(line);
15066
+ }
15067
+ else {
15068
+ return bson.deserialize(line);
15069
+ }
15070
+ }));
14951
15071
  this.logger.debug('Stream established. Processing events');
14952
15072
  this.notifyCompletedUploads = () => {
14953
- if (!stream.closed) {
14954
- stream.enqueueData({ crud_upload_completed: null });
14955
- }
15073
+ stream.inject({ crud_upload_completed: null });
14956
15074
  };
14957
- while (!stream.closed) {
14958
- const line = await stream.read();
14959
- if (!line) {
15075
+ while (true) {
15076
+ const { value: line, done } = await stream.next();
15077
+ if (done) {
14960
15078
  // The stream has closed while waiting
14961
15079
  return;
14962
15080
  }
@@ -15135,14 +15253,17 @@ The next upload iteration will be delayed.`);
15135
15253
  const syncImplementation = this;
15136
15254
  const adapter = this.options.adapter;
15137
15255
  const remote = this.options.remote;
15256
+ const controller = new AbortController();
15257
+ const abort = () => {
15258
+ return controller.abort(signal.reason);
15259
+ };
15260
+ signal.addEventListener('abort', abort);
15138
15261
  let receivingLines = null;
15139
15262
  let hadSyncLine = false;
15140
15263
  let hideDisconnectOnRestart = false;
15141
15264
  if (signal.aborted) {
15142
15265
  throw new AbortOperation('Connection request has been aborted');
15143
15266
  }
15144
- const abortController = new AbortController();
15145
- signal.addEventListener('abort', () => abortController.abort());
15146
15267
  // Pending sync lines received from the service, as well as local events that trigger a powersync_control
15147
15268
  // invocation (local events include refreshed tokens and completed uploads).
15148
15269
  // This is a single data stream so that we can handle all control calls from a single place.
@@ -15150,49 +15271,36 @@ The next upload iteration will be delayed.`);
15150
15271
  async function connect(instr) {
15151
15272
  const syncOptions = {
15152
15273
  path: '/sync/stream',
15153
- abortSignal: abortController.signal,
15274
+ abortSignal: controller.signal,
15154
15275
  data: instr.request
15155
15276
  };
15156
- if (resolvedOptions.connectionMethod == SyncStreamConnectionMethod.HTTP) {
15157
- controlInvocations = await remote.postStreamRaw(syncOptions, (line) => {
15158
- if (typeof line == 'string') {
15159
- return {
15160
- command: PowerSyncControlCommand.PROCESS_TEXT_LINE,
15161
- payload: line
15162
- };
15163
- }
15164
- else {
15165
- // Directly enqueued by us
15166
- return line;
15167
- }
15168
- });
15169
- }
15170
- else {
15171
- controlInvocations = await remote.socketStreamRaw({
15172
- ...syncOptions,
15173
- fetchStrategy: resolvedOptions.fetchStrategy
15174
- }, (payload) => {
15175
- if (payload instanceof Uint8Array) {
15176
- return {
15177
- command: PowerSyncControlCommand.PROCESS_BSON_LINE,
15178
- payload: payload
15179
- };
15180
- }
15181
- else {
15182
- // Directly enqueued by us
15183
- return payload;
15184
- }
15185
- });
15186
- }
15277
+ controlInvocations = injectable(map(await syncImplementation.receiveSyncLines({
15278
+ options: syncOptions,
15279
+ connection: resolvedOptions
15280
+ }), (line) => {
15281
+ if (typeof line == 'string') {
15282
+ return {
15283
+ command: PowerSyncControlCommand.PROCESS_TEXT_LINE,
15284
+ payload: line
15285
+ };
15286
+ }
15287
+ else {
15288
+ return {
15289
+ command: PowerSyncControlCommand.PROCESS_BSON_LINE,
15290
+ payload: line
15291
+ };
15292
+ }
15293
+ }));
15187
15294
  // The rust client will set connected: true after the first sync line because that's when it gets invoked, but
15188
15295
  // we're already connected here and can report that.
15189
15296
  syncImplementation.updateSyncStatus({ connected: true });
15190
15297
  try {
15191
- while (!controlInvocations.closed) {
15192
- const line = await controlInvocations.read();
15193
- if (line == null) {
15194
- return;
15298
+ while (true) {
15299
+ let event = await controlInvocations.next();
15300
+ if (event.done) {
15301
+ break;
15195
15302
  }
15303
+ const line = event.value;
15196
15304
  await control(line.command, line.payload);
15197
15305
  if (!hadSyncLine) {
15198
15306
  syncImplementation.triggerCrudUpload();
@@ -15201,12 +15309,8 @@ The next upload iteration will be delayed.`);
15201
15309
  }
15202
15310
  }
15203
15311
  finally {
15204
- const activeInstructions = controlInvocations;
15205
- // We concurrently add events to the active data stream when e.g. a CRUD upload is completed or a token is
15206
- // refreshed. That would throw after closing (and we can't handle those events either way), so set this back
15207
- // to null.
15208
- controlInvocations = null;
15209
- await activeInstructions.close();
15312
+ abort();
15313
+ signal.removeEventListener('abort', abort);
15210
15314
  }
15211
15315
  }
15212
15316
  async function stop() {
@@ -15216,6 +15320,10 @@ The next upload iteration will be delayed.`);
15216
15320
  const rawResponse = await adapter.control(op, payload ?? null);
15217
15321
  const logger = syncImplementation.logger;
15218
15322
  logger.trace('powersync_control', op, payload == null || typeof payload == 'string' ? payload : '<bytes>', rawResponse);
15323
+ if (op != PowerSyncControlCommand.STOP) {
15324
+ // Evidently we have a working connection here, otherwise powersync_control would have failed.
15325
+ syncImplementation.connectionMayHaveChanged = false;
15326
+ }
15219
15327
  await handleInstructions(JSON.parse(rawResponse));
15220
15328
  }
15221
15329
  async function handleInstruction(instruction) {
@@ -15250,14 +15358,14 @@ The next upload iteration will be delayed.`);
15250
15358
  remote.invalidateCredentials();
15251
15359
  // Restart iteration after the credentials have been refreshed.
15252
15360
  remote.fetchCredentials().then((_) => {
15253
- controlInvocations?.enqueueData({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
15361
+ controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
15254
15362
  }, (err) => {
15255
15363
  syncImplementation.logger.warn('Could not prefetch credentials', err);
15256
15364
  });
15257
15365
  }
15258
15366
  }
15259
15367
  else if ('CloseSyncStream' in instruction) {
15260
- abortController.abort();
15368
+ controller.abort();
15261
15369
  hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
15262
15370
  }
15263
15371
  else if ('FlushFileSystem' in instruction) ;
@@ -15286,17 +15394,13 @@ The next upload iteration will be delayed.`);
15286
15394
  }
15287
15395
  await control(PowerSyncControlCommand.START, JSON.stringify(options));
15288
15396
  this.notifyCompletedUploads = () => {
15289
- if (controlInvocations && !controlInvocations?.closed) {
15290
- controlInvocations.enqueueData({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
15291
- }
15397
+ controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
15292
15398
  };
15293
15399
  this.handleActiveStreamsChange = () => {
15294
- if (controlInvocations && !controlInvocations?.closed) {
15295
- controlInvocations.enqueueData({
15296
- command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
15297
- payload: JSON.stringify(this.activeStreams)
15298
- });
15299
- }
15400
+ controlInvocations?.inject({
15401
+ command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
15402
+ payload: JSON.stringify(this.activeStreams)
15403
+ });
15300
15404
  };
15301
15405
  await receivingLines;
15302
15406
  }
@@ -15947,7 +16051,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
15947
16051
  this._schema = schema;
15948
16052
  this.ready = false;
15949
16053
  this.sdkVersion = '';
15950
- this.runExclusiveMutex = new async_mutex__WEBPACK_IMPORTED_MODULE_0__.Mutex();
16054
+ this.runExclusiveMutex = new Mutex();
15951
16055
  // Start async init
15952
16056
  this.subscriptions = {
15953
16057
  firstStatusMatching: (predicate, abort) => this.waitForStatus(predicate, abort),
@@ -16412,6 +16516,10 @@ SELECT * FROM crud_entries;
16412
16516
  * Execute a SQL write (INSERT/UPDATE/DELETE) query
16413
16517
  * and optionally return results.
16414
16518
  *
16519
+ * When using the default client-side [JSON-based view system](https://docs.powersync.com/architecture/client-architecture#client-side-schema-and-sqlite-database-structure),
16520
+ * the returned result's `rowsAffected` may be `0` for successful `UPDATE` and `DELETE` statements.
16521
+ * Use a `RETURNING` clause and inspect `result.rows` when you need to confirm which rows changed.
16522
+ *
16415
16523
  * @param sql The SQL query to execute
16416
16524
  * @param parameters Optional array of parameters to bind to the query
16417
16525
  * @returns The query result as an object with structured key-value pairs
@@ -16508,7 +16616,7 @@ SELECT * FROM crud_entries;
16508
16616
  async readTransaction(callback, lockTimeout = DEFAULT_LOCK_TIMEOUT_MS) {
16509
16617
  await this.waitForReady();
16510
16618
  return this.database.readTransaction(async (tx) => {
16511
- const res = await callback({ ...tx });
16619
+ const res = await callback(tx);
16512
16620
  await tx.rollback();
16513
16621
  return res;
16514
16622
  }, { timeoutMs: lockTimeout });
@@ -17285,10 +17393,8 @@ class Schema {
17285
17393
  * developer instead of automatically by PowerSync.
17286
17394
  * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
17287
17395
  * using client-side table and column constraints.
17288
- * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
17289
17396
  *
17290
17397
  * @param tables An object of (table name, raw table definition) entries.
17291
- * @experimental Note that the raw tables API is still experimental and may change in the future.
17292
17398
  */
17293
17399
  withRawTables(tables) {
17294
17400
  for (const [name, rawTableDefinition] of Object.entries(tables)) {
@@ -17661,12 +17767,10 @@ var __webpack_exports__ = {};
17661
17767
  !*** ./lib/src/worker/db/WASQLiteDB.worker.js ***!
17662
17768
  \************************************************/
17663
17769
  __webpack_require__.r(__webpack_exports__);
17664
- /* 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");
17770
+ /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
17665
17771
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
17666
17772
  /* 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");
17667
- /* harmony import */ var _shared_navigator_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/navigator.js */ "./lib/src/shared/navigator.js");
17668
- /* harmony import */ var _SharedWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SharedWASQLiteConnection.js */ "./lib/src/worker/db/SharedWASQLiteConnection.js");
17669
- /* harmony import */ var _WorkerWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./WorkerWASQLiteConnection.js */ "./lib/src/worker/db/WorkerWASQLiteConnection.js");
17773
+ /* harmony import */ var _MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./MultiDatabaseServer.js */ "./lib/src/worker/db/MultiDatabaseServer.js");
17670
17774
  /**
17671
17775
  * Supports both shared and dedicated workers, based on how the worker is constructed (new SharedWorker vs new Worker()).
17672
17776
  */
@@ -17674,67 +17778,28 @@ __webpack_require__.r(__webpack_exports__);
17674
17778
 
17675
17779
 
17676
17780
 
17677
-
17678
-
17679
17781
  const baseLogger = (0,_powersync_common__WEBPACK_IMPORTED_MODULE_1__.createBaseLogger)();
17680
17782
  baseLogger.useDefaults();
17681
17783
  const logger = (0,_powersync_common__WEBPACK_IMPORTED_MODULE_1__.createLogger)('db-worker');
17682
- const DBMap = new Map();
17683
- const OPEN_DB_LOCK = 'open-wasqlite-db';
17684
- let nextClientId = 1;
17685
- const openDBShared = async (options) => {
17686
- // Prevent multiple simultaneous opens from causing race conditions
17687
- return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_3__.getNavigatorLocks)().request(OPEN_DB_LOCK, async () => {
17688
- const clientId = nextClientId++;
17689
- const { dbFilename, logLevel } = options;
17690
- logger.setLevel(logLevel);
17691
- if (!DBMap.has(dbFilename)) {
17692
- const clientIds = new Set();
17693
- // This format returns proxy objects for function callbacks
17694
- const connection = new _WorkerWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_5__.WorkerWASQLiteConnection(options);
17695
- await connection.init();
17696
- connection.registerListener({
17697
- holdOverwritten: async () => {
17698
- /**
17699
- * The previous hold has been overwritten, without being released.
17700
- * we need to cleanup any resources associated with it.
17701
- * We can perform a rollback to release any potential transactions that were started.
17702
- */
17703
- await connection.execute('ROLLBACK').catch(() => { });
17704
- }
17705
- });
17706
- DBMap.set(dbFilename, {
17707
- clientIds,
17708
- db: connection
17709
- });
17710
- }
17711
- // Associates this clientId with the shared connection entry
17712
- const sharedConnection = new _SharedWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_4__.SharedWASQLiteConnection({
17713
- dbMap: DBMap,
17714
- dbFilename,
17715
- clientId,
17716
- logger
17717
- });
17718
- return comlink__WEBPACK_IMPORTED_MODULE_2__.proxy(sharedConnection);
17719
- });
17784
+ const server = new _MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__.MultiDatabaseServer(logger);
17785
+ const exposedFunctions = {
17786
+ connect: (config) => server.handleConnection(config),
17787
+ connectToExisting: ({ identifier, lockName }) => server.connectToExisting(identifier, lockName)
17720
17788
  };
17721
17789
  // Check if we're in a SharedWorker context
17722
- if (typeof SharedWorkerGlobalScope !== 'undefined') {
17790
+ if (_MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__.isSharedWorker) {
17723
17791
  const _self = self;
17724
17792
  _self.onconnect = function (event) {
17725
17793
  const port = event.ports[0];
17726
- comlink__WEBPACK_IMPORTED_MODULE_2__.expose(openDBShared, port);
17794
+ comlink__WEBPACK_IMPORTED_MODULE_2__.expose(exposedFunctions, port);
17727
17795
  };
17728
17796
  }
17729
17797
  else {
17730
17798
  // A dedicated worker can be shared externally
17731
- comlink__WEBPACK_IMPORTED_MODULE_2__.expose(openDBShared);
17799
+ comlink__WEBPACK_IMPORTED_MODULE_2__.expose(exposedFunctions);
17732
17800
  }
17733
17801
  addEventListener('unload', () => {
17734
- Array.from(DBMap.values()).forEach(async (dbConnection) => {
17735
- const { db } = dbConnection;
17736
- db.close?.();
17737
- });
17802
+ server.closeAll();
17738
17803
  });
17739
17804
 
17740
17805
  })();