@powersync/web 1.35.0 → 1.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/index.umd.js +1126 -1231
  2. package/dist/index.umd.js.map +1 -1
  3. package/dist/worker/SharedSyncImplementation.umd.js +599 -3086
  4. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
  5. package/dist/worker/WASQLiteDB.umd.js +860 -868
  6. package/dist/worker/WASQLiteDB.umd.js.map +1 -1
  7. package/lib/package.json +2 -3
  8. package/lib/src/db/PowerSyncDatabase.d.ts +1 -2
  9. package/lib/src/db/PowerSyncDatabase.js +3 -4
  10. package/lib/src/db/adapters/AsyncWebAdapter.d.ts +40 -0
  11. package/lib/src/db/adapters/AsyncWebAdapter.js +69 -0
  12. package/lib/src/db/adapters/SSRDBAdapter.d.ts +1 -2
  13. package/lib/src/db/adapters/SSRDBAdapter.js +5 -6
  14. package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.d.ts +56 -0
  15. package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js +121 -0
  16. package/lib/src/db/adapters/wa-sqlite/DatabaseClient.d.ts +54 -0
  17. package/lib/src/db/adapters/wa-sqlite/DatabaseClient.js +227 -0
  18. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.d.ts +47 -0
  19. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.js +146 -0
  20. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.d.ts +46 -0
  21. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js +147 -0
  22. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +14 -6
  23. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +66 -39
  24. package/lib/src/db/adapters/wa-sqlite/vfs.d.ts +61 -0
  25. package/lib/src/db/adapters/wa-sqlite/vfs.js +91 -0
  26. package/lib/src/db/adapters/web-sql-flags.d.ts +5 -0
  27. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.d.ts +1 -2
  28. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.js +2 -3
  29. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +4 -19
  30. package/lib/src/index.d.ts +1 -4
  31. package/lib/src/index.js +1 -4
  32. package/lib/src/shared/tab_close_signal.d.ts +11 -0
  33. package/lib/src/shared/tab_close_signal.js +26 -0
  34. package/lib/src/worker/db/MultiDatabaseServer.d.ts +17 -0
  35. package/lib/src/worker/db/MultiDatabaseServer.js +86 -0
  36. package/lib/src/worker/db/WASQLiteDB.worker.js +9 -48
  37. package/lib/src/worker/db/open-worker-database.d.ts +3 -3
  38. package/lib/src/worker/db/open-worker-database.js +1 -1
  39. package/lib/src/worker/sync/SharedSyncImplementation.d.ts +5 -6
  40. package/lib/src/worker/sync/SharedSyncImplementation.js +92 -54
  41. package/lib/tsconfig.tsbuildinfo +1 -1
  42. package/package.json +3 -4
  43. package/src/db/PowerSyncDatabase.ts +3 -3
  44. package/src/db/adapters/AsyncWebAdapter.ts +91 -0
  45. package/src/db/adapters/SSRDBAdapter.ts +7 -7
  46. package/src/db/adapters/wa-sqlite/ConcurrentConnection.ts +137 -0
  47. package/src/db/adapters/wa-sqlite/DatabaseClient.ts +325 -0
  48. package/src/db/adapters/wa-sqlite/DatabaseServer.ts +201 -0
  49. package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +191 -0
  50. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +87 -43
  51. package/src/db/adapters/wa-sqlite/vfs.ts +112 -0
  52. package/src/db/adapters/web-sql-flags.ts +6 -0
  53. package/src/db/sync/SSRWebStreamingSyncImplementation.ts +2 -3
  54. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +4 -20
  55. package/src/index.ts +1 -4
  56. package/src/shared/tab_close_signal.ts +28 -0
  57. package/src/worker/db/MultiDatabaseServer.ts +104 -0
  58. package/src/worker/db/WASQLiteDB.worker.ts +10 -57
  59. package/src/worker/db/open-worker-database.ts +3 -3
  60. package/src/worker/sync/SharedSyncImplementation.ts +118 -58
  61. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js +0 -1878
  62. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js.map +0 -1
  63. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js +0 -555
  64. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js.map +0 -1
  65. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.d.ts +0 -17
  66. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.js +0 -33
  67. package/lib/src/db/adapters/AsyncDatabaseConnection.d.ts +0 -49
  68. package/lib/src/db/adapters/AsyncDatabaseConnection.js +0 -1
  69. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.d.ts +0 -109
  70. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.js +0 -401
  71. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.d.ts +0 -59
  72. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js +0 -147
  73. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.d.ts +0 -12
  74. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.js +0 -19
  75. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.d.ts +0 -155
  76. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js +0 -401
  77. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.d.ts +0 -32
  78. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.js +0 -49
  79. package/lib/src/worker/db/SharedWASQLiteConnection.d.ts +0 -42
  80. package/lib/src/worker/db/SharedWASQLiteConnection.js +0 -90
  81. package/lib/src/worker/db/WorkerWASQLiteConnection.d.ts +0 -9
  82. package/lib/src/worker/db/WorkerWASQLiteConnection.js +0 -12
  83. package/src/db/adapters/AbstractWebSQLOpenFactory.ts +0 -48
  84. package/src/db/adapters/AsyncDatabaseConnection.ts +0 -55
  85. package/src/db/adapters/LockedAsyncDatabaseAdapter.ts +0 -490
  86. package/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.ts +0 -201
  87. package/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.ts +0 -23
  88. package/src/db/adapters/wa-sqlite/WASQLiteConnection.ts +0 -497
  89. package/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.ts +0 -86
  90. package/src/worker/db/SharedWASQLiteConnection.ts +0 -131
  91. package/src/worker/db/WorkerWASQLiteConnection.ts +0 -14
@@ -1,401 +0,0 @@
1
- import * as SQLite from '@journeyapps/wa-sqlite';
2
- import { BaseObserver } from '@powersync/common';
3
- import { Mutex } from 'async-mutex';
4
- /**
5
- * List of currently tested virtual filesystems
6
- */
7
- export var WASQLiteVFS;
8
- (function (WASQLiteVFS) {
9
- WASQLiteVFS["IDBBatchAtomicVFS"] = "IDBBatchAtomicVFS";
10
- WASQLiteVFS["OPFSCoopSyncVFS"] = "OPFSCoopSyncVFS";
11
- WASQLiteVFS["AccessHandlePoolVFS"] = "AccessHandlePoolVFS";
12
- })(WASQLiteVFS || (WASQLiteVFS = {}));
13
- /**
14
- * @internal
15
- */
16
- export const AsyncWASQLiteModuleFactory = async () => {
17
- const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');
18
- return factory();
19
- };
20
- /**
21
- * @internal
22
- */
23
- export const MultiCipherAsyncWASQLiteModuleFactory = async () => {
24
- const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs');
25
- return factory();
26
- };
27
- /**
28
- * @internal
29
- */
30
- export const SyncWASQLiteModuleFactory = async () => {
31
- const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite.mjs');
32
- return factory();
33
- };
34
- /**
35
- * @internal
36
- */
37
- export const MultiCipherSyncWASQLiteModuleFactory = async () => {
38
- const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs');
39
- return factory();
40
- };
41
- /**
42
- * @internal
43
- */
44
- export const DEFAULT_MODULE_FACTORIES = {
45
- [WASQLiteVFS.IDBBatchAtomicVFS]: async (options) => {
46
- let module;
47
- if (options.encryptionKey) {
48
- module = await MultiCipherAsyncWASQLiteModuleFactory();
49
- }
50
- else {
51
- module = await AsyncWASQLiteModuleFactory();
52
- }
53
- const { IDBBatchAtomicVFS } = await import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');
54
- return {
55
- module,
56
- // @ts-expect-error The types for this static method are missing upstream
57
- vfs: await IDBBatchAtomicVFS.create(options.dbFileName, module, { lockPolicy: 'exclusive' })
58
- };
59
- },
60
- [WASQLiteVFS.AccessHandlePoolVFS]: async (options) => {
61
- let module;
62
- if (options.encryptionKey) {
63
- module = await MultiCipherSyncWASQLiteModuleFactory();
64
- }
65
- else {
66
- module = await SyncWASQLiteModuleFactory();
67
- }
68
- // @ts-expect-error The types for this static method are missing upstream
69
- const { AccessHandlePoolVFS } = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');
70
- return {
71
- module,
72
- vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)
73
- };
74
- },
75
- [WASQLiteVFS.OPFSCoopSyncVFS]: async (options) => {
76
- let module;
77
- if (options.encryptionKey) {
78
- module = await MultiCipherSyncWASQLiteModuleFactory();
79
- }
80
- else {
81
- module = await SyncWASQLiteModuleFactory();
82
- }
83
- // @ts-expect-error The types for this static method are missing upstream
84
- const { OPFSCoopSyncVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');
85
- const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);
86
- return {
87
- module,
88
- vfs
89
- };
90
- }
91
- };
92
- /**
93
- * @internal
94
- * WA-SQLite connection which directly interfaces with WA-SQLite.
95
- * This is usually instantiated inside a worker.
96
- */
97
- export class WASqliteConnection extends BaseObserver {
98
- options;
99
- _sqliteAPI = null;
100
- _dbP = null;
101
- _moduleFactory;
102
- updatedTables;
103
- updateTimer;
104
- statementMutex;
105
- broadcastChannel;
106
- /**
107
- * Unique id for this specific connection. This is used to prevent broadcast table change
108
- * notification loops.
109
- */
110
- connectionId;
111
- _holdCounter;
112
- _holdId;
113
- constructor(options) {
114
- super();
115
- this.options = options;
116
- this.updatedTables = new Set();
117
- this.updateTimer = null;
118
- this.broadcastChannel = null;
119
- this.connectionId = new Date().valueOf() + Math.random();
120
- this.statementMutex = new Mutex();
121
- this._moduleFactory = DEFAULT_MODULE_FACTORIES[this.options.vfs];
122
- this._holdCounter = 0;
123
- this._holdId = null;
124
- }
125
- /**
126
- * Gets the id for the current hold.
127
- * This can be used to check for invalid states.
128
- */
129
- get currentHoldId() {
130
- return this._holdId;
131
- }
132
- get sqliteAPI() {
133
- if (!this._sqliteAPI) {
134
- throw new Error(`Initialization has not completed`);
135
- }
136
- return this._sqliteAPI;
137
- }
138
- get dbP() {
139
- if (!this._dbP) {
140
- throw new Error(`Initialization has not completed`);
141
- }
142
- return this._dbP;
143
- }
144
- /**
145
- * Checks if the database connection is in autocommit mode.
146
- * @returns true if in autocommit mode, false if in a transaction
147
- */
148
- async isAutoCommit() {
149
- return this.sqliteAPI.get_autocommit(this.dbP) != 0;
150
- }
151
- async markHold() {
152
- const previousHoldId = this._holdId;
153
- this._holdId = `${++this._holdCounter}`;
154
- if (previousHoldId) {
155
- await this.iterateAsyncListeners(async (cb) => cb.holdOverwritten?.(previousHoldId));
156
- }
157
- return this._holdId;
158
- }
159
- async releaseHold(holdId) {
160
- if (holdId != this._holdId) {
161
- throw new Error(`Invalid hold state, expected ${this._holdId} but got ${holdId}`);
162
- }
163
- this._holdId = null;
164
- }
165
- async openDB() {
166
- this._dbP = await this.sqliteAPI.open_v2(this.options.dbFilename);
167
- return this._dbP;
168
- }
169
- async executeEncryptionPragma() {
170
- if (this.options.encryptionKey) {
171
- await this.executeSingleStatement(`PRAGMA key = "${this.options.encryptionKey}"`);
172
- }
173
- return;
174
- }
175
- async openSQLiteAPI() {
176
- const { module, vfs } = await this._moduleFactory({
177
- dbFileName: this.options.dbFilename,
178
- encryptionKey: this.options.encryptionKey
179
- });
180
- const sqlite3 = SQLite.Factory(module);
181
- sqlite3.vfs_register(vfs, true);
182
- /**
183
- * Register the PowerSync core SQLite extension
184
- */
185
- module.ccall('powersync_init_static', 'int', []);
186
- /**
187
- * Create the multiple cipher vfs if an encryption key is provided
188
- */
189
- if (this.options.encryptionKey) {
190
- const createResult = module.ccall('sqlite3mc_vfs_create', 'int', ['string', 'int'], [this.options.dbFilename, 1]);
191
- if (createResult !== 0) {
192
- throw new Error('Failed to create multiple cipher vfs, Database encryption will not work');
193
- }
194
- }
195
- return sqlite3;
196
- }
197
- registerBroadcastListeners() {
198
- this.broadcastChannel = new BroadcastChannel(`${this.options.dbFilename}-table-updates`);
199
- this.broadcastChannel.addEventListener('message', (event) => {
200
- const data = event.data;
201
- if (this.connectionId == data.connectionId) {
202
- // Ignore messages from the same connection
203
- return;
204
- }
205
- // Ensuring that we don't rebroadcast the same message
206
- this.queueTableUpdate(data.changedTables, false);
207
- });
208
- }
209
- queueTableUpdate(tableNames, shouldBroadcast = true) {
210
- tableNames.forEach((tableName) => this.updatedTables.add(tableName));
211
- if (this.updateTimer == null) {
212
- this.updateTimer = setTimeout(() => this.fireUpdates(shouldBroadcast), 0);
213
- }
214
- }
215
- async init() {
216
- this._sqliteAPI = await this.openSQLiteAPI();
217
- await this.openDB();
218
- this.registerBroadcastListeners();
219
- await this.executeSingleStatement(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
220
- await this.executeEncryptionPragma();
221
- await this.executeSingleStatement(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);
222
- this.sqliteAPI.update_hook(this.dbP, (updateType, dbName, tableName) => {
223
- if (!tableName) {
224
- return;
225
- }
226
- const changedTables = new Set([tableName]);
227
- this.queueTableUpdate(changedTables);
228
- });
229
- }
230
- async getConfig() {
231
- return this.options;
232
- }
233
- fireUpdates(shouldBroadcast = true) {
234
- this.updateTimer = null;
235
- const event = { tables: [...this.updatedTables], groupedUpdates: {}, rawUpdates: [] };
236
- // Share to other connections
237
- if (shouldBroadcast) {
238
- this.broadcastChannel.postMessage({
239
- changedTables: this.updatedTables,
240
- connectionId: this.connectionId
241
- });
242
- }
243
- this.updatedTables.clear();
244
- this.iterateListeners((cb) => cb.tablesUpdated?.(event));
245
- }
246
- /**
247
- * This executes SQL statements in a batch.
248
- */
249
- async executeBatch(sql, bindings) {
250
- return this.acquireExecuteLock(async () => {
251
- let affectedRows = 0;
252
- try {
253
- await this.executeSingleStatement('BEGIN TRANSACTION');
254
- const wrappedBindings = bindings ? bindings : [];
255
- for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {
256
- if (stmt === null) {
257
- return {
258
- rowsAffected: 0,
259
- rows: { _array: [], length: 0 }
260
- };
261
- }
262
- //Prepare statement once
263
- for (const binding of wrappedBindings) {
264
- // TODO not sure why this is needed currently, but booleans break
265
- for (let i = 0; i < binding.length; i++) {
266
- const b = binding[i];
267
- if (typeof b == 'boolean') {
268
- binding[i] = b ? 1 : 0;
269
- }
270
- }
271
- if (bindings) {
272
- this.sqliteAPI.bind_collection(stmt, binding);
273
- }
274
- const result = await this.sqliteAPI.step(stmt);
275
- if (result === SQLite.SQLITE_DONE) {
276
- //The value returned by sqlite3_changes() immediately after an INSERT, UPDATE or DELETE statement run on a view is always zero.
277
- affectedRows += this.sqliteAPI.changes(this.dbP);
278
- }
279
- this.sqliteAPI.reset(stmt);
280
- }
281
- }
282
- await this.executeSingleStatement('COMMIT');
283
- }
284
- catch (err) {
285
- await this.executeSingleStatement('ROLLBACK');
286
- return {
287
- rowsAffected: 0,
288
- rows: { _array: [], length: 0 }
289
- };
290
- }
291
- const result = {
292
- rowsAffected: affectedRows,
293
- rows: { _array: [], length: 0 }
294
- };
295
- return result;
296
- });
297
- }
298
- /**
299
- * This executes single SQL statements inside a requested lock.
300
- */
301
- async execute(sql, bindings) {
302
- // Running multiple statements on the same connection concurrently should not be allowed
303
- return this.acquireExecuteLock(async () => {
304
- return this.executeSingleStatement(sql, bindings);
305
- });
306
- }
307
- async executeRaw(sql, bindings) {
308
- return this.acquireExecuteLock(async () => {
309
- return this.executeSingleStatementRaw(sql, bindings);
310
- });
311
- }
312
- async close() {
313
- this.broadcastChannel?.close();
314
- await this.acquireExecuteLock(async () => {
315
- /**
316
- * Running the close operation inside the same execute mutex prevents errors like:
317
- * ```
318
- * unable to close due to unfinalized statements or unfinished backups
319
- * ```
320
- */
321
- await this.sqliteAPI.close(this.dbP);
322
- });
323
- }
324
- async registerOnTableChange(callback) {
325
- return this.registerListener({
326
- tablesUpdated: (event) => callback(event)
327
- });
328
- }
329
- /**
330
- * This requests a lock for executing statements.
331
- * Should only be used internally.
332
- */
333
- acquireExecuteLock = (callback) => {
334
- return this.statementMutex.runExclusive(callback);
335
- };
336
- /**
337
- * This executes a single statement using SQLite3.
338
- */
339
- async executeSingleStatement(sql, bindings) {
340
- const results = await this._execute(sql, bindings);
341
- const rows = [];
342
- for (const resultSet of results) {
343
- for (const row of resultSet.rows) {
344
- const outRow = {};
345
- resultSet.columns.forEach((key, index) => {
346
- outRow[key] = row[index];
347
- });
348
- rows.push(outRow);
349
- }
350
- }
351
- const result = {
352
- insertId: this.sqliteAPI.last_insert_id(this.dbP),
353
- rowsAffected: this.sqliteAPI.changes(this.dbP),
354
- rows: {
355
- _array: rows,
356
- length: rows.length
357
- }
358
- };
359
- return result;
360
- }
361
- /**
362
- * This executes a single statement using SQLite3 and returns the results as an array of arrays.
363
- */
364
- async executeSingleStatementRaw(sql, bindings) {
365
- const results = await this._execute(sql, bindings);
366
- return results.flatMap((resultset) => resultset.rows.map((row) => resultset.columns.map((_, index) => row[index])));
367
- }
368
- async _execute(sql, bindings) {
369
- const results = [];
370
- for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {
371
- let columns;
372
- const wrappedBindings = bindings ? [bindings] : [[]];
373
- for (const binding of wrappedBindings) {
374
- // TODO not sure why this is needed currently, but booleans break
375
- binding.forEach((b, index, arr) => {
376
- if (typeof b == 'boolean') {
377
- arr[index] = b ? 1 : 0;
378
- }
379
- });
380
- this.sqliteAPI.reset(stmt);
381
- if (bindings) {
382
- this.sqliteAPI.bind_collection(stmt, binding);
383
- }
384
- const rows = [];
385
- while ((await this.sqliteAPI.step(stmt)) === SQLite.SQLITE_ROW) {
386
- const row = this.sqliteAPI.row(stmt);
387
- rows.push(row);
388
- }
389
- columns = columns ?? this.sqliteAPI.column_names(stmt);
390
- if (columns.length) {
391
- results.push({ columns, rows });
392
- }
393
- }
394
- // When binding parameters, only a single statement is executed.
395
- if (bindings) {
396
- break;
397
- }
398
- }
399
- return results;
400
- }
401
- }
@@ -1,32 +0,0 @@
1
- import { type PowerSyncOpenFactoryOptions } from '@powersync/common';
2
- import { ResolvedWebSQLOpenOptions, TemporaryStorageOption, WebSQLFlags } from '../web-sql-flags.js';
3
- import { InternalWASQLiteDBAdapter } from './InternalWASQLiteDBAdapter.js';
4
- import { WASQLiteVFS } from './WASQLiteConnection.js';
5
- /**
6
- * These flags are the same as {@link WebSQLFlags}.
7
- * This export is maintained only for API consistency
8
- */
9
- export type WASQLiteFlags = WebSQLFlags;
10
- export interface WASQLiteDBAdapterOptions extends Omit<PowerSyncOpenFactoryOptions, 'schema'> {
11
- flags?: WASQLiteFlags;
12
- /**
13
- * Use an existing port to an initialized worker.
14
- * A worker will be initialized if none is provided
15
- */
16
- workerPort?: MessagePort;
17
- worker?: string | URL | ((options: ResolvedWebSQLOpenOptions) => Worker | SharedWorker);
18
- vfs?: WASQLiteVFS;
19
- temporaryStorage?: TemporaryStorageOption;
20
- cacheSizeKb?: number;
21
- /**
22
- * Encryption key for the database.
23
- * If set, the database will be encrypted using multiple-ciphers.
24
- */
25
- encryptionKey?: string;
26
- }
27
- /**
28
- * Adapter for WA-SQLite SQLite connections.
29
- */
30
- export declare class WASQLiteDBAdapter extends InternalWASQLiteDBAdapter {
31
- constructor(options: WASQLiteDBAdapterOptions);
32
- }
@@ -1,49 +0,0 @@
1
- import * as Comlink from 'comlink';
2
- import { resolveWebPowerSyncFlags } from '../../PowerSyncDatabase.js';
3
- import { DEFAULT_CACHE_SIZE_KB, TemporaryStorageOption } from '../web-sql-flags.js';
4
- import { WorkerWrappedAsyncDatabaseConnection } from '../WorkerWrappedAsyncDatabaseConnection.js';
5
- import { InternalWASQLiteDBAdapter } from './InternalWASQLiteDBAdapter.js';
6
- import { WASQLiteOpenFactory } from './WASQLiteOpenFactory.js';
7
- /**
8
- * Adapter for WA-SQLite SQLite connections.
9
- */
10
- export class WASQLiteDBAdapter extends InternalWASQLiteDBAdapter {
11
- constructor(options) {
12
- super({
13
- name: options.dbFilename,
14
- openConnection: async () => {
15
- const { workerPort, temporaryStorage, cacheSizeKb } = options;
16
- if (workerPort) {
17
- const remote = Comlink.wrap(workerPort);
18
- return new WorkerWrappedAsyncDatabaseConnection({
19
- remote,
20
- remoteCanCloseUnexpectedly: false,
21
- identifier: options.dbFilename,
22
- baseConnection: await remote({
23
- ...options,
24
- temporaryStorage: temporaryStorage ?? TemporaryStorageOption.MEMORY,
25
- cacheSizeKb: cacheSizeKb ?? DEFAULT_CACHE_SIZE_KB,
26
- flags: resolveWebPowerSyncFlags(options.flags),
27
- encryptionKey: options.encryptionKey
28
- })
29
- });
30
- }
31
- const openFactory = new WASQLiteOpenFactory({
32
- dbFilename: options.dbFilename,
33
- dbLocation: options.dbLocation,
34
- debugMode: options.debugMode,
35
- flags: options.flags,
36
- temporaryStorage,
37
- cacheSizeKb,
38
- logger: options.logger,
39
- vfs: options.vfs,
40
- encryptionKey: options.encryptionKey,
41
- worker: options.worker
42
- });
43
- return openFactory.openConnection();
44
- },
45
- debugMode: options.debugMode,
46
- logger: options.logger
47
- });
48
- }
49
- }
@@ -1,42 +0,0 @@
1
- import { ILogger } from '@powersync/common';
2
- import { AsyncDatabaseConnection, OnTableChangeCallback, ProxiedQueryResult } from '../../db/adapters/AsyncDatabaseConnection.js';
3
- import { ResolvedWebSQLOpenOptions } from '../../db/adapters/web-sql-flags.js';
4
- /**
5
- * Keeps track of open DB connections and the clients which
6
- * are using it.
7
- */
8
- export type SharedDBWorkerConnection = {
9
- clientIds: Set<number>;
10
- db: AsyncDatabaseConnection;
11
- };
12
- export type SharedWASQLiteConnectionOptions = {
13
- dbMap: Map<string, SharedDBWorkerConnection>;
14
- dbFilename: string;
15
- clientId: number;
16
- logger: ILogger;
17
- };
18
- export declare class SharedWASQLiteConnection implements AsyncDatabaseConnection {
19
- protected options: SharedWASQLiteConnectionOptions;
20
- protected isClosing: boolean;
21
- protected activeHoldId: string | null;
22
- constructor(options: SharedWASQLiteConnectionOptions);
23
- protected get logger(): ILogger;
24
- protected get dbEntry(): SharedDBWorkerConnection;
25
- protected get connection(): AsyncDatabaseConnection<ResolvedWebSQLOpenOptions>;
26
- protected get clientIds(): Set<number>;
27
- init(): Promise<void>;
28
- markHold(): Promise<string>;
29
- releaseHold(id: string): Promise<void>;
30
- isAutoCommit(): Promise<boolean>;
31
- /**
32
- * Handles closing of a shared connection.
33
- * The connection is only closed if there are no active clients using it.
34
- */
35
- close(): Promise<void>;
36
- protected withClosing<T>(action: () => Promise<T>): Promise<T>;
37
- execute(sql: string, params?: any[]): Promise<ProxiedQueryResult>;
38
- executeRaw(sql: string, params?: any[]): Promise<any[][]>;
39
- executeBatch(sql: string, params?: any[] | undefined): Promise<ProxiedQueryResult>;
40
- registerOnTableChange(callback: OnTableChangeCallback): Promise<() => void>;
41
- getConfig(): Promise<ResolvedWebSQLOpenOptions>;
42
- }
@@ -1,90 +0,0 @@
1
- export class SharedWASQLiteConnection {
2
- options;
3
- isClosing;
4
- // Keeps track if this current hold if the shared connection has a hold
5
- activeHoldId;
6
- constructor(options) {
7
- this.options = options;
8
- // Add this client ID to the set of known clients
9
- this.clientIds.add(options.clientId);
10
- this.isClosing = false;
11
- this.activeHoldId = null;
12
- }
13
- get logger() {
14
- return this.options.logger;
15
- }
16
- get dbEntry() {
17
- return this.options.dbMap.get(this.options.dbFilename);
18
- }
19
- get connection() {
20
- return this.dbEntry.db;
21
- }
22
- get clientIds() {
23
- return this.dbEntry.clientIds;
24
- }
25
- async init() {
26
- // No-op since the connection is already initialized when it was created
27
- }
28
- async markHold() {
29
- this.activeHoldId = await this.connection.markHold();
30
- return this.activeHoldId;
31
- }
32
- async releaseHold(id) {
33
- try {
34
- await this.connection.releaseHold(id);
35
- }
36
- finally {
37
- this.activeHoldId = null;
38
- }
39
- }
40
- async isAutoCommit() {
41
- return this.connection.isAutoCommit();
42
- }
43
- /**
44
- * Handles closing of a shared connection.
45
- * The connection is only closed if there are no active clients using it.
46
- */
47
- async close() {
48
- // This prevents further statements on this connection from being executed
49
- this.isClosing = true;
50
- const { clientIds, logger } = this;
51
- const { clientId, dbFilename, dbMap } = this.options;
52
- logger.debug(`Close requested from client ${clientId} of ${[...clientIds]}`);
53
- clientIds.delete(clientId);
54
- if (this.activeHoldId) {
55
- // We can't cleanup here since we're not in a lock context.
56
- // The cleanup will occur once a new hold is acquired.
57
- this.logger.info(`Hold ${this.activeHoldId} was still active when the connection was closed. Cleanup will occur once a new hold is acquired.`);
58
- }
59
- if (clientIds.size == 0) {
60
- logger.debug(`Closing connection to ${this.options}.`);
61
- const connection = this.connection;
62
- dbMap.delete(dbFilename);
63
- await connection.close();
64
- return;
65
- }
66
- logger.debug(`Connection to ${dbFilename} not closed yet due to active clients.`);
67
- return;
68
- }
69
- async withClosing(action) {
70
- if (this.isClosing) {
71
- throw new Error('Connection is closing');
72
- }
73
- return action();
74
- }
75
- async execute(sql, params) {
76
- return this.withClosing(() => this.connection.execute(sql, params));
77
- }
78
- async executeRaw(sql, params) {
79
- return this.withClosing(() => this.connection.executeRaw(sql, params));
80
- }
81
- executeBatch(sql, params) {
82
- return this.withClosing(() => this.connection.executeBatch(sql, params));
83
- }
84
- registerOnTableChange(callback) {
85
- return this.connection.registerOnTableChange(callback);
86
- }
87
- getConfig() {
88
- return this.connection.getConfig();
89
- }
90
- }
@@ -1,9 +0,0 @@
1
- import { OnTableChangeCallback } from '../../db/adapters/AsyncDatabaseConnection.js';
2
- import { WASqliteConnection } from '../../db/adapters/wa-sqlite/WASQLiteConnection.js';
3
- /**
4
- * A Small proxy wrapper around the WASqliteConnection.
5
- * This ensures that certain return types are properly proxied.
6
- */
7
- export declare class WorkerWASQLiteConnection extends WASqliteConnection {
8
- registerOnTableChange(callback: OnTableChangeCallback): Promise<() => void>;
9
- }
@@ -1,12 +0,0 @@
1
- import * as Comlink from 'comlink';
2
- import { WASqliteConnection } from '../../db/adapters/wa-sqlite/WASQLiteConnection.js';
3
- /**
4
- * A Small proxy wrapper around the WASqliteConnection.
5
- * This ensures that certain return types are properly proxied.
6
- */
7
- export class WorkerWASQLiteConnection extends WASqliteConnection {
8
- async registerOnTableChange(callback) {
9
- // Proxy the callback remove function
10
- return Comlink.proxy(await super.registerOnTableChange(callback));
11
- }
12
- }
@@ -1,48 +0,0 @@
1
- import { DBAdapter, type ILogger, SQLOpenFactory, createLogger } from '@powersync/common';
2
- import { SSRDBAdapter } from './SSRDBAdapter.js';
3
- import { ResolvedWebSQLFlags, WebSQLOpenFactoryOptions, isServerSide, resolveWebSQLFlags } from './web-sql-flags.js';
4
-
5
- export abstract class AbstractWebSQLOpenFactory implements SQLOpenFactory {
6
- protected resolvedFlags: ResolvedWebSQLFlags;
7
- protected logger: ILogger;
8
-
9
- constructor(protected options: WebSQLOpenFactoryOptions) {
10
- this.resolvedFlags = resolveWebSQLFlags(options.flags);
11
- this.logger = options.logger ?? createLogger(`AbstractWebSQLOpenFactory - ${this.options.dbFilename}`);
12
- }
13
-
14
- /**
15
- * Opens a DBAdapter if not in SSR mode
16
- */
17
- protected abstract openAdapter(): DBAdapter;
18
-
19
- /**
20
- * Opens a {@link DBAdapter} using resolved flags.
21
- * A SSR implementation is loaded if SSR mode is detected.
22
- */
23
- openDB() {
24
- const {
25
- resolvedFlags: { disableSSRWarning, enableMultiTabs, ssrMode = isServerSide() }
26
- } = this;
27
- if (ssrMode && !disableSSRWarning) {
28
- this.logger.warn(
29
- `
30
- Running PowerSync in SSR mode.
31
- Only empty query results will be returned.
32
- Disable this warning by setting 'disableSSRWarning: true' in options.`
33
- );
34
- }
35
-
36
- if (!enableMultiTabs) {
37
- this.logger.warn(
38
- 'Multiple tab support is not enabled. Using this site across multiple tabs may not function correctly.'
39
- );
40
- }
41
-
42
- if (ssrMode) {
43
- return new SSRDBAdapter();
44
- }
45
-
46
- return this.openAdapter();
47
- }
48
- }