@powersync/capacitor 0.3.0 → 0.4.1

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.
@@ -23,7 +23,7 @@ Pod::Spec.new do |s|
23
23
  s.ios.deployment_target = '14.0'
24
24
  s.dependency 'Capacitor'
25
25
  s.swift_version = '5.1'
26
- s.dependency "powersync-sqlite-core", "~> 0.4.10"
26
+ s.dependency "powersync-sqlite-core", "~> 0.4.11"
27
27
  s.xcconfig = {
28
28
  'OTHER_CFLAGS' => '$(inherited) -DSQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION=1',
29
29
  'HEADER_SEARCH_PATHS' => '$(inherited) "$(PODS_ROOT)/SQLCipher"'
@@ -3,7 +3,7 @@ ext {
3
3
  androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.7.0'
4
4
  androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.2.1'
5
5
  androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.6.1'
6
- powerSyncCoreVersion = project.hasProperty('powerSyncCoreVersion') ? rootProject.ext.powerSyncCoreVersion : '0.4.10'
6
+ powerSyncCoreVersion = project.hasProperty('powerSyncCoreVersion') ? rootProject.ext.powerSyncCoreVersion : '0.4.11'
7
7
  }
8
8
 
9
9
  buildscript {
@@ -1,6 +1,6 @@
1
1
  import { SQLiteDBConnection } from '@capacitor-community/sqlite';
2
2
  import { BaseObserver, DBAdapter, DBAdapterListener, DBLockOptions, LockContext, QueryResult, Transaction } from '@powersync/web';
3
- import Lock from 'async-lock';
3
+ import { Mutex } from 'async-mutex';
4
4
  import { CapacitorSQLiteOpenFactoryOptions } from './CapacitorSQLiteOpenFactory.js';
5
5
  /**
6
6
  * An implementation of {@link DBAdapter} using the Capacitor Community SQLite [plugin](https://github.com/capacitor-community/sqlite).
@@ -13,7 +13,8 @@ export declare class CapacitorSQLiteAdapter extends BaseObserver<DBAdapterListen
13
13
  protected _writeConnection: SQLiteDBConnection | null;
14
14
  protected _readConnection: SQLiteDBConnection | null;
15
15
  protected initializedPromise: Promise<void>;
16
- protected lock: Lock;
16
+ protected writeMutex: Mutex;
17
+ protected readMutex: Mutex;
17
18
  constructor(options: CapacitorSQLiteOpenFactoryOptions);
18
19
  protected get writeConnection(): SQLiteDBConnection;
19
20
  protected get readConnection(): SQLiteDBConnection;
@@ -1,7 +1,7 @@
1
1
  import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';
2
2
  import { Capacitor } from '@capacitor/core';
3
- import { BaseObserver } from '@powersync/web';
4
- import Lock from 'async-lock';
3
+ import { BaseObserver, mutexRunExclusive } from '@powersync/web';
4
+ import { Mutex } from 'async-mutex';
5
5
  import { PowerSyncCore } from '../plugin/PowerSyncCore.js';
6
6
  import { messageForErrorCode } from '../plugin/PowerSyncPlugin.js';
7
7
  import { DEFAULT_SQLITE_OPTIONS } from './CapacitorSQLiteOpenFactory.js';
@@ -32,7 +32,8 @@ export class CapacitorSQLiteAdapter extends BaseObserver {
32
32
  this.options = options;
33
33
  this._writeConnection = null;
34
34
  this._readConnection = null;
35
- this.lock = new Lock();
35
+ this.writeMutex = new Mutex();
36
+ this.readMutex = new Mutex();
36
37
  this.initializedPromise = this.init();
37
38
  }
38
39
  get writeConnection() {
@@ -198,10 +199,10 @@ export class CapacitorSQLiteAdapter extends BaseObserver {
198
199
  });
199
200
  }
200
201
  readLock(fn, options) {
201
- return this.lock.acquire('read_lock', async () => {
202
+ return mutexRunExclusive(this.readMutex, async () => {
202
203
  await this.initializedPromise;
203
204
  return await fn(this.generateLockContext(this.readConnection));
204
- });
205
+ }, options);
205
206
  }
206
207
  readTransaction(fn, options) {
207
208
  return this.readLock(async (ctx) => {
@@ -209,7 +210,7 @@ export class CapacitorSQLiteAdapter extends BaseObserver {
209
210
  });
210
211
  }
211
212
  writeLock(fn, options) {
212
- return this.lock.acquire('write_lock', async () => {
213
+ return mutexRunExclusive(this.writeMutex, async () => {
213
214
  var _a;
214
215
  await this.initializedPromise;
215
216
  const result = await fn(this.generateLockContext(this.writeConnection));
@@ -226,7 +227,7 @@ export class CapacitorSQLiteAdapter extends BaseObserver {
226
227
  };
227
228
  this.iterateListeners((l) => { var _a; return (_a = l.tablesUpdated) === null || _a === void 0 ? void 0 : _a.call(l, notification); });
228
229
  return result;
229
- });
230
+ }, options);
230
231
  }
231
232
  writeTransaction(fn, options) {
232
233
  return this.writeLock(async (ctx) => {
@@ -1 +1 @@
1
- {"version":3,"file":"CapacitorSQLiteAdapter.js","sourceRoot":"","sources":["../../../src/adapter/CapacitorSQLiteAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAsB,MAAM,6BAA6B,CAAC;AACpG,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EACL,YAAY,EAQb,MAAM,gBAAgB,CAAC;AACxB,OAAO,IAAI,MAAM,YAAY,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAqC,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AAC5G;;GAEG;AACH,KAAK,UAAU,YAAY,CAAC,GAAW,EAAE,QAAoC;IAC3E,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IAChC,IAAI,CAAC;QACH,MAAM,CAAC,GAAG,MAAM,QAAQ,EAAE,CAAC;QAC3B,WAAW,CAAC,OAAO,CAAC,SAAS,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC/C,OAAO,CAAC,CAAC;IACX,CAAC;IAAC,OAAO,CAAM,EAAE,CAAC;QAChB,WAAW,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,OAAO,KAAK,GA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cesContent":["import { CapacitorSQLite, SQLiteConnection, SQLiteDBConnection } from '@capacitor-community/sqlite';\nimport { Capacitor } from '@capacitor/core';\n\nimport {\n BaseObserver,\n BatchedUpdateNotification,\n DBAdapter,\n DBAdapterListener,\n DBLockOptions,\n LockContext,\n QueryResult,\n Transaction\n} from '@powersync/web';\nimport Lock from 'async-lock';\nimport { PowerSyncCore } from '../plugin/PowerSyncCore.js';\nimport { messageForErrorCode } from '../plugin/PowerSyncPlugin.js';\nimport { CapacitorSQLiteOpenFactoryOptions, DEFAULT_SQLITE_OPTIONS } from './CapacitorSQLiteOpenFactory.js';\n/**\n * Monitors the execution time of a query and logs it to the performance timeline.\n */\nasync function monitorQuery(sql: string, executor: () => Promise<QueryResult>): Promise<QueryResult> {\n const start = performance.now();\n try {\n const r = await executor();\n performance.measure(`[SQL] ${sql}`, { start });\n return r;\n } catch (e: any) {\n performance.measure(`[SQL] [ERROR: ${e.message}] ${sql}`, { start });\n throw e;\n }\n}\n/**\n * An implementation of {@link DBAdapter} using the Capacitor Community SQLite [plugin](https://github.com/capacitor-community/sqlite).\n *\n * @experimental\n * @alpha This is currently experimental and may change without a major version bump.\n */\nexport class CapacitorSQLiteAdapter extends BaseObserver<DBAdapterListener> implements DBAdapter {\n protected _writeConnection: SQLiteDBConnection | null;\n protected _readConnection: SQLiteDBConnection | null;\n protected initializedPromise: Promise<void>;\n protected lock: Lock;\n\n constructor(protected options: CapacitorSQLiteOpenFactoryOptions) {\n super();\n this._writeConnection = null;\n this._readConnection = null;\n this.lock = new Lock();\n this.initializedPromise = this.init();\n }\n\n protected get writeConnection(): SQLiteDBConnection {\n if (!this._writeConnection) {\n throw new Error('Init not completed yet');\n }\n return this._writeConnection;\n }\n\n protected get readConnection(): SQLiteDBConnection {\n if (!this._readConnection) {\n throw new Error('Init not completed yet');\n }\n return this._readConnection;\n }\n\n get name() {\n return this.options.dbFilename;\n }\n\n private async init() {\n const { responseCode: registrationResponseCode } = await PowerSyncCore.registerCore();\n if (registrationResponseCode != 0) {\n throw new Error(`Could not register PowerSync core extension: ${messageForErrorCode(registrationResponseCode)}`);\n }\n\n const sqlite = new SQLiteConnection(CapacitorSQLite);\n\n // It seems like the isConnection and retrieveConnection methods\n // only check a JS side map of connections.\n // On hot reload this JS cache can be cleared, while the connection\n // still exists natively. and `createConnection` will fail if it already exists.\n await sqlite.closeConnection(this.options.dbFilename, false).catch(() => {});\n await sqlite.closeConnection(this.options.dbFilename, true).catch(() => {});\n\n // TODO support encryption eventually\n this._writeConnection = await sqlite.createConnection(this.options.dbFilename, false, 'no-encryption', 1, false);\n this._readConnection = await sqlite.createConnection(this.options.dbFilename, false, 'no-encryption', 1, true);\n\n await this._writeConnection.open();\n\n const { cacheSizeKb, journalSizeLimit, synchronous } = { ...DEFAULT_SQLITE_OPTIONS, ...this.options.sqliteOptions };\n\n await this.writeConnection.query('PRAGMA journal_mode = WAL');\n await this.writeConnection.query(`PRAGMA journal_size_limit = ${journalSizeLimit}`);\n await this.writeConnection.query(`PRAGMA temp_store = memory`);\n await this.writeConnection.query(`PRAGMA synchronous = ${synchronous}`);\n await this.writeConnection.query(`PRAGMA cache_size = -${cacheSizeKb}`);\n\n await this._readConnection.open();\n\n const platform = Capacitor.getPlatform();\n if (platform == 'android') {\n /**\n * SQLCipher for Android enables dynamic loading of extensions.\n * On iOS we use a static auto extension registration.\n */\n const extensionQuery = \"SELECT load_extension('libpowersync.so', 'sqlite3_powersync_init')\";\n await this.writeConnection.query(extensionQuery);\n await this.readConnection.query(extensionQuery);\n }\n await this.writeConnection.query(\"SELECT powersync_update_hooks('install')\");\n }\n\n async close(): Promise<void> {\n await this.initializedPromise;\n await this.writeConnection.close();\n await this.readConnection.close();\n }\n\n protected generateLockContext(db: SQLiteDBConnection): LockContext {\n const _query = async (query: string, params: any[] = []) => {\n const result = await db.query(query, params);\n const arrayResult = result.values ?? [];\n return {\n rowsAffected: 0,\n rows: {\n _array: arrayResult,\n length: arrayResult.length,\n item: (idx: number) => arrayResult[idx]\n }\n };\n };\n\n const _execute = async (query: string, params: any[] = []): Promise<QueryResult> => {\n const platform = Capacitor.getPlatform();\n\n if (db.getConnectionReadOnly()) {\n return _query(query, params);\n }\n\n if (platform == 'android') {\n // Android: use query for SELECT and executeSet for mutations\n // We cannot use `run` here for both cases.\n if (query.toLowerCase().trim().startsWith('select')) {\n return _query(query, params);\n } else {\n const result = await db.executeSet([{ statement: query, values: params }], false);\n return {\n insertId: result.changes?.lastId,\n rowsAffected: result.changes?.changes ?? 0,\n rows: {\n _array: [],\n length: 0,\n item: () => null\n }\n };\n }\n }\n\n // iOS (and other platforms): use run(\"all\")\n const result = await db.run(query, params, false, 'all');\n const resultSet = result.changes?.values ?? [];\n return {\n insertId: result.changes?.lastId,\n rowsAffected: result.changes?.changes ?? 0,\n rows: {\n _array: resultSet,\n length: resultSet.length,\n item: (idx) => resultSet[idx]\n }\n };\n };\n\n const execute = this.options.debugMode\n ? (sql: string, params?: any[]) => monitorQuery(sql, () => _execute(sql, params))\n : _execute;\n\n const executeQuery = this.options.debugMode\n ? (sql: string, params?: any[]) => monitorQuery(sql, () => _query(sql, params))\n : _query;\n\n const getAll = async <T>(query: string, params?: any[]): Promise<T[]> => {\n const result = await executeQuery(query, params);\n return result.rows?._array ?? ([] as T[]);\n };\n\n const getOptional = async <T>(query: string, params?: any[]): Promise<T | null> => {\n const results = await getAll<T>(query, params);\n return results.length > 0 ? results[0] : null;\n };\n\n const get = async <T>(query: string, params?: any[]): Promise<T> => {\n const result = await getOptional<T>(query, params);\n if (!result) {\n throw new Error(`No results for query: ${query}`);\n }\n return result;\n };\n\n const executeRaw = async (query: string, params?: any[]): Promise<any[][]> => {\n // This is a workaround, we don't support multiple columns of the same name\n const results = await execute(query, params);\n return results.rows?._array.map((row) => Object.values(row)) ?? [];\n };\n\n return {\n getAll,\n getOptional,\n get,\n executeRaw,\n execute\n };\n }\n\n execute(query: string, params?: any[]): Promise<QueryResult> {\n return this.writeLock((tx) => tx.execute(query, params));\n }\n\n executeRaw(query: string, params?: any[]): Promise<any[][]> {\n return this.writeLock((tx) => tx.executeRaw(query, params));\n }\n\n async executeBatch(query: string, params: any[][] = []): Promise<QueryResult> {\n return this.writeLock(async (tx) => {\n let result = await this.writeConnection.executeSet(\n params.map((param) => ({\n statement: query,\n values: param\n }))\n );\n\n return {\n rowsAffected: result.changes?.changes ?? 0,\n insertId: result.changes?.lastId\n };\n });\n }\n\n readLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions): Promise<T> {\n return this.lock.acquire('read_lock', async () => {\n await this.initializedPromise;\n return await fn(this.generateLockContext(this.readConnection));\n });\n }\n\n readTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions): Promise<T> {\n return this.readLock(async (ctx) => {\n return this.internalTransaction(ctx, fn);\n });\n }\n\n writeLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions): Promise<T> {\n return this.lock.acquire('write_lock', async () => {\n await this.initializedPromise;\n const result = await fn(this.generateLockContext(this.writeConnection));\n\n // Fetch table updates\n const updates = await this.writeConnection.query(\"SELECT powersync_update_hooks('get') AS table_name\");\n const jsonUpdates = updates.values?.[0];\n if (!jsonUpdates || !jsonUpdates.table_name) {\n throw new Error('Could not fetch table updates');\n }\n const notification: BatchedUpdateNotification = {\n rawUpdates: [],\n tables: JSON.parse(jsonUpdates.table_name),\n groupedUpdates: {}\n };\n this.iterateListeners((l) => l.tablesUpdated?.(notification));\n return result;\n });\n }\n\n writeTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions): Promise<T> {\n return this.writeLock(async (ctx) => {\n return this.internalTransaction(ctx, fn);\n });\n }\n\n refreshSchema(): Promise<void> {\n return this.writeLock(async (writeTx) => {\n return this.readLock(async (readTx) => {\n const updateQuery = `PRAGMA table_info('sqlite_master')`;\n await writeTx.get(updateQuery);\n await readTx.get(updateQuery);\n });\n });\n }\n\n getAll<T>(sql: string, parameters?: any[]): Promise<T[]> {\n return this.readLock((tx) => tx.getAll<T>(sql, parameters));\n }\n\n getOptional<T>(sql: string, parameters?: any[]): Promise<T | null> {\n return this.readLock((tx) => tx.getOptional<T>(sql, parameters));\n }\n\n get<T>(sql: string, parameters?: any[]): Promise<T> {\n return this.readLock((tx) => tx.get<T>(sql, parameters));\n }\n\n protected async internalTransaction<T>(ctx: LockContext, fn: (tx: Transaction) => Promise<T>): Promise<T> {\n let finalized = false;\n const commit = async (): Promise<QueryResult> => {\n if (finalized) {\n return { rowsAffected: 0 };\n }\n finalized = true;\n return ctx.execute('COMMIT');\n };\n const rollback = async (): Promise<QueryResult> => {\n if (finalized) {\n return { rowsAffected: 0 };\n }\n finalized = true;\n return ctx.execute('ROLLBACK');\n };\n try {\n await ctx.execute('BEGIN');\n const result = await fn({\n ...ctx,\n commit,\n rollback\n });\n await commit();\n return result;\n } catch (ex) {\n try {\n await rollback();\n } catch (ex2) {\n // In rare cases, a rollback may fail.\n // Safe to ignore.\n }\n throw ex;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"CapacitorSQLiteAdapter.js","sourceRoot":"","sources":["../../../src/adapter/CapacitorSQLiteAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAsB,MAAM,6BAA6B,CAAC;AACpG,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EACL,YAAY,EAMZ,iBAAiB,EAGlB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAqC,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AAC5G;;GAEG;AACH,KAAK,UAAU,YAAY,CAAC,GAAW,EAAE,QAAoC;IAC3E,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IAChC,IA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iCAClB,GAAG,KACN,MAAM;gBACN,QAAQ,IACR,CAAC;YACH,MAAM,MAAM,EAAE,CAAC;YACf,OAAO,MAAM,CAAC;QAChB,CAAC;QAAC,OAAO,EAAE,EAAE,CAAC;YACZ,IAAI,CAAC;gBACH,MAAM,QAAQ,EAAE,CAAC;YACnB,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,sCAAsC;gBACtC,kBAAkB;YACpB,CAAC;YACD,MAAM,EAAE,CAAC;QACX,CAAC;IACH,CAAC;CACF","sourcesContent":["import { CapacitorSQLite, SQLiteConnection, SQLiteDBConnection } from '@capacitor-community/sqlite';\nimport { Capacitor } from '@capacitor/core';\n\nimport {\n BaseObserver,\n BatchedUpdateNotification,\n DBAdapter,\n DBAdapterListener,\n DBLockOptions,\n LockContext,\n mutexRunExclusive,\n QueryResult,\n Transaction\n} from '@powersync/web';\nimport { Mutex } from 'async-mutex';\nimport { PowerSyncCore } from '../plugin/PowerSyncCore.js';\nimport { messageForErrorCode } from '../plugin/PowerSyncPlugin.js';\nimport { CapacitorSQLiteOpenFactoryOptions, DEFAULT_SQLITE_OPTIONS } from './CapacitorSQLiteOpenFactory.js';\n/**\n * Monitors the execution time of a query and logs it to the performance timeline.\n */\nasync function monitorQuery(sql: string, executor: () => Promise<QueryResult>): Promise<QueryResult> {\n const start = performance.now();\n try {\n const r = await executor();\n performance.measure(`[SQL] ${sql}`, { start });\n return r;\n } catch (e: any) {\n performance.measure(`[SQL] [ERROR: ${e.message}] ${sql}`, { start });\n throw e;\n }\n}\n/**\n * An implementation of {@link DBAdapter} using the Capacitor Community SQLite [plugin](https://github.com/capacitor-community/sqlite).\n *\n * @experimental\n * @alpha This is currently experimental and may change without a major version bump.\n */\nexport class CapacitorSQLiteAdapter extends BaseObserver<DBAdapterListener> implements DBAdapter {\n protected _writeConnection: SQLiteDBConnection | null;\n protected _readConnection: SQLiteDBConnection | null;\n protected initializedPromise: Promise<void>;\n protected writeMutex: Mutex;\n protected readMutex: Mutex;\n\n constructor(protected options: CapacitorSQLiteOpenFactoryOptions) {\n super();\n this._writeConnection = null;\n this._readConnection = null;\n this.writeMutex = new Mutex();\n this.readMutex = new Mutex();\n this.initializedPromise = this.init();\n }\n\n protected get writeConnection(): SQLiteDBConnection {\n if (!this._writeConnection) {\n throw new Error('Init not completed yet');\n }\n return this._writeConnection;\n }\n\n protected get readConnection(): SQLiteDBConnection {\n if (!this._readConnection) {\n throw new Error('Init not completed yet');\n }\n return this._readConnection;\n }\n\n get name() {\n return this.options.dbFilename;\n }\n\n private async init() {\n const { responseCode: registrationResponseCode } = await PowerSyncCore.registerCore();\n if (registrationResponseCode != 0) {\n throw new Error(`Could not register PowerSync core extension: ${messageForErrorCode(registrationResponseCode)}`);\n }\n\n const sqlite = new SQLiteConnection(CapacitorSQLite);\n\n // It seems like the isConnection and retrieveConnection methods\n // only check a JS side map of connections.\n // On hot reload this JS cache can be cleared, while the connection\n // still exists natively. and `createConnection` will fail if it already exists.\n await sqlite.closeConnection(this.options.dbFilename, false).catch(() => {});\n await sqlite.closeConnection(this.options.dbFilename, true).catch(() => {});\n\n // TODO support encryption eventually\n this._writeConnection = await sqlite.createConnection(this.options.dbFilename, false, 'no-encryption', 1, false);\n this._readConnection = await sqlite.createConnection(this.options.dbFilename, false, 'no-encryption', 1, true);\n\n await this._writeConnection.open();\n\n const { cacheSizeKb, journalSizeLimit, synchronous } = { ...DEFAULT_SQLITE_OPTIONS, ...this.options.sqliteOptions };\n\n await this.writeConnection.query('PRAGMA journal_mode = WAL');\n await this.writeConnection.query(`PRAGMA journal_size_limit = ${journalSizeLimit}`);\n await this.writeConnection.query(`PRAGMA temp_store = memory`);\n await this.writeConnection.query(`PRAGMA synchronous = ${synchronous}`);\n await this.writeConnection.query(`PRAGMA cache_size = -${cacheSizeKb}`);\n\n await this._readConnection.open();\n\n const platform = Capacitor.getPlatform();\n if (platform == 'android') {\n /**\n * SQLCipher for Android enables dynamic loading of extensions.\n * On iOS we use a static auto extension registration.\n */\n const extensionQuery = \"SELECT load_extension('libpowersync.so', 'sqlite3_powersync_init')\";\n await this.writeConnection.query(extensionQuery);\n await this.readConnection.query(extensionQuery);\n }\n await this.writeConnection.query(\"SELECT powersync_update_hooks('install')\");\n }\n\n async close(): Promise<void> {\n await this.initializedPromise;\n await this.writeConnection.close();\n await this.readConnection.close();\n }\n\n protected generateLockContext(db: SQLiteDBConnection): LockContext {\n const _query = async (query: string, params: any[] = []) => {\n const result = await db.query(query, params);\n const arrayResult = result.values ?? [];\n return {\n rowsAffected: 0,\n rows: {\n _array: arrayResult,\n length: arrayResult.length,\n item: (idx: number) => arrayResult[idx]\n }\n };\n };\n\n const _execute = async (query: string, params: any[] = []): Promise<QueryResult> => {\n const platform = Capacitor.getPlatform();\n\n if (db.getConnectionReadOnly()) {\n return _query(query, params);\n }\n\n if (platform == 'android') {\n // Android: use query for SELECT and executeSet for mutations\n // We cannot use `run` here for both cases.\n if (query.toLowerCase().trim().startsWith('select')) {\n return _query(query, params);\n } else {\n const result = await db.executeSet([{ statement: query, values: params }], false);\n return {\n insertId: result.changes?.lastId,\n rowsAffected: result.changes?.changes ?? 0,\n rows: {\n _array: [],\n length: 0,\n item: () => null\n }\n };\n }\n }\n\n // iOS (and other platforms): use run(\"all\")\n const result = await db.run(query, params, false, 'all');\n const resultSet = result.changes?.values ?? [];\n return {\n insertId: result.changes?.lastId,\n rowsAffected: result.changes?.changes ?? 0,\n rows: {\n _array: resultSet,\n length: resultSet.length,\n item: (idx) => resultSet[idx]\n }\n };\n };\n\n const execute = this.options.debugMode\n ? (sql: string, params?: any[]) => monitorQuery(sql, () => _execute(sql, params))\n : _execute;\n\n const executeQuery = this.options.debugMode\n ? (sql: string, params?: any[]) => monitorQuery(sql, () => _query(sql, params))\n : _query;\n\n const getAll = async <T>(query: string, params?: any[]): Promise<T[]> => {\n const result = await executeQuery(query, params);\n return result.rows?._array ?? ([] as T[]);\n };\n\n const getOptional = async <T>(query: string, params?: any[]): Promise<T | null> => {\n const results = await getAll<T>(query, params);\n return results.length > 0 ? results[0] : null;\n };\n\n const get = async <T>(query: string, params?: any[]): Promise<T> => {\n const result = await getOptional<T>(query, params);\n if (!result) {\n throw new Error(`No results for query: ${query}`);\n }\n return result;\n };\n\n const executeRaw = async (query: string, params?: any[]): Promise<any[][]> => {\n // This is a workaround, we don't support multiple columns of the same name\n const results = await execute(query, params);\n return results.rows?._array.map((row) => Object.values(row)) ?? [];\n };\n\n return {\n getAll,\n getOptional,\n get,\n executeRaw,\n execute\n };\n }\n\n execute(query: string, params?: any[]): Promise<QueryResult> {\n return this.writeLock((tx) => tx.execute(query, params));\n }\n\n executeRaw(query: string, params?: any[]): Promise<any[][]> {\n return this.writeLock((tx) => tx.executeRaw(query, params));\n }\n\n async executeBatch(query: string, params: any[][] = []): Promise<QueryResult> {\n return this.writeLock(async (tx) => {\n let result = await this.writeConnection.executeSet(\n params.map((param) => ({\n statement: query,\n values: param\n }))\n );\n\n return {\n rowsAffected: result.changes?.changes ?? 0,\n insertId: result.changes?.lastId\n };\n });\n }\n\n readLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions): Promise<T> {\n return mutexRunExclusive(\n this.readMutex,\n async () => {\n await this.initializedPromise;\n return await fn(this.generateLockContext(this.readConnection));\n },\n options\n );\n }\n\n readTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions): Promise<T> {\n return this.readLock(async (ctx) => {\n return this.internalTransaction(ctx, fn);\n });\n }\n\n writeLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions): Promise<T> {\n return mutexRunExclusive(\n this.writeMutex,\n async () => {\n await this.initializedPromise;\n const result = await fn(this.generateLockContext(this.writeConnection));\n\n // Fetch table updates\n const updates = await this.writeConnection.query(\"SELECT powersync_update_hooks('get') AS table_name\");\n const jsonUpdates = updates.values?.[0];\n if (!jsonUpdates || !jsonUpdates.table_name) {\n throw new Error('Could not fetch table updates');\n }\n const notification: BatchedUpdateNotification = {\n rawUpdates: [],\n tables: JSON.parse(jsonUpdates.table_name),\n groupedUpdates: {}\n };\n this.iterateListeners((l) => l.tablesUpdated?.(notification));\n return result;\n },\n options\n );\n }\n\n writeTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions): Promise<T> {\n return this.writeLock(async (ctx) => {\n return this.internalTransaction(ctx, fn);\n });\n }\n\n refreshSchema(): Promise<void> {\n return this.writeLock(async (writeTx) => {\n return this.readLock(async (readTx) => {\n const updateQuery = `PRAGMA table_info('sqlite_master')`;\n await writeTx.get(updateQuery);\n await readTx.get(updateQuery);\n });\n });\n }\n\n getAll<T>(sql: string, parameters?: any[]): Promise<T[]> {\n return this.readLock((tx) => tx.getAll<T>(sql, parameters));\n }\n\n getOptional<T>(sql: string, parameters?: any[]): Promise<T | null> {\n return this.readLock((tx) => tx.getOptional<T>(sql, parameters));\n }\n\n get<T>(sql: string, parameters?: any[]): Promise<T> {\n return this.readLock((tx) => tx.get<T>(sql, parameters));\n }\n\n protected async internalTransaction<T>(ctx: LockContext, fn: (tx: Transaction) => Promise<T>): Promise<T> {\n let finalized = false;\n const commit = async (): Promise<QueryResult> => {\n if (finalized) {\n return { rowsAffected: 0 };\n }\n finalized = true;\n return ctx.execute('COMMIT');\n };\n const rollback = async (): Promise<QueryResult> => {\n if (finalized) {\n return { rowsAffected: 0 };\n }\n finalized = true;\n return ctx.execute('ROLLBACK');\n };\n try {\n await ctx.execute('BEGIN');\n const result = await fn({\n ...ctx,\n commit,\n rollback\n });\n await commit();\n return result;\n } catch (ex) {\n try {\n await rollback();\n } catch (ex2) {\n // In rare cases, a rollback may fail.\n // Safe to ignore.\n }\n throw ex;\n }\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { AbstractStreamingSyncImplementation, LockOptions } from '@powersync/web';
2
- import Lock from 'async-lock';
3
2
  export declare class CapacitorStreamingSyncImplementation extends AbstractStreamingSyncImplementation {
4
- static GLOBAL_LOCK: Lock;
3
+ protected instanceId: number;
4
+ dispose(): Promise<void>;
5
5
  obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
6
6
  }
@@ -1,9 +1,46 @@
1
- import { AbstractStreamingSyncImplementation } from '@powersync/web';
2
- import Lock from 'async-lock';
1
+ import { AbstractStreamingSyncImplementation, LockType, mutexRunExclusive } from '@powersync/web';
2
+ import { Mutex } from 'async-mutex';
3
+ const GLOBAL_MUTEX_STORE = new Map();
4
+ /**
5
+ * Used to identify multiple instances of CapacitorStreamingSyncImplementation
6
+ */
7
+ let _CAPACITOR_STREAMING_SYNC_SEQUENCE = 0;
3
8
  export class CapacitorStreamingSyncImplementation extends AbstractStreamingSyncImplementation {
9
+ constructor() {
10
+ super(...arguments);
11
+ // A unique ID for tacking this specific instance of CapacitorStreamingSyncImplementation
12
+ this.instanceId = _CAPACITOR_STREAMING_SYNC_SEQUENCE++;
13
+ }
14
+ async dispose() {
15
+ await super.dispose();
16
+ // Clear up any global mutexes which aren't used anymore
17
+ for (const mutexEntry of GLOBAL_MUTEX_STORE.entries()) {
18
+ const [identifier, mutex] = mutexEntry;
19
+ if (!mutex.tracking.has(this.instanceId)) {
20
+ continue;
21
+ }
22
+ mutex.tracking.delete(this.instanceId);
23
+ if (mutex.tracking.size == 0) {
24
+ GLOBAL_MUTEX_STORE.delete(identifier);
25
+ }
26
+ }
27
+ }
4
28
  async obtainLock(lockOptions) {
5
- const identifier = `streaming-sync-${lockOptions.type}-${this.options.identifier}`;
6
- return CapacitorStreamingSyncImplementation.GLOBAL_LOCK.acquire(identifier, async () => {
29
+ // If we don't have an identifier for some reason (should not happen), we use a shared Mutex
30
+ const { identifier: baseIdentifier = 'DEFAULT' } = this.options;
31
+ if (!GLOBAL_MUTEX_STORE.has(baseIdentifier)) {
32
+ GLOBAL_MUTEX_STORE.set(baseIdentifier, {
33
+ tracking: new Set([this.instanceId]),
34
+ locks: {
35
+ [LockType.CRUD]: new Mutex(),
36
+ [LockType.SYNC]: new Mutex()
37
+ }
38
+ });
39
+ }
40
+ const mutexRecord = GLOBAL_MUTEX_STORE.get(baseIdentifier);
41
+ mutexRecord.tracking.add(this.instanceId);
42
+ const mutex = mutexRecord.locks[lockOptions.type];
43
+ return mutexRunExclusive(mutex, async () => {
7
44
  var _a;
8
45
  if ((_a = lockOptions.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
9
46
  throw new Error('Aborted');
@@ -12,5 +49,4 @@ export class CapacitorStreamingSyncImplementation extends AbstractStreamingSyncI
12
49
  });
13
50
  }
14
51
  }
15
- CapacitorStreamingSyncImplementation.GLOBAL_LOCK = new Lock();
16
52
  //# sourceMappingURL=CapacitorSyncImplementation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"CapacitorSyncImplementation.js","sourceRoot":"","sources":["../../../src/sync/CapacitorSyncImplementation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAe,MAAM,gBAAgB,CAAC;AAClF,OAAO,IAAI,MAAM,YAAY,CAAC;AAE9B,MAAM,OAAO,oCAAqC,SAAQ,mCAAmC;IAG3F,KAAK,CAAC,UAAU,CAAI,WAA2B;QAC7C,MAAM,UAAU,GAAG,kBAAkB,WAAW,CAAC,IAAI,IAAI,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;QACnF,OAAO,oCAAoC,CAAC,WAAW,CAAC,OAAO,CAAC,UAAU,EAAE,KAAK,IAAI,EAAE;;YACrF,IAAI,MAAA,WAAW,CAAC,MAAM,0CAAE,OAAO,EAAE,CAAC;gBAChC,MAAM,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;YAC7B,CAAC;YACD,OAAO,MAAM,WAAW,CAAC,QAAQ,EAAE,CAAC;QACtC,CAAC,CAAC,CAAC;IACL,CAAC;;AAVM,gDAAW,GAAG,IAAI,IAAI,EAAE,CAAC","sourcesContent":["import { AbstractStreamingSyncImplementation, LockOptions } from '@powersync/web';\nimport Lock from 'async-lock';\n\nexport class CapacitorStreamingSyncImplementation extends AbstractStreamingSyncImplementation {\n static GLOBAL_LOCK = new Lock();\n\n async obtainLock<T>(lockOptions: LockOptions<T>): Promise<T> {\n const identifier = `streaming-sync-${lockOptions.type}-${this.options.identifier}`;\n return CapacitorStreamingSyncImplementation.GLOBAL_LOCK.acquire(identifier, async () => {\n if (lockOptions.signal?.aborted) {\n throw new Error('Aborted');\n }\n return await lockOptions.callback();\n });\n }\n}\n"]}
1
+ {"version":3,"file":"CapacitorSyncImplementation.js","sourceRoot":"","sources":["../../../src/sync/CapacitorSyncImplementation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAe,QAAQ,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAC/G,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAapC,MAAM,kBAAkB,GAA0B,IAAI,GAAG,EAAE,CAAC;AAE5D;;GAEG;AACH,IAAI,kCAAkC,GAAG,CAAC,CAAC;AAE3C,MAAM,OAAO,oCAAqC,SAAQ,mCAAmC;IAA7F;;QACE,yFAAyF;QAC/E,eAAU,GAAG,kCAAkC,EAAE,CAAC;IA0C9D,CAAC;IAxCC,KAAK,CAAC,OAAO;QACX,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;QAEtB,wDAAwD;QACxD,KAAK,MAAM,UAAU,IAAI,kBAAkB,CAAC,OAAO,EAAE,EAAE,CAAC;YACtD,MAAM,CAAC,UAAU,EAAE,KAAK,CAAC,GAAG,UAAU,CAAC;YACvC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;gBACzC,SAAS;YACX,CAAC;YACD,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YACvC,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,EAAE,CAAC;gBAC7B,kBAAkB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;YACxC,CAAC;QACH,CAAC;IACH,CAAC;IAED,KAAK,CAAC,UAAU,CAAI,WAA2B;QAC7C,4FAA4F;QAC5F,MAAM,EAAE,UAAU,EAAE,cAAc,GAAG,SAAS,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC;QAChE,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE,CAAC;YAC5C,kBAAkB,CAAC,GAAG,CAAC,cAAc,EAAE;gBACrC,QAAQ,EAAE,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;gBACpC,KAAK,EAAE;oBACL,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,KAAK,EAAE;oBAC5B,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,KAAK,EAAE;iBAC7B;aACF,CAAC,CAAC;QACL,CAAC;QAED,MAAM,WAAW,GAAG,kBAAkB,CAAC,GAAG,CAAC,cAAc,CAAE,CAAC;QAC5D,WAAW,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC1C,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QAElD,OAAO,iBAAiB,CAAC,KAAK,EAAE,KAAK,IAAI,EAAE;;YACzC,IAAI,MAAA,WAAW,CAAC,MAAM,0CAAE,OAAO,EAAE,CAAC;gBAChC,MAAM,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;YAC7B,CAAC;YACD,OAAO,MAAM,WAAW,CAAC,QAAQ,EAAE,CAAC;QACtC,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { AbstractStreamingSyncImplementation, LockOptions, LockType, mutexRunExclusive } from '@powersync/web';\nimport { Mutex } from 'async-mutex';\n\ntype MutexMap = {\n /**\n * Used to track the consumers of this Mutex.\n * It should be safe to dispose the Mutex if this is empty.\n */\n tracking: Set<number>;\n locks: {\n [Type in LockType]: Mutex;\n };\n};\n\nconst GLOBAL_MUTEX_STORE: Map<string, MutexMap> = new Map();\n\n/**\n * Used to identify multiple instances of CapacitorStreamingSyncImplementation\n */\nlet _CAPACITOR_STREAMING_SYNC_SEQUENCE = 0;\n\nexport class CapacitorStreamingSyncImplementation extends AbstractStreamingSyncImplementation {\n // A unique ID for tacking this specific instance of CapacitorStreamingSyncImplementation\n protected instanceId = _CAPACITOR_STREAMING_SYNC_SEQUENCE++;\n\n async dispose(): Promise<void> {\n await super.dispose();\n\n // Clear up any global mutexes which aren't used anymore\n for (const mutexEntry of GLOBAL_MUTEX_STORE.entries()) {\n const [identifier, mutex] = mutexEntry;\n if (!mutex.tracking.has(this.instanceId)) {\n continue;\n }\n mutex.tracking.delete(this.instanceId);\n if (mutex.tracking.size == 0) {\n GLOBAL_MUTEX_STORE.delete(identifier);\n }\n }\n }\n\n async obtainLock<T>(lockOptions: LockOptions<T>): Promise<T> {\n // If we don't have an identifier for some reason (should not happen), we use a shared Mutex\n const { identifier: baseIdentifier = 'DEFAULT' } = this.options;\n if (!GLOBAL_MUTEX_STORE.has(baseIdentifier)) {\n GLOBAL_MUTEX_STORE.set(baseIdentifier, {\n tracking: new Set([this.instanceId]),\n locks: {\n [LockType.CRUD]: new Mutex(),\n [LockType.SYNC]: new Mutex()\n }\n });\n }\n\n const mutexRecord = GLOBAL_MUTEX_STORE.get(baseIdentifier)!;\n mutexRecord.tracking.add(this.instanceId);\n const mutex = mutexRecord.locks[lockOptions.type];\n\n return mutexRunExclusive(mutex, async () => {\n if (lockOptions.signal?.aborted) {\n throw new Error('Aborted');\n }\n return await lockOptions.callback();\n });\n }\n}\n"]}
package/dist/plugin.cjs CHANGED
@@ -3,7 +3,7 @@
3
3
  var sqlite = require('@capacitor-community/sqlite');
4
4
  var core = require('@capacitor/core');
5
5
  var web$1 = require('@powersync/web');
6
- var Lock = require('async-lock');
6
+ var asyncMutex = require('async-mutex');
7
7
 
8
8
  const PowerSyncCore = core.registerPlugin('PowerSync', {
9
9
  web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.PowerSyncWeb())
@@ -65,7 +65,8 @@ class CapacitorSQLiteAdapter extends web$1.BaseObserver {
65
65
  this.options = options;
66
66
  this._writeConnection = null;
67
67
  this._readConnection = null;
68
- this.lock = new Lock();
68
+ this.writeMutex = new asyncMutex.Mutex();
69
+ this.readMutex = new asyncMutex.Mutex();
69
70
  this.initializedPromise = this.init();
70
71
  }
71
72
  get writeConnection() {
@@ -231,10 +232,10 @@ class CapacitorSQLiteAdapter extends web$1.BaseObserver {
231
232
  });
232
233
  }
233
234
  readLock(fn, options) {
234
- return this.lock.acquire('read_lock', async () => {
235
+ return web$1.mutexRunExclusive(this.readMutex, async () => {
235
236
  await this.initializedPromise;
236
237
  return await fn(this.generateLockContext(this.readConnection));
237
- });
238
+ }, options);
238
239
  }
239
240
  readTransaction(fn, options) {
240
241
  return this.readLock(async (ctx) => {
@@ -242,7 +243,7 @@ class CapacitorSQLiteAdapter extends web$1.BaseObserver {
242
243
  });
243
244
  }
244
245
  writeLock(fn, options) {
245
- return this.lock.acquire('write_lock', async () => {
246
+ return web$1.mutexRunExclusive(this.writeMutex, async () => {
246
247
  var _a;
247
248
  await this.initializedPromise;
248
249
  const result = await fn(this.generateLockContext(this.writeConnection));
@@ -259,7 +260,7 @@ class CapacitorSQLiteAdapter extends web$1.BaseObserver {
259
260
  };
260
261
  this.iterateListeners((l) => { var _a; return (_a = l.tablesUpdated) === null || _a === void 0 ? void 0 : _a.call(l, notification); });
261
262
  return result;
262
- });
263
+ }, options);
263
264
  }
264
265
  writeTransaction(fn, options) {
265
266
  return this.writeLock(async (ctx) => {
@@ -320,10 +321,47 @@ class CapacitorSQLiteAdapter extends web$1.BaseObserver {
320
321
  }
321
322
  }
322
323
 
324
+ const GLOBAL_MUTEX_STORE = new Map();
325
+ /**
326
+ * Used to identify multiple instances of CapacitorStreamingSyncImplementation
327
+ */
328
+ let _CAPACITOR_STREAMING_SYNC_SEQUENCE = 0;
323
329
  class CapacitorStreamingSyncImplementation extends web$1.AbstractStreamingSyncImplementation {
330
+ constructor() {
331
+ super(...arguments);
332
+ // A unique ID for tacking this specific instance of CapacitorStreamingSyncImplementation
333
+ this.instanceId = _CAPACITOR_STREAMING_SYNC_SEQUENCE++;
334
+ }
335
+ async dispose() {
336
+ await super.dispose();
337
+ // Clear up any global mutexes which aren't used anymore
338
+ for (const mutexEntry of GLOBAL_MUTEX_STORE.entries()) {
339
+ const [identifier, mutex] = mutexEntry;
340
+ if (!mutex.tracking.has(this.instanceId)) {
341
+ continue;
342
+ }
343
+ mutex.tracking.delete(this.instanceId);
344
+ if (mutex.tracking.size == 0) {
345
+ GLOBAL_MUTEX_STORE.delete(identifier);
346
+ }
347
+ }
348
+ }
324
349
  async obtainLock(lockOptions) {
325
- const identifier = `streaming-sync-${lockOptions.type}-${this.options.identifier}`;
326
- return CapacitorStreamingSyncImplementation.GLOBAL_LOCK.acquire(identifier, async () => {
350
+ // If we don't have an identifier for some reason (should not happen), we use a shared Mutex
351
+ const { identifier: baseIdentifier = 'DEFAULT' } = this.options;
352
+ if (!GLOBAL_MUTEX_STORE.has(baseIdentifier)) {
353
+ GLOBAL_MUTEX_STORE.set(baseIdentifier, {
354
+ tracking: new Set([this.instanceId]),
355
+ locks: {
356
+ [web$1.LockType.CRUD]: new asyncMutex.Mutex(),
357
+ [web$1.LockType.SYNC]: new asyncMutex.Mutex()
358
+ }
359
+ });
360
+ }
361
+ const mutexRecord = GLOBAL_MUTEX_STORE.get(baseIdentifier);
362
+ mutexRecord.tracking.add(this.instanceId);
363
+ const mutex = mutexRecord.locks[lockOptions.type];
364
+ return web$1.mutexRunExclusive(mutex, async () => {
327
365
  var _a;
328
366
  if ((_a = lockOptions.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
329
367
  throw new Error('Aborted');
@@ -332,7 +370,6 @@ class CapacitorStreamingSyncImplementation extends web$1.AbstractStreamingSyncIm
332
370
  });
333
371
  }
334
372
  }
335
- CapacitorStreamingSyncImplementation.GLOBAL_LOCK = new Lock();
336
373
 
337
374
  /**
338
375
  * PowerSyncDatabase class for managing database connections and sync implementations.
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.cjs","sources":["esm/plugin/PowerSyncCore.js","esm/plugin/PowerSyncPlugin.js","esm/adapter/CapacitorSQLiteOpenFactory.js","esm/adapter/CapacitorSQLiteAdapter.js","esm/sync/CapacitorSyncImplementation.js","esm/PowerSyncDatabase.js","esm/plugin/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nexport const PowerSyncCore = registerPlugin('PowerSync', {\n web: () => import('./web.js').then((m) => new m.PowerSyncWeb())\n});\n//# sourceMappingURL=PowerSyncCore.js.map","export const messageForErrorCode = (code) => {\n switch (code) {\n case 0:\n return 'Success';\n default:\n return `Extension registration failed with SQLite error code: ${code}`;\n }\n};\n//# sourceMappingURL=PowerSyncPlugin.js.map","import { CapacitorSQLiteAdapter } from './CapacitorSQLiteAdapter.js';\nvar SqliteSynchronous;\n(function (SqliteSynchronous) {\n SqliteSynchronous[\"normal\"] = \"NORMAL\";\n SqliteSynchronous[\"full\"] = \"FULL\";\n SqliteSynchronous[\"off\"] = \"OFF\";\n})(SqliteSynchronous || (SqliteSynchronous = {}));\nexport const DEFAULT_SQLITE_OPTIONS = {\n journalSizeLimit: 6 * 1024 * 1024,\n synchronous: SqliteSynchronous.normal,\n cacheSizeKb: 50 * 1024\n};\nexport class CapacitorSQLiteOpenFactory {\n constructor(options) {\n this.options = options;\n }\n openDB() {\n return new CapacitorSQLiteAdapter(this.options);\n }\n}\n//# sourceMappingURL=CapacitorSQLiteOpenFactory.js.map","import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';\nimport { Capacitor } from '@capacitor/core';\nimport { BaseObserver } from '@powersync/web';\nimport Lock from 'async-lock';\nimport { PowerSyncCore } from '../plugin/PowerSyncCore.js';\nimport { messageForErrorCode } from '../plugin/PowerSyncPlugin.js';\nimport { DEFAULT_SQLITE_OPTIONS } from './CapacitorSQLiteOpenFactory.js';\n/**\n * Monitors the execution time of a query and logs it to the performance timeline.\n */\nasync function monitorQuery(sql, executor) {\n const start = performance.now();\n try {\n const r = await executor();\n performance.measure(`[SQL] ${sql}`, { start });\n return r;\n }\n catch (e) {\n performance.measure(`[SQL] [ERROR: ${e.message}] ${sql}`, { start });\n throw e;\n }\n}\n/**\n * An implementation of {@link DBAdapter} using the Capacitor Community SQLite [plugin](https://github.com/capacitor-community/sqlite).\n *\n * @experimental\n * @alpha This is currently experimental and may change without a major version bump.\n */\nexport class CapacitorSQLiteAdapter extends BaseObserver {\n constructor(options) {\n super();\n this.options = options;\n this._writeConnection = null;\n this._readConnection = null;\n this.lock = new Lock();\n this.initializedPromise = this.init();\n }\n get writeConnection() {\n if (!this._writeConnection) {\n throw new Error('Init not completed yet');\n }\n return this._writeConnection;\n }\n get readConnection() {\n if (!this._readConnection) {\n throw new Error('Init not completed yet');\n }\n return this._readConnection;\n }\n get name() {\n return this.options.dbFilename;\n }\n async init() {\n const { responseCode: registrationResponseCode } = await PowerSyncCore.registerCore();\n if (registrationResponseCode != 0) {\n throw new Error(`Could not register PowerSync core extension: ${messageForErrorCode(registrationResponseCode)}`);\n }\n const sqlite = new SQLiteConnection(CapacitorSQLite);\n // It seems like the isConnection and retrieveConnection methods\n // only check a JS side map of connections.\n // On hot reload this JS cache can be cleared, while the connection\n // still exists natively. and `createConnection` will fail if it already exists.\n await sqlite.closeConnection(this.options.dbFilename, false).catch(() => { });\n await sqlite.closeConnection(this.options.dbFilename, true).catch(() => { });\n // TODO support encryption eventually\n this._writeConnection = await sqlite.createConnection(this.options.dbFilename, false, 'no-encryption', 1, false);\n this._readConnection = await sqlite.createConnection(this.options.dbFilename, false, 'no-encryption', 1, true);\n await this._writeConnection.open();\n const { cacheSizeKb, journalSizeLimit, synchronous } = Object.assign(Object.assign({}, DEFAULT_SQLITE_OPTIONS), this.options.sqliteOptions);\n await this.writeConnection.query('PRAGMA journal_mode = WAL');\n await this.writeConnection.query(`PRAGMA journal_size_limit = ${journalSizeLimit}`);\n await this.writeConnection.query(`PRAGMA temp_store = memory`);\n await this.writeConnection.query(`PRAGMA synchronous = ${synchronous}`);\n await this.writeConnection.query(`PRAGMA cache_size = -${cacheSizeKb}`);\n await this._readConnection.open();\n const platform = Capacitor.getPlatform();\n if (platform == 'android') {\n /**\n * SQLCipher for Android enables dynamic loading of extensions.\n * On iOS we use a static auto extension registration.\n */\n const extensionQuery = \"SELECT load_extension('libpowersync.so', 'sqlite3_powersync_init')\";\n await this.writeConnection.query(extensionQuery);\n await this.readConnection.query(extensionQuery);\n }\n await this.writeConnection.query(\"SELECT powersync_update_hooks('install')\");\n }\n async close() {\n await this.initializedPromise;\n await this.writeConnection.close();\n await this.readConnection.close();\n }\n generateLockContext(db) {\n const _query = async (query, params = []) => {\n var _a;\n const result = await db.query(query, params);\n const arrayResult = (_a = result.values) !== null && _a !== void 0 ? _a : [];\n return {\n rowsAffected: 0,\n rows: {\n _array: arrayResult,\n length: arrayResult.length,\n item: (idx) => arrayResult[idx]\n }\n };\n };\n const _execute = async (query, params = []) => {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n const platform = Capacitor.getPlatform();\n if (db.getConnectionReadOnly()) {\n return _query(query, params);\n }\n if (platform == 'android') {\n // Android: use query for SELECT and executeSet for mutations\n // We cannot use `run` here for both cases.\n if (query.toLowerCase().trim().startsWith('select')) {\n return _query(query, params);\n }\n else {\n const result = await db.executeSet([{ statement: query, values: params }], false);\n return {\n insertId: (_a = result.changes) === null || _a === void 0 ? void 0 : _a.lastId,\n rowsAffected: (_c = (_b = result.changes) === null || _b === void 0 ? void 0 : _b.changes) !== null && _c !== void 0 ? _c : 0,\n rows: {\n _array: [],\n length: 0,\n item: () => null\n }\n };\n }\n }\n // iOS (and other platforms): use run(\"all\")\n const result = await db.run(query, params, false, 'all');\n const resultSet = (_e = (_d = result.changes) === null || _d === void 0 ? void 0 : _d.values) !== null && _e !== void 0 ? _e : [];\n return {\n insertId: (_f = result.changes) === null || _f === void 0 ? void 0 : _f.lastId,\n rowsAffected: (_h = (_g = result.changes) === null || _g === void 0 ? void 0 : _g.changes) !== null && _h !== void 0 ? _h : 0,\n rows: {\n _array: resultSet,\n length: resultSet.length,\n item: (idx) => resultSet[idx]\n }\n };\n };\n const execute = this.options.debugMode\n ? (sql, params) => monitorQuery(sql, () => _execute(sql, params))\n : _execute;\n const executeQuery = this.options.debugMode\n ? (sql, params) => monitorQuery(sql, () => _query(sql, params))\n : _query;\n const getAll = async (query, params) => {\n var _a, _b;\n const result = await executeQuery(query, params);\n return (_b = (_a = result.rows) === null || _a === void 0 ? void 0 : _a._array) !== null && _b !== void 0 ? _b : [];\n };\n const getOptional = async (query, params) => {\n const results = await getAll(query, params);\n return results.length > 0 ? results[0] : null;\n };\n const get = async (query, params) => {\n const result = await getOptional(query, params);\n if (!result) {\n throw new Error(`No results for query: ${query}`);\n }\n return result;\n };\n const executeRaw = async (query, params) => {\n var _a, _b;\n // This is a workaround, we don't support multiple columns of the same name\n const results = await execute(query, params);\n return (_b = (_a = results.rows) === null || _a === void 0 ? void 0 : _a._array.map((row) => Object.values(row))) !== null && _b !== void 0 ? _b : [];\n };\n return {\n getAll,\n getOptional,\n get,\n executeRaw,\n execute\n };\n }\n execute(query, params) {\n return this.writeLock((tx) => tx.execute(query, params));\n }\n executeRaw(query, params) {\n return this.writeLock((tx) => tx.executeRaw(query, params));\n }\n async executeBatch(query, params = []) {\n return this.writeLock(async (tx) => {\n var _a, _b, _c;\n let result = await this.writeConnection.executeSet(params.map((param) => ({\n statement: query,\n values: param\n })));\n return {\n rowsAffected: (_b = (_a = result.changes) === null || _a === void 0 ? void 0 : _a.changes) !== null && _b !== void 0 ? _b : 0,\n insertId: (_c = result.changes) === null || _c === void 0 ? void 0 : _c.lastId\n };\n });\n }\n readLock(fn, options) {\n return this.lock.acquire('read_lock', async () => {\n await this.initializedPromise;\n return await fn(this.generateLockContext(this.readConnection));\n });\n }\n readTransaction(fn, options) {\n return this.readLock(async (ctx) => {\n return this.internalTransaction(ctx, fn);\n });\n }\n writeLock(fn, options) {\n return this.lock.acquire('write_lock', async () => {\n var _a;\n await this.initializedPromise;\n const result = await fn(this.generateLockContext(this.writeConnection));\n // Fetch table updates\n const updates = await this.writeConnection.query(\"SELECT powersync_update_hooks('get') AS table_name\");\n const jsonUpdates = (_a = updates.values) === null || _a === void 0 ? void 0 : _a[0];\n if (!jsonUpdates || !jsonUpdates.table_name) {\n throw new Error('Could not fetch table updates');\n }\n const notification = {\n rawUpdates: [],\n tables: JSON.parse(jsonUpdates.table_name),\n groupedUpdates: {}\n };\n this.iterateListeners((l) => { var _a; return (_a = l.tablesUpdated) === null || _a === void 0 ? void 0 : _a.call(l, notification); });\n return result;\n });\n }\n writeTransaction(fn, options) {\n return this.writeLock(async (ctx) => {\n return this.internalTransaction(ctx, fn);\n });\n }\n refreshSchema() {\n return this.writeLock(async (writeTx) => {\n return this.readLock(async (readTx) => {\n const updateQuery = `PRAGMA table_info('sqlite_master')`;\n await writeTx.get(updateQuery);\n await readTx.get(updateQuery);\n });\n });\n }\n getAll(sql, parameters) {\n return this.readLock((tx) => tx.getAll(sql, parameters));\n }\n getOptional(sql, parameters) {\n return this.readLock((tx) => tx.getOptional(sql, parameters));\n }\n get(sql, parameters) {\n return this.readLock((tx) => tx.get(sql, parameters));\n }\n async internalTransaction(ctx, fn) {\n let finalized = false;\n const commit = async () => {\n if (finalized) {\n return { rowsAffected: 0 };\n }\n finalized = true;\n return ctx.execute('COMMIT');\n };\n const rollback = async () => {\n if (finalized) {\n return { rowsAffected: 0 };\n }\n finalized = true;\n return ctx.execute('ROLLBACK');\n };\n try {\n await ctx.execute('BEGIN');\n const result = await fn(Object.assign(Object.assign({}, ctx), { commit,\n rollback }));\n await commit();\n return result;\n }\n catch (ex) {\n try {\n await rollback();\n }\n catch (ex2) {\n // In rare cases, a rollback may fail.\n // Safe to ignore.\n }\n throw ex;\n }\n }\n}\n//# sourceMappingURL=CapacitorSQLiteAdapter.js.map","import { AbstractStreamingSyncImplementation } from '@powersync/web';\nimport Lock from 'async-lock';\nexport class CapacitorStreamingSyncImplementation extends AbstractStreamingSyncImplementation {\n async obtainLock(lockOptions) {\n const identifier = `streaming-sync-${lockOptions.type}-${this.options.identifier}`;\n return CapacitorStreamingSyncImplementation.GLOBAL_LOCK.acquire(identifier, async () => {\n var _a;\n if ((_a = lockOptions.signal) === null || _a === void 0 ? void 0 : _a.aborted) {\n throw new Error('Aborted');\n }\n return await lockOptions.callback();\n });\n }\n}\nCapacitorStreamingSyncImplementation.GLOBAL_LOCK = new Lock();\n//# sourceMappingURL=CapacitorSyncImplementation.js.map","import { Capacitor } from '@capacitor/core';\nimport { MEMORY_TRIGGER_CLAIM_MANAGER, PowerSyncDatabase as WebPowerSyncDatabase, WebRemote } from '@powersync/web';\nimport { CapacitorSQLiteAdapter } from './adapter/CapacitorSQLiteAdapter.js';\nimport { CapacitorStreamingSyncImplementation } from './sync/CapacitorSyncImplementation.js';\n/**\n * PowerSyncDatabase class for managing database connections and sync implementations.\n * This extends the WebPowerSyncDatabase to provide platform-specific implementations\n * for Capacitor environments (iOS and Android).\n *\n * @experimental\n * @alpha\n */\nexport class PowerSyncDatabase extends WebPowerSyncDatabase {\n get isNativeCapacitorPlatform() {\n const platform = Capacitor.getPlatform();\n return platform == 'ios' || platform == 'android';\n }\n openDBAdapter(options) {\n var _a, _b, _c;\n const platform = Capacitor.getPlatform();\n if (platform == 'ios' || platform == 'android') {\n if (options.database.dbLocation) {\n (_a = options.logger) === null || _a === void 0 ? void 0 : _a.warn(`\n dbLocation is ignored on iOS and Android platforms. \n The database directory can be configured in the Capacitor project.\n See https://github.com/capacitor-community/sqlite?tab=readme-ov-file#installation`);\n }\n (_b = options.logger) === null || _b === void 0 ? void 0 : _b.debug(`Using CapacitorSQLiteAdapter for platform: ${platform}`);\n return new CapacitorSQLiteAdapter(Object.assign({}, options.database));\n }\n else {\n (_c = options.logger) === null || _c === void 0 ? void 0 : _c.debug(`Using default web adapter for web platform`);\n return super.openDBAdapter(options);\n }\n }\n generateTriggerManagerConfig() {\n const config = super.generateTriggerManagerConfig();\n if (this.isNativeCapacitorPlatform) {\n /**\n * We usually only ever have a single tab for capacitor.\n * Avoiding navigator locks allows insecure contexts (during development).\n */\n config.claimManager = MEMORY_TRIGGER_CLAIM_MANAGER;\n }\n return config;\n }\n runExclusive(cb) {\n if (this.isNativeCapacitorPlatform) {\n // Use mutex for mobile platforms.\n // This is mainly for testing purposes since navigator.locks require secure contexts.\n return this.runExclusiveMutex.runExclusive(cb);\n }\n else {\n // Use navigator.locks for web platform\n return super.runExclusive(cb);\n }\n }\n generateSyncStreamImplementation(connector, options) {\n var _a;\n if (this.isNativeCapacitorPlatform) {\n // We don't want to support multi-tab on mobile platforms.\n // We technically can, but it's not a common use case and requires additional work/testing.\n this.logger.debug(`Using Capacitor sync implementation`);\n if ((_a = this.options.flags) === null || _a === void 0 ? void 0 : _a.enableMultiTabs) {\n this.logger.warn(`enableMultiTabs is not supported on Capacitor mobile platforms. Ignoring the flag.`);\n }\n const remote = new WebRemote(connector, this.logger);\n return new CapacitorStreamingSyncImplementation(Object.assign(Object.assign({}, this.options), { retryDelayMs: options.retryDelayMs, crudUploadThrottleMs: options.crudUploadThrottleMs, adapter: this.bucketStorageAdapter, remote, uploadCrud: async () => {\n await this.waitForReady();\n await connector.uploadData(this);\n }, identifier: this.database.name, logger: this.logger, subscriptions: options.subscriptions }));\n }\n else {\n this.logger.debug(`Using default web sync implementation for web platform`);\n return super.generateSyncStreamImplementation(connector, options);\n }\n }\n}\n//# sourceMappingURL=PowerSyncDatabase.js.map","import { WebPlugin } from '@capacitor/core';\nexport class PowerSyncWeb extends WebPlugin {\n async registerCore() {\n throw new Error('This code path is not supported on web.');\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","BaseObserver","sqlite","SQLiteConnection","CapacitorSQLite","Capacitor","AbstractStreamingSyncImplementation","WebPowerSyncDatabase","MEMORY_TRIGGER_CLAIM_MANAGER","WebRemote","WebPlugin"],"m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SyncImplementation.js","esm/PowerSyncDatabase.js","esm/plugin/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nexport const PowerSyncCore = registerPlugin('PowerSync', {\n web: () => import('./web.js').then((m) => new m.PowerSyncWeb())\n});\n//# sourceMappingURL=PowerSyncCore.js.map","export const messageForErrorCode = (code) => {\n switch (code) {\n case 0:\n return 'Success';\n default:\n return `Extension registration failed with SQLite error code: ${code}`;\n }\n};\n//# sourceMappingURL=PowerSyncPlugin.js.map","import { CapacitorSQLiteAdapter } from './CapacitorSQLiteAdapter.js';\nvar SqliteSynchronous;\n(function (SqliteSynchronous) {\n SqliteSynchronous[\"normal\"] = \"NORMAL\";\n SqliteSynchronous[\"full\"] = \"FULL\";\n SqliteSynchronous[\"off\"] = \"OFF\";\n})(SqliteSynchronous || (SqliteSynchronous = {}));\nexport const DEFAULT_SQLITE_OPTIONS = {\n journalSizeLimit: 6 * 1024 * 1024,\n synchronous: SqliteSynchronous.normal,\n cacheSizeKb: 50 * 1024\n};\nexport class CapacitorSQLiteOpenFactory {\n constructor(options) {\n this.options = options;\n }\n openDB() {\n return new CapacitorSQLiteAdapter(this.options);\n }\n}\n//# sourceMappingURL=CapacitorSQLiteOpenFactory.js.map","import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';\nimport { Capacitor } from '@capacitor/core';\nimport { BaseObserver, mutexRunExclusive } from '@powersync/web';\nimport { Mutex } from 'async-mutex';\nimport { PowerSyncCore } from '../plugin/PowerSyncCore.js';\nimport { messageForErrorCode } from '../plugin/PowerSyncPlugin.js';\nimport { DEFAULT_SQLITE_OPTIONS } from './CapacitorSQLiteOpenFactory.js';\n/**\n * Monitors the execution time of a query and logs it to the performance timeline.\n */\nasync function monitorQuery(sql, executor) {\n const start = performance.now();\n try {\n const r = await executor();\n performance.measure(`[SQL] ${sql}`, { start });\n return r;\n }\n catch (e) {\n performance.measure(`[SQL] [ERROR: ${e.message}] ${sql}`, { start });\n throw e;\n }\n}\n/**\n * An implementation of {@link DBAdapter} using the Capacitor Community SQLite [plugin](https://github.com/capacitor-community/sqlite).\n *\n * @experimental\n * @alpha This is currently experimental and may change without a major version bump.\n */\nexport class CapacitorSQLiteAdapter extends BaseObserver {\n constructor(options) {\n super();\n this.options = options;\n this._writeConnection = null;\n this._readConnection = null;\n this.writeMutex = new Mutex();\n this.readMutex = new Mutex();\n this.initializedPromise = this.init();\n }\n get writeConnection() {\n if (!this._writeConnection) {\n throw new Error('Init not completed yet');\n }\n return this._writeConnection;\n }\n get readConnection() {\n if (!this._readConnection) {\n throw new Error('Init not completed yet');\n }\n return this._readConnection;\n }\n get name() {\n return this.options.dbFilename;\n }\n async init() {\n const { responseCode: registrationResponseCode } = await PowerSyncCore.registerCore();\n if (registrationResponseCode != 0) {\n throw new Error(`Could not register PowerSync core extension: ${messageForErrorCode(registrationResponseCode)}`);\n }\n const sqlite = new SQLiteConnection(CapacitorSQLite);\n // It seems like the isConnection and retrieveConnection methods\n // only check a JS side map of connections.\n // On hot reload this JS cache can be cleared, while the connection\n // still exists natively. and `createConnection` will fail if it already exists.\n await sqlite.closeConnection(this.options.dbFilename, false).catch(() => { });\n await sqlite.closeConnection(this.options.dbFilename, true).catch(() => { });\n // TODO support encryption eventually\n this._writeConnection = await sqlite.createConnection(this.options.dbFilename, false, 'no-encryption', 1, false);\n this._readConnection = await sqlite.createConnection(this.options.dbFilename, false, 'no-encryption', 1, true);\n await this._writeConnection.open();\n const { cacheSizeKb, journalSizeLimit, synchronous } = Object.assign(Object.assign({}, DEFAULT_SQLITE_OPTIONS), this.options.sqliteOptions);\n await this.writeConnection.query('PRAGMA journal_mode = WAL');\n await this.writeConnection.query(`PRAGMA journal_size_limit = ${journalSizeLimit}`);\n await this.writeConnection.query(`PRAGMA temp_store = memory`);\n await this.writeConnection.query(`PRAGMA synchronous = ${synchronous}`);\n await this.writeConnection.query(`PRAGMA cache_size = -${cacheSizeKb}`);\n await this._readConnection.open();\n const platform = Capacitor.getPlatform();\n if (platform == 'android') {\n /**\n * SQLCipher for Android enables dynamic loading of extensions.\n * On iOS we use a static auto extension registration.\n */\n const extensionQuery = \"SELECT load_extension('libpowersync.so', 'sqlite3_powersync_init')\";\n await this.writeConnection.query(extensionQuery);\n await this.readConnection.query(extensionQuery);\n }\n await this.writeConnection.query(\"SELECT powersync_update_hooks('install')\");\n }\n async close() {\n await this.initializedPromise;\n await this.writeConnection.close();\n await this.readConnection.close();\n }\n generateLockContext(db) {\n const _query = async (query, params = []) => {\n var _a;\n const result = await db.query(query, params);\n const arrayResult = (_a = result.values) !== null && _a !== void 0 ? _a : [];\n return {\n rowsAffected: 0,\n rows: {\n _array: arrayResult,\n length: arrayResult.length,\n item: (idx) => arrayResult[idx]\n }\n };\n };\n const _execute = async (query, params = []) => {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n const platform = Capacitor.getPlatform();\n if (db.getConnectionReadOnly()) {\n return _query(query, params);\n }\n if (platform == 'android') {\n // Android: use query for SELECT and executeSet for mutations\n // We cannot use `run` here for both cases.\n if (query.toLowerCase().trim().startsWith('select')) {\n return _query(query, params);\n }\n else {\n const result = await db.executeSet([{ statement: query, values: params }], false);\n return {\n insertId: (_a = result.changes) === null || _a === void 0 ? void 0 : _a.lastId,\n rowsAffected: (_c = (_b = result.changes) === null || _b === void 0 ? void 0 : _b.changes) !== null && _c !== void 0 ? _c : 0,\n rows: {\n _array: [],\n length: 0,\n item: () => null\n }\n };\n }\n }\n // iOS (and other platforms): use run(\"all\")\n const result = await db.run(query, params, false, 'all');\n const resultSet = (_e = (_d = result.changes) === null || _d === void 0 ? void 0 : _d.values) !== null && _e !== void 0 ? _e : [];\n return {\n insertId: (_f = result.changes) === null || _f === void 0 ? void 0 : _f.lastId,\n rowsAffected: (_h = (_g = result.changes) === null || _g === void 0 ? void 0 : _g.changes) !== null && _h !== void 0 ? _h : 0,\n rows: {\n _array: resultSet,\n length: resultSet.length,\n item: (idx) => resultSet[idx]\n }\n };\n };\n const execute = this.options.debugMode\n ? (sql, params) => monitorQuery(sql, () => _execute(sql, params))\n : _execute;\n const executeQuery = this.options.debugMode\n ? (sql, params) => monitorQuery(sql, () => _query(sql, params))\n : _query;\n const getAll = async (query, params) => {\n var _a, _b;\n const result = await executeQuery(query, params);\n return (_b = (_a = result.rows) === null || _a === void 0 ? void 0 : _a._array) !== null && _b !== void 0 ? _b : [];\n };\n const getOptional = async (query, params) => {\n const results = await getAll(query, params);\n return results.length > 0 ? results[0] : null;\n };\n const get = async (query, params) => {\n const result = await getOptional(query, params);\n if (!result) {\n throw new Error(`No results for query: ${query}`);\n }\n return result;\n };\n const executeRaw = async (query, params) => {\n var _a, _b;\n // This is a workaround, we don't support multiple columns of the same name\n const results = await execute(query, params);\n return (_b = (_a = results.rows) === null || _a === void 0 ? void 0 : _a._array.map((row) => Object.values(row))) !== null && _b !== void 0 ? _b : [];\n };\n return {\n getAll,\n getOptional,\n get,\n executeRaw,\n execute\n };\n }\n execute(query, params) {\n return this.writeLock((tx) => tx.execute(query, params));\n }\n executeRaw(query, params) {\n return this.writeLock((tx) => tx.executeRaw(query, params));\n }\n async executeBatch(query, params = []) {\n return this.writeLock(async (tx) => {\n var _a, _b, _c;\n let result = await this.writeConnection.executeSet(params.map((param) => ({\n statement: query,\n values: param\n })));\n return {\n rowsAffected: (_b = (_a = result.changes) === null || _a === void 0 ? void 0 : _a.changes) !== null && _b !== void 0 ? _b : 0,\n insertId: (_c = result.changes) === null || _c === void 0 ? void 0 : _c.lastId\n };\n });\n }\n readLock(fn, options) {\n return mutexRunExclusive(this.readMutex, async () => {\n await this.initializedPromise;\n return await fn(this.generateLockContext(this.readConnection));\n }, options);\n }\n readTransaction(fn, options) {\n return this.readLock(async (ctx) => {\n return this.internalTransaction(ctx, fn);\n });\n }\n writeLock(fn, options) {\n return mutexRunExclusive(this.writeMutex, async () => {\n var _a;\n await this.initializedPromise;\n const result = await fn(this.generateLockContext(this.writeConnection));\n // Fetch table updates\n const updates = await this.writeConnection.query(\"SELECT powersync_update_hooks('get') AS table_name\");\n const jsonUpdates = (_a = updates.values) === null || _a === void 0 ? void 0 : _a[0];\n if (!jsonUpdates || !jsonUpdates.table_name) {\n throw new Error('Could not fetch table updates');\n }\n const notification = {\n rawUpdates: [],\n tables: JSON.parse(jsonUpdates.table_name),\n groupedUpdates: {}\n };\n this.iterateListeners((l) => { var _a; return (_a = l.tablesUpdated) === null || _a === void 0 ? void 0 : _a.call(l, notification); });\n return result;\n }, options);\n }\n writeTransaction(fn, options) {\n return this.writeLock(async (ctx) => {\n return this.internalTransaction(ctx, fn);\n });\n }\n refreshSchema() {\n return this.writeLock(async (writeTx) => {\n return this.readLock(async (readTx) => {\n const updateQuery = `PRAGMA table_info('sqlite_master')`;\n await writeTx.get(updateQuery);\n await readTx.get(updateQuery);\n });\n });\n }\n getAll(sql, parameters) {\n return this.readLock((tx) => tx.getAll(sql, parameters));\n }\n getOptional(sql, parameters) {\n return this.readLock((tx) => tx.getOptional(sql, parameters));\n }\n get(sql, parameters) {\n return this.readLock((tx) => tx.get(sql, parameters));\n }\n async internalTransaction(ctx, fn) {\n let finalized = false;\n const commit = async () => {\n if (finalized) {\n return { rowsAffected: 0 };\n }\n finalized = true;\n return ctx.execute('COMMIT');\n };\n const rollback = async () => {\n if (finalized) {\n return { rowsAffected: 0 };\n }\n finalized = true;\n return ctx.execute('ROLLBACK');\n };\n try {\n await ctx.execute('BEGIN');\n const result = await fn(Object.assign(Object.assign({}, ctx), { commit,\n rollback }));\n await commit();\n return result;\n }\n catch (ex) {\n try {\n await rollback();\n }\n catch (ex2) {\n // In rare cases, a rollback may fail.\n // Safe to ignore.\n }\n throw ex;\n }\n }\n}\n//# sourceMappingURL=CapacitorSQLiteAdapter.js.map","import { AbstractStreamingSyncImplementation, LockType, mutexRunExclusive } from '@powersync/web';\nimport { Mutex } from 'async-mutex';\nconst GLOBAL_MUTEX_STORE = new Map();\n/**\n * Used to identify multiple instances of CapacitorStreamingSyncImplementation\n */\nlet _CAPACITOR_STREAMING_SYNC_SEQUENCE = 0;\nexport class CapacitorStreamingSyncImplementation extends AbstractStreamingSyncImplementation {\n constructor() {\n super(...arguments);\n // A unique ID for tacking this specific instance of CapacitorStreamingSyncImplementation\n this.instanceId = _CAPACITOR_STREAMING_SYNC_SEQUENCE++;\n }\n async dispose() {\n await super.dispose();\n // Clear up any global mutexes which aren't used anymore\n for (const mutexEntry of GLOBAL_MUTEX_STORE.entries()) {\n const [identifier, mutex] = mutexEntry;\n if (!mutex.tracking.has(this.instanceId)) {\n continue;\n }\n mutex.tracking.delete(this.instanceId);\n if (mutex.tracking.size == 0) {\n GLOBAL_MUTEX_STORE.delete(identifier);\n }\n }\n }\n async obtainLock(lockOptions) {\n // If we don't have an identifier for some reason (should not happen), we use a shared Mutex\n const { identifier: baseIdentifier = 'DEFAULT' } = this.options;\n if (!GLOBAL_MUTEX_STORE.has(baseIdentifier)) {\n GLOBAL_MUTEX_STORE.set(baseIdentifier, {\n tracking: new Set([this.instanceId]),\n locks: {\n [LockType.CRUD]: new Mutex(),\n [LockType.SYNC]: new Mutex()\n }\n });\n }\n const mutexRecord = GLOBAL_MUTEX_STORE.get(baseIdentifier);\n mutexRecord.tracking.add(this.instanceId);\n const mutex = mutexRecord.locks[lockOptions.type];\n return mutexRunExclusive(mutex, async () => {\n var _a;\n if ((_a = lockOptions.signal) === null || _a === void 0 ? void 0 : _a.aborted) {\n throw new Error('Aborted');\n }\n return await lockOptions.callback();\n });\n }\n}\n//# sourceMappingURL=CapacitorSyncImplementation.js.map","import { Capacitor } from '@capacitor/core';\nimport { MEMORY_TRIGGER_CLAIM_MANAGER, PowerSyncDatabase as WebPowerSyncDatabase, WebRemote } from '@powersync/web';\nimport { CapacitorSQLiteAdapter } from './adapter/CapacitorSQLiteAdapter.js';\nimport { CapacitorStreamingSyncImplementation } from './sync/CapacitorSyncImplementation.js';\n/**\n * PowerSyncDatabase class for managing database connections and sync implementations.\n * This extends the WebPowerSyncDatabase to provide platform-specific implementations\n * for Capacitor environments (iOS and Android).\n *\n * @experimental\n * @alpha\n */\nexport class PowerSyncDatabase extends WebPowerSyncDatabase {\n get isNativeCapacitorPlatform() {\n const platform = Capacitor.getPlatform();\n return platform == 'ios' || platform == 'android';\n }\n openDBAdapter(options) {\n var _a, _b, _c;\n const platform = Capacitor.getPlatform();\n if (platform == 'ios' || platform == 'android') {\n if (options.database.dbLocation) {\n (_a = options.logger) === null || _a === void 0 ? void 0 : _a.warn(`\n dbLocation is ignored on iOS and Android platforms. \n The database directory can be configured in the Capacitor project.\n See https://github.com/capacitor-community/sqlite?tab=readme-ov-file#installation`);\n }\n (_b = options.logger) === null || _b === void 0 ? void 0 : _b.debug(`Using CapacitorSQLiteAdapter for platform: ${platform}`);\n return new CapacitorSQLiteAdapter(Object.assign({}, options.database));\n }\n else {\n (_c = options.logger) === null || _c === void 0 ? void 0 : _c.debug(`Using default web adapter for web platform`);\n return super.openDBAdapter(options);\n }\n }\n generateTriggerManagerConfig() {\n const config = super.generateTriggerManagerConfig();\n if (this.isNativeCapacitorPlatform) {\n /**\n * We usually only ever have a single tab for capacitor.\n * Avoiding navigator locks allows insecure contexts (during development).\n */\n config.claimManager = MEMORY_TRIGGER_CLAIM_MANAGER;\n }\n return config;\n }\n runExclusive(cb) {\n if (this.isNativeCapacitorPlatform) {\n // Use mutex for mobile platforms.\n // This is mainly for testing purposes since navigator.locks require secure contexts.\n return this.runExclusiveMutex.runExclusive(cb);\n }\n else {\n // Use navigator.locks for web platform\n return super.runExclusive(cb);\n }\n }\n generateSyncStreamImplementation(connector, options) {\n var _a;\n if (this.isNativeCapacitorPlatform) {\n // We don't want to support multi-tab on mobile platforms.\n // We technically can, but it's not a common use case and requires additional work/testing.\n this.logger.debug(`Using Capacitor sync implementation`);\n if ((_a = this.options.flags) === null || _a === void 0 ? void 0 : _a.enableMultiTabs) {\n this.logger.warn(`enableMultiTabs is not supported on Capacitor mobile platforms. Ignoring the flag.`);\n }\n const remote = new WebRemote(connector, this.logger);\n return new CapacitorStreamingSyncImplementation(Object.assign(Object.assign({}, this.options), { retryDelayMs: options.retryDelayMs, crudUploadThrottleMs: options.crudUploadThrottleMs, adapter: this.bucketStorageAdapter, remote, uploadCrud: async () => {\n await this.waitForReady();\n await connector.uploadData(this);\n }, identifier: this.database.name, logger: this.logger, subscriptions: options.subscriptions }));\n }\n else {\n this.logger.debug(`Using default web sync implementation for web platform`);\n return super.generateSyncStreamImplementation(connector, options);\n }\n }\n}\n//# sourceMappingURL=PowerSyncDatabase.js.map","import { WebPlugin } from '@capacitor/core';\nexport class PowerSyncWeb extends WebPlugin {\n async registerCore() {\n throw new Error('This code path is not supported on web.');\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","BaseObserver","Mutex","sqlite","SQLiteConnection","CapacitorSQLite","Capacitor","mutexRunExclusive","AbstractStreamingSyncImplementation","LockType","WebPowerSyncDatabase","MEMORY_TRIGGER_CLAIM_MANAGER","WebRemote","WebPlugin"],"mappings":";;;;;;;AACO,MAAM,aAAa,GAAGA,mBAAc,CAAC,WAAW,EAAE;AACzD,IAAI,GAAG,EAAE,MAAM,mDAAkB,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,YAAY,EAAE;AAClE,CAAC,CAAC;;ACHK,MAAM,mBAAmB,GAAG,CAAC,IAAI,KAAK;AAC7C,IAAI,QAAQ,IAAI;AAChB,QAAQ,KAAK,CAAC;AACd,YAAY,OAAO,SAAS;AAC5B,QAAQ;AACR,YAAY,OAAO,CAAC,sDAAsD,EAAE,IAAI,CAAC,CAAC;AAClF;AACA,CAAC;;ACND,IAAI,iBAAiB;AACrB,CAAC,UAAU,iBAAiB,EAAE;AAC9B,IAAI,iBAAiB,CAAC,QAAQ,CAAC,GAAG,QAAQ;AAC1C,IAAI,iBAAiB,CAAC,MAAM,CAAC,GAAG,MAAM;AACtC,IAAI,iBAAiB,CAAC,KAAK,CAAC,GAAG,KAAK;AACpC,CAAC,EAAE,iBAAiB,KAAK,iBAAiB,GAAG,E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oBAAoB,MAAM,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC;AACpD,gBAAgB,CAAC,EAAE,UAAU,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC;AAChH,QAAQ;AACR,aAAa;AACb,YAAY,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,sDAAsD,CAAC,CAAC;AACvF,YAAY,OAAO,KAAK,CAAC,gCAAgC,CAAC,SAAS,EAAE,OAAO,CAAC;AAC7E,QAAQ;AACR,IAAI;AACJ;;AC5EO,MAAM,YAAY,SAASC,cAAS,CAAC;AAC5C,IAAI,MAAM,YAAY,GAAG;AACzB,QAAQ,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC;AAClE,IAAI;AACJ;;;;;;;;;;;"}
package/dist/plugin.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { SQLiteDBConnection } from '@capacitor-community/sqlite';
2
2
  import { SQLOpenOptions, SQLOpenFactory, DBAdapter, BaseObserver, DBAdapterListener, LockContext, QueryResult, DBLockOptions, Transaction, PowerSyncDatabase as PowerSyncDatabase$1, WebPowerSyncDatabaseOptionsWithSettings, TriggerManagerConfig, PowerSyncBackendConnector, RequiredAdditionalConnectionOptions, StreamingSyncImplementation } from '@powersync/web';
3
- import Lock from 'async-lock';
3
+ import { Mutex } from 'async-mutex';
4
4
 
5
5
  declare enum SqliteSynchronous {
6
6
  normal = "NORMAL",
@@ -46,7 +46,8 @@ declare class CapacitorSQLiteAdapter extends BaseObserver<DBAdapterListener> imp
46
46
  protected _writeConnection: SQLiteDBConnection | null;
47
47
  protected _readConnection: SQLiteDBConnection | null;
48
48
  protected initializedPromise: Promise<void>;
49
- protected lock: Lock;
49
+ protected writeMutex: Mutex;
50
+ protected readMutex: Mutex;
50
51
  constructor(options: CapacitorSQLiteOpenFactoryOptions);
51
52
  protected get writeConnection(): SQLiteDBConnection;
52
53
  protected get readConnection(): SQLiteDBConnection;
package/dist/plugin.js CHANGED
@@ -1,4 +1,4 @@
1
- var capacitorPowerSync = (function (exports, sqlite, core, web$1, Lock) {
1
+ var capacitorPowerSync = (function (exports, sqlite, core, web$1, asyncMutex) {
2
2
  'use strict';
3
3
 
4
4
  const PowerSyncCore = core.registerPlugin('PowerSync', {
@@ -61,7 +61,8 @@ var capacitorPowerSync = (function (exports, sqlite, core, web$1, Lock) {
61
61
  this.options = options;
62
62
  this._writeConnection = null;
63
63
  this._readConnection = null;
64
- this.lock = new Lock();
64
+ this.writeMutex = new asyncMutex.Mutex();
65
+ this.readMutex = new asyncMutex.Mutex();
65
66
  this.initializedPromise = this.init();
66
67
  }
67
68
  get writeConnection() {
@@ -227,10 +228,10 @@ var capacitorPowerSync = (function (exports, sqlite, core, web$1, Lock) {
227
228
  });
228
229
  }
229
230
  readLock(fn, options) {
230
- return this.lock.acquire('read_lock', async () => {
231
+ return web$1.mutexRunExclusive(this.readMutex, async () => {
231
232
  await this.initializedPromise;
232
233
  return await fn(this.generateLockContext(this.readConnection));
233
- });
234
+ }, options);
234
235
  }
235
236
  readTransaction(fn, options) {
236
237
  return this.readLock(async (ctx) => {
@@ -238,7 +239,7 @@ var capacitorPowerSync = (function (exports, sqlite, core, web$1, Lock) {
238
239
  });
239
240
  }
240
241
  writeLock(fn, options) {
241
- return this.lock.acquire('write_lock', async () => {
242
+ return web$1.mutexRunExclusive(this.writeMutex, async () => {
242
243
  var _a;
243
244
  await this.initializedPromise;
244
245
  const result = await fn(this.generateLockContext(this.writeConnection));
@@ -255,7 +256,7 @@ var capacitorPowerSync = (function (exports, sqlite, core, web$1, Lock) {
255
256
  };
256
257
  this.iterateListeners((l) => { var _a; return (_a = l.tablesUpdated) === null || _a === void 0 ? void 0 : _a.call(l, notification); });
257
258
  return result;
258
- });
259
+ }, options);
259
260
  }
260
261
  writeTransaction(fn, options) {
261
262
  return this.writeLock(async (ctx) => {
@@ -316,10 +317,47 @@ var capacitorPowerSync = (function (exports, sqlite, core, web$1, Lock) {
316
317
  }
317
318
  }
318
319
 
320
+ const GLOBAL_MUTEX_STORE = new Map();
321
+ /**
322
+ * Used to identify multiple instances of CapacitorStreamingSyncImplementation
323
+ */
324
+ let _CAPACITOR_STREAMING_SYNC_SEQUENCE = 0;
319
325
  class CapacitorStreamingSyncImplementation extends web$1.AbstractStreamingSyncImplementation {
326
+ constructor() {
327
+ super(...arguments);
328
+ // A unique ID for tacking this specific instance of CapacitorStreamingSyncImplementation
329
+ this.instanceId = _CAPACITOR_STREAMING_SYNC_SEQUENCE++;
330
+ }
331
+ async dispose() {
332
+ await super.dispose();
333
+ // Clear up any global mutexes which aren't used anymore
334
+ for (const mutexEntry of GLOBAL_MUTEX_STORE.entries()) {
335
+ const [identifier, mutex] = mutexEntry;
336
+ if (!mutex.tracking.has(this.instanceId)) {
337
+ continue;
338
+ }
339
+ mutex.tracking.delete(this.instanceId);
340
+ if (mutex.tracking.size == 0) {
341
+ GLOBAL_MUTEX_STORE.delete(identifier);
342
+ }
343
+ }
344
+ }
320
345
  async obtainLock(lockOptions) {
321
- const identifier = `streaming-sync-${lockOptions.type}-${this.options.identifier}`;
322
- return CapacitorStreamingSyncImplementation.GLOBAL_LOCK.acquire(identifier, async () => {
346
+ // If we don't have an identifier for some reason (should not happen), we use a shared Mutex
347
+ const { identifier: baseIdentifier = 'DEFAULT' } = this.options;
348
+ if (!GLOBAL_MUTEX_STORE.has(baseIdentifier)) {
349
+ GLOBAL_MUTEX_STORE.set(baseIdentifier, {
350
+ tracking: new Set([this.instanceId]),
351
+ locks: {
352
+ [web$1.LockType.CRUD]: new asyncMutex.Mutex(),
353
+ [web$1.LockType.SYNC]: new asyncMutex.Mutex()
354
+ }
355
+ });
356
+ }
357
+ const mutexRecord = GLOBAL_MUTEX_STORE.get(baseIdentifier);
358
+ mutexRecord.tracking.add(this.instanceId);
359
+ const mutex = mutexRecord.locks[lockOptions.type];
360
+ return web$1.mutexRunExclusive(mutex, async () => {
323
361
  var _a;
324
362
  if ((_a = lockOptions.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
325
363
  throw new Error('Aborted');
@@ -328,7 +366,6 @@ var capacitorPowerSync = (function (exports, sqlite, core, web$1, Lock) {
328
366
  });
329
367
  }
330
368
  }
331
- CapacitorStreamingSyncImplementation.GLOBAL_LOCK = new Lock();
332
369
 
333
370
  /**
334
371
  * PowerSyncDatabase class for managing database connections and sync implementations.
@@ -422,5 +459,5 @@ var capacitorPowerSync = (function (exports, sqlite, core, web$1, Lock) {
422
459
 
423
460
  return exports;
424
461
 
425
- })({}, sqlite, capacitorExports, web$1, Lock);
462
+ })({}, sqlite, capacitorExports, web$1, asyncMutex);
426
463
  //# sourceMappingURL=plugin.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sources":["esm/plugin/PowerSyncCore.js","esm/plugin/PowerSyncPlugin.js","esm/adapter/CapacitorSQLiteOpenFactory.js","esm/adapter/CapacitorSQLiteAdapter.js","esm/sync/CapacitorSyncImplementation.js","esm/PowerSyncDatabase.js","esm/plugin/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nexport const PowerSyncCore = registerPlugin('PowerSync', {\n web: () => import('./web.js').then((m) => new m.PowerSyncWeb())\n});\n//# sourceMappingURL=PowerSyncCore.js.map","export const messageForErrorCode = (code) => {\n switch (code) {\n case 0:\n return 'Success';\n default:\n return `Extension registration failed with SQLite error code: ${code}`;\n }\n};\n//# sourceMappingURL=PowerSyncPlugin.js.map","import { CapacitorSQLiteAdapter } from './CapacitorSQLiteAdapter.js';\nvar SqliteSynchronous;\n(function (SqliteSynchronous) {\n SqliteSynchronous[\"normal\"] = \"NORMAL\";\n SqliteSynchronous[\"full\"] = \"FULL\";\n SqliteSynchronous[\"off\"] = \"OFF\";\n})(SqliteSynchronous || (SqliteSynchronous = {}));\nexport const DEFAULT_SQLITE_OPTIONS = {\n journalSizeLimit: 6 * 1024 * 1024,\n synchronous: SqliteSynchronous.normal,\n cacheSizeKb: 50 * 1024\n};\nexport class CapacitorSQLiteOpenFactory {\n constructor(options) {\n this.options = options;\n }\n openDB() {\n return new CapacitorSQLiteAdapter(this.options);\n }\n}\n//# sourceMappingURL=CapacitorSQLiteOpenFactory.js.map","import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';\nimport { Capacitor } from '@capacitor/core';\nimport { BaseObserver } from '@powersync/web';\nimport Lock from 'async-lock';\nimport { PowerSyncCore } from '../plugin/PowerSyncCore.js';\nimport { messageForErrorCode } from '../plugin/PowerSyncPlugin.js';\nimport { DEFAULT_SQLITE_OPTIONS } from './CapacitorSQLiteOpenFactory.js';\n/**\n * Monitors the execution time of a query and logs it to the performance timeline.\n */\nasync function monitorQuery(sql, executor) {\n const start = performance.now();\n try {\n const r = await executor();\n performance.measure(`[SQL] ${sql}`, { start });\n return r;\n }\n catch (e) {\n performance.measure(`[SQL] [ERROR: ${e.message}] ${sql}`, { start });\n throw e;\n }\n}\n/**\n * An implementation of {@link DBAdapter} using the Capacitor Community SQLite [plugin](https://github.com/capacitor-community/sqlite).\n *\n * @experimental\n * @alpha This is currently experimental and may change without a major version bump.\n */\nexport class CapacitorSQLiteAdapter extends BaseObserver {\n constructor(options) {\n super();\n this.options = options;\n this._writeConnection = null;\n this._readConnection = null;\n this.lock = new Lock();\n this.initializedPromise = this.init();\n }\n get writeConnection() {\n if (!this._writeConnection) {\n throw new Error('Init not completed yet');\n }\n return this._writeConnection;\n }\n get readConnection() {\n if (!this._readConnection) {\n throw new Error('Init not completed yet');\n }\n return this._readConnection;\n }\n get name() {\n return this.options.dbFilename;\n }\n async init() {\n const { responseCode: registrationResponseCode } = await PowerSyncCore.registerCore();\n if (registrationResponseCode != 0) {\n throw new Error(`Could not register PowerSync core extension: ${messageForErrorCode(registrationResponseCode)}`);\n }\n const sqlite = new SQLiteConnection(CapacitorSQLite);\n // It seems like the isConnection and retrieveConnection methods\n // only check a JS side map of connections.\n // On hot reload this JS cache can be cleared, while the connection\n // still exists natively. and `createConnection` will fail if it already exists.\n await sqlite.closeConnection(this.options.dbFilename, false).catch(() => { });\n await sqlite.closeConnection(this.options.dbFilename, true).catch(() => { });\n // TODO support encryption eventually\n this._writeConnection = await sqlite.createConnection(this.options.dbFilename, false, 'no-encryption', 1, false);\n this._readConnection = await sqlite.createConnection(this.options.dbFilename, false, 'no-encryption', 1, true);\n await this._writeConnection.open();\n const { cacheSizeKb, journalSizeLimit, synchronous } = Object.assign(Object.assign({}, DEFAULT_SQLITE_OPTIONS), this.options.sqliteOptions);\n await this.writeConnection.query('PRAGMA journal_mode = WAL');\n await this.writeConnection.query(`PRAGMA journal_size_limit = ${journalSizeLimit}`);\n await this.writeConnection.query(`PRAGMA temp_store = memory`);\n await this.writeConnection.query(`PRAGMA synchronous = ${synchronous}`);\n await this.writeConnection.query(`PRAGMA cache_size = -${cacheSizeKb}`);\n await this._readConnection.open();\n const platform = Capacitor.getPlatform();\n if (platform == 'android') {\n /**\n * SQLCipher for Android enables dynamic loading of extensions.\n * On iOS we use a static auto extension registration.\n */\n const extensionQuery = \"SELECT load_extension('libpowersync.so', 'sqlite3_powersync_init')\";\n await this.writeConnection.query(extensionQuery);\n await this.readConnection.query(extensionQuery);\n }\n await this.writeConnection.query(\"SELECT powersync_update_hooks('install')\");\n }\n async close() {\n await this.initializedPromise;\n await this.writeConnection.close();\n await this.readConnection.close();\n }\n generateLockContext(db) {\n const _query = async (query, params = []) => {\n var _a;\n const result = await db.query(query, params);\n const arrayResult = (_a = result.values) !== null && _a !== void 0 ? _a : [];\n return {\n rowsAffected: 0,\n rows: {\n _array: arrayResult,\n length: arrayResult.length,\n item: (idx) => arrayResult[idx]\n }\n };\n };\n const _execute = async (query, params = []) => {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n const platform = Capacitor.getPlatform();\n if (db.getConnectionReadOnly()) {\n return _query(query, params);\n }\n if (platform == 'android') {\n // Android: use query for SELECT and executeSet for mutations\n // We cannot use `run` here for both cases.\n if (query.toLowerCase().trim().startsWith('select')) {\n return _query(query, params);\n }\n else {\n const result = await db.executeSet([{ statement: query, values: params }], false);\n return {\n insertId: (_a = result.changes) === null || _a === void 0 ? void 0 : _a.lastId,\n rowsAffected: (_c = (_b = result.changes) === null || _b === void 0 ? void 0 : _b.changes) !== null && _c !== void 0 ? _c : 0,\n rows: {\n _array: [],\n length: 0,\n item: () => null\n }\n };\n }\n }\n // iOS (and other platforms): use run(\"all\")\n const result = await db.run(query, params, false, 'all');\n const resultSet = (_e = (_d = result.changes) === null || _d === void 0 ? void 0 : _d.values) !== null && _e !== void 0 ? _e : [];\n return {\n insertId: (_f = result.changes) === null || _f === void 0 ? void 0 : _f.lastId,\n rowsAffected: (_h = (_g = result.changes) === null || _g === void 0 ? void 0 : _g.changes) !== null && _h !== void 0 ? _h : 0,\n rows: {\n _array: resultSet,\n length: resultSet.length,\n item: (idx) => resultSet[idx]\n }\n };\n };\n const execute = this.options.debugMode\n ? (sql, params) => monitorQuery(sql, () => _execute(sql, params))\n : _execute;\n const executeQuery = this.options.debugMode\n ? (sql, params) => monitorQuery(sql, () => _query(sql, params))\n : _query;\n const getAll = async (query, params) => {\n var _a, _b;\n const result = await executeQuery(query, params);\n return (_b = (_a = result.rows) === null || _a === void 0 ? void 0 : _a._array) !== null && _b !== void 0 ? _b : [];\n };\n const getOptional = async (query, params) => {\n const results = await getAll(query, params);\n return results.length > 0 ? results[0] : null;\n };\n const get = async (query, params) => {\n const result = await getOptional(query, params);\n if (!result) {\n throw new Error(`No results for query: ${query}`);\n }\n return result;\n };\n const executeRaw = async (query, params) => {\n var _a, _b;\n // This is a workaround, we don't support multiple columns of the same name\n const results = await execute(query, params);\n return (_b = (_a = results.rows) === null || _a === void 0 ? void 0 : _a._array.map((row) => Object.values(row))) !== null && _b !== void 0 ? _b : [];\n };\n return {\n getAll,\n getOptional,\n get,\n executeRaw,\n execute\n };\n }\n execute(query, params) {\n return this.writeLock((tx) => tx.execute(query, params));\n }\n executeRaw(query, params) {\n return this.writeLock((tx) => tx.executeRaw(query, params));\n }\n async executeBatch(query, params = []) {\n return this.writeLock(async (tx) => {\n var _a, _b, _c;\n let result = await this.writeConnection.executeSet(params.map((param) => ({\n statement: query,\n values: param\n })));\n return {\n rowsAffected: (_b = (_a = result.changes) === null || _a === void 0 ? void 0 : _a.changes) !== null && _b !== void 0 ? _b : 0,\n insertId: (_c = result.changes) === null || _c === void 0 ? void 0 : _c.lastId\n };\n });\n }\n readLock(fn, options) {\n return this.lock.acquire('read_lock', async () => {\n await this.initializedPromise;\n return await fn(this.generateLockContext(this.readConnection));\n });\n }\n readTransaction(fn, options) {\n return this.readLock(async (ctx) => {\n return this.internalTransaction(ctx, fn);\n });\n }\n writeLock(fn, options) {\n return this.lock.acquire('write_lock', async () => {\n var _a;\n await this.initializedPromise;\n const result = await fn(this.generateLockContext(this.writeConnection));\n // Fetch table updates\n const updates = await this.writeConnection.query(\"SELECT powersync_update_hooks('get') AS table_name\");\n const jsonUpdates = (_a = updates.values) === null || _a === void 0 ? void 0 : _a[0];\n if (!jsonUpdates || !jsonUpdates.table_name) {\n throw new Error('Could not fetch table updates');\n }\n const notification = {\n rawUpdates: [],\n tables: JSON.parse(jsonUpdates.table_name),\n groupedUpdates: {}\n };\n this.iterateListeners((l) => { var _a; return (_a = l.tablesUpdated) === null || _a === void 0 ? void 0 : _a.call(l, notification); });\n return result;\n });\n }\n writeTransaction(fn, options) {\n return this.writeLock(async (ctx) => {\n return this.internalTransaction(ctx, fn);\n });\n }\n refreshSchema() {\n return this.writeLock(async (writeTx) => {\n return this.readLock(async (readTx) => {\n const updateQuery = `PRAGMA table_info('sqlite_master')`;\n await writeTx.get(updateQuery);\n await readTx.get(updateQuery);\n });\n });\n }\n getAll(sql, parameters) {\n return this.readLock((tx) => tx.getAll(sql, parameters));\n }\n getOptional(sql, parameters) {\n return this.readLock((tx) => tx.getOptional(sql, parameters));\n }\n get(sql, parameters) {\n return this.readLock((tx) => tx.get(sql, parameters));\n }\n async internalTransaction(ctx, fn) {\n let finalized = false;\n const commit = async () => {\n if (finalized) {\n return { rowsAffected: 0 };\n }\n finalized = true;\n return ctx.execute('COMMIT');\n };\n const rollback = async () => {\n if (finalized) {\n return { rowsAffected: 0 };\n }\n finalized = true;\n return ctx.execute('ROLLBACK');\n };\n try {\n await ctx.execute('BEGIN');\n const result = await fn(Object.assign(Object.assign({}, ctx), { commit,\n rollback }));\n await commit();\n return result;\n }\n catch (ex) {\n try {\n await rollback();\n }\n catch (ex2) {\n // In rare cases, a rollback may fail.\n // Safe to ignore.\n }\n throw ex;\n }\n }\n}\n//# sourceMappingURL=CapacitorSQLiteAdapter.js.map","import { AbstractStreamingSyncImplementation } from '@powersync/web';\nimport Lock from 'async-lock';\nexport class CapacitorStreamingSyncImplementation extends AbstractStreamingSyncImplementation {\n async obtainLock(lockOptions) {\n const identifier = `streaming-sync-${lockOptions.type}-${this.options.identifier}`;\n return CapacitorStreamingSyncImplementation.GLOBAL_LOCK.acquire(identifier, async () => {\n var _a;\n if ((_a = lockOptions.signal) === null || _a === void 0 ? void 0 : _a.aborted) {\n throw new Error('Aborted');\n }\n return await lockOptions.callback();\n });\n }\n}\nCapacitorStreamingSyncImplementation.GLOBAL_LOCK = new Lock();\n//# sourceMappingURL=CapacitorSyncImplementation.js.map","import { Capacitor } from '@capacitor/core';\nimport { MEMORY_TRIGGER_CLAIM_MANAGER, PowerSyncDatabase as WebPowerSyncDatabase, WebRemote } from '@powersync/web';\nimport { CapacitorSQLiteAdapter } from './adapter/CapacitorSQLiteAdapter.js';\nimport { CapacitorStreamingSyncImplementation } from './sync/CapacitorSyncImplementation.js';\n/**\n * PowerSyncDatabase class for managing database connections and sync implementations.\n * This extends the WebPowerSyncDatabase to provide platform-specific implementations\n * for Capacitor environments (iOS and Android).\n *\n * @experimental\n * @alpha\n */\nexport class PowerSyncDatabase extends WebPowerSyncDatabase {\n get isNativeCapacitorPlatform() {\n const platform = Capacitor.getPlatform();\n return platform == 'ios' || platform == 'android';\n }\n openDBAdapter(options) {\n var _a, _b, _c;\n const platform = Capacitor.getPlatform();\n if (platform == 'ios' || platform == 'android') {\n if (options.database.dbLocation) {\n (_a = options.logger) === null || _a === void 0 ? void 0 : _a.warn(`\n dbLocation is ignored on iOS and Android platforms. \n The database directory can be configured in the Capacitor project.\n See https://github.com/capacitor-community/sqlite?tab=readme-ov-file#installation`);\n }\n (_b = options.logger) === null || _b === void 0 ? void 0 : _b.debug(`Using CapacitorSQLiteAdapter for platform: ${platform}`);\n return new CapacitorSQLiteAdapter(Object.assign({}, options.database));\n }\n else {\n (_c = options.logger) === null || _c === void 0 ? void 0 : _c.debug(`Using default web adapter for web platform`);\n return super.openDBAdapter(options);\n }\n }\n generateTriggerManagerConfig() {\n const config = super.generateTriggerManagerConfig();\n if (this.isNativeCapacitorPlatform) {\n /**\n * We usually only ever have a single tab for capacitor.\n * Avoiding navigator locks allows insecure contexts (during development).\n */\n config.claimManager = MEMORY_TRIGGER_CLAIM_MANAGER;\n }\n return config;\n }\n runExclusive(cb) {\n if (this.isNativeCapacitorPlatform) {\n // Use mutex for mobile platforms.\n // This is mainly for testing purposes since navigator.locks require secure contexts.\n return this.runExclusiveMutex.runExclusive(cb);\n }\n else {\n // Use navigator.locks for web platform\n return super.runExclusive(cb);\n }\n }\n generateSyncStreamImplementation(connector, options) {\n var _a;\n if (this.isNativeCapacitorPlatform) {\n // We don't want to support multi-tab on mobile platforms.\n // We technically can, but it's not a common use case and requires additional work/testing.\n this.logger.debug(`Using Capacitor sync implementation`);\n if ((_a = this.options.flags) === null || _a === void 0 ? void 0 : _a.enableMultiTabs) {\n this.logger.warn(`enableMultiTabs is not supported on Capacitor mobile platforms. Ignoring the flag.`);\n }\n const remote = new WebRemote(connector, this.logger);\n return new CapacitorStreamingSyncImplementation(Object.assign(Object.assign({}, this.options), { retryDelayMs: options.retryDelayMs, crudUploadThrottleMs: options.crudUploadThrottleMs, adapter: this.bucketStorageAdapter, remote, uploadCrud: async () => {\n await this.waitForReady();\n await connector.uploadData(this);\n }, identifier: this.database.name, logger: this.logger, subscriptions: options.subscriptions }));\n }\n else {\n this.logger.debug(`Using default web sync implementation for web platform`);\n return super.generateSyncStreamImplementation(connector, options);\n }\n }\n}\n//# sourceMappingURL=PowerSyncDatabase.js.map","import { WebPlugin } from '@capacitor/core';\nexport class PowerSyncWeb extends WebPlugin {\n async registerCore() {\n throw new Error('This code path is not supported on web.');\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","BaseObserver","sqlite","SQLiteConnection","CapacitorSQLite","Capacitor","AbstractStreamingSyncImplementation","WebPowerSyncDatabase","MEMORY_TRIGGER_CLAIM_MANAGER","WebRemote","WebPlugin"],"mappings":";;;IACO,MAAM,aAAa,GAAGA,mBAAc,CAAC,WAAW,EAAE;IACzD,IAAI,GAAG,EAAE,MAAM,mDAAkB,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,YAAY,EAAE;IAClE,CAAC,CAAC;;ICHK,MAAM,mBAAmB,GAAG,CAAC,IAAI,KAAK;IAC7C,IAAI,QAAQ,IAAI;IAChB,QAAQ,KAAK,CAAC;IACd,YAAY,OAAO,SAAS;IAC5B,QAAQ;IACR,YAAY,OAAO,CAAC,sDAAsD,EAAE,IAAI,CAAC,CAAC;IAClF;IACA,CAAC;;ICND,IAAI,iBAAiB;IACrB,CAAC,UAAU,iBAAiB,EAAE;IAC9B,IAAI,iBAAiB,CAAC,QAAQ,CAAC,GAAG,QAAQ;IAC1C,IAAI,iBAAiB,CAAC,MAAM,CAAC,GAAG,MAAM;IACtC,IAAI,iBAAiB,CAAC,KAAK,CAAC,GAAG,KAAK;IACpC,CAAC,EAAE,iBAAiB,KAAK,iBAAiB,GAAG,EAAE,CAAC,CAAC;IAC1C,MAAM,sBAAsB,GAAG;IACtC,IAAI,gBAAgB,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI;IACrC,IAAI,WAAW,EAAE,iBAAiB,CAAC,MAAM;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CAAC,CAAC,sDAAsD,CAAC,CAAC;IACvF,YAAY,OAAO,KAAK,CAAC,gCAAgC,CAAC,SAAS,EAAE,OAAO,CAAC;IAC7E,QAAQ;IACR,IAAI;IACJ;;IC5EO,MAAM,YAAY,SAASC,cAAS,CAAC;IAC5C,IAAI,MAAM,YAAY,GAAG;IACzB,QAAQ,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC;IAClE,IAAI;IACJ;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"plugin.js","sources":["esm/plugin/PowerSyncCore.js","esm/plugin/PowerSyncPlugin.js","esm/adapter/CapacitorSQLiteOpenFactory.js","esm/adapter/CapacitorSQLiteAdapter.js","esm/sync/CapacitorSyncImplementation.js","esm/PowerSyncDatabase.js","esm/plugin/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nexport const PowerSyncCore = registerPlugin('PowerSync', {\n web: () => import('./web.js').then((m) => new m.PowerSyncWeb())\n});\n//# sourceMappingURL=PowerSyncCore.js.map","export const messageForErrorCode = (code) => {\n switch (code) {\n case 0:\n return 'Success';\n default:\n return `Extension registration failed with SQLite error code: ${code}`;\n }\n};\n//# sourceMappingURL=PowerSyncPlugin.js.map","import { CapacitorSQLiteAdapter } from './CapacitorSQLiteAdapter.js';\nvar SqliteSynchronous;\n(function (SqliteSynchronous) {\n SqliteSynchronous[\"normal\"] = \"NORMAL\";\n SqliteSynchronous[\"full\"] = \"FULL\";\n SqliteSynchronous[\"off\"] = \"OFF\";\n})(SqliteSynchronous || (SqliteSynchronous = {}));\nexport const DEFAULT_SQLITE_OPTIONS = {\n journalSizeLimit: 6 * 1024 * 1024,\n synchronous: SqliteSynchronous.normal,\n cacheSizeKb: 50 * 1024\n};\nexport class CapacitorSQLiteOpenFactory {\n constructor(options) {\n this.options = options;\n }\n openDB() {\n return new CapacitorSQLiteAdapter(this.options);\n }\n}\n//# sourceMappingURL=CapacitorSQLiteOpenFactory.js.map","import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';\nimport { Capacitor } from '@capacitor/core';\nimport { BaseObserver, mutexRunExclusive } from '@powersync/web';\nimport { Mutex } from 'async-mutex';\nimport { PowerSyncCore } from '../plugin/PowerSyncCore.js';\nimport { messageForErrorCode } from '../plugin/PowerSyncPlugin.js';\nimport { DEFAULT_SQLITE_OPTIONS } from './CapacitorSQLiteOpenFactory.js';\n/**\n * Monitors the execution time of a query and logs it to the performance timeline.\n */\nasync function monitorQuery(sql, executor) {\n const start = performance.now();\n try {\n const r = await executor();\n performance.measure(`[SQL] ${sql}`, { start });\n return r;\n }\n catch (e) {\n performance.measure(`[SQL] [ERROR: ${e.message}] ${sql}`, { start });\n throw e;\n }\n}\n/**\n * An implementation of {@link DBAdapter} using the Capacitor Community SQLite [plugin](https://github.com/capacitor-community/sqlite).\n *\n * @experimental\n * @alpha This is currently experimental and may change without a major version bump.\n */\nexport class CapacitorSQLiteAdapter extends BaseObserver {\n constructor(options) {\n super();\n this.options = options;\n this._writeConnection = null;\n this._readConnection = null;\n this.writeMutex = new Mutex();\n this.readMutex = new Mutex();\n this.initializedPromise = this.init();\n }\n get writeConnection() {\n if (!this._writeConnection) {\n throw new Error('Init not completed yet');\n }\n return this._writeConnection;\n }\n get readConnection() {\n if (!this._readConnection) {\n throw new Error('Init not completed yet');\n }\n return this._readConnection;\n }\n get name() {\n return this.options.dbFilename;\n }\n async init() {\n const { responseCode: registrationResponseCode } = await PowerSyncCore.registerCore();\n if (registrationResponseCode != 0) {\n throw new Error(`Could not register PowerSync core extension: ${messageForErrorCode(registrationResponseCode)}`);\n }\n const sqlite = new SQLiteConnection(CapacitorSQLite);\n // It seems like the isConnection and retrieveConnection methods\n // only check a JS side map of connections.\n // On hot reload this JS cache can be cleared, while the connection\n // still exists natively. and `createConnection` will fail if it already exists.\n await sqlite.closeConnection(this.options.dbFilename, false).catch(() => { });\n await sqlite.closeConnection(this.options.dbFilename, true).catch(() => { });\n // TODO support encryption eventually\n this._writeConnection = await sqlite.createConnection(this.options.dbFilename, false, 'no-encryption', 1, false);\n this._readConnection = await sqlite.createConnection(this.options.dbFilename, false, 'no-encryption', 1, true);\n await this._writeConnection.open();\n const { cacheSizeKb, journalSizeLimit, synchronous } = Object.assign(Object.assign({}, DEFAULT_SQLITE_OPTIONS), this.options.sqliteOptions);\n await this.writeConnection.query('PRAGMA journal_mode = WAL');\n await this.writeConnection.query(`PRAGMA journal_size_limit = ${journalSizeLimit}`);\n await this.writeConnection.query(`PRAGMA temp_store = memory`);\n await this.writeConnection.query(`PRAGMA synchronous = ${synchronous}`);\n await this.writeConnection.query(`PRAGMA cache_size = -${cacheSizeKb}`);\n await this._readConnection.open();\n const platform = Capacitor.getPlatform();\n if (platform == 'android') {\n /**\n * SQLCipher for Android enables dynamic loading of extensions.\n * On iOS we use a static auto extension registration.\n */\n const extensionQuery = \"SELECT load_extension('libpowersync.so', 'sqlite3_powersync_init')\";\n await this.writeConnection.query(extensionQuery);\n await this.readConnection.query(extensionQuery);\n }\n await this.writeConnection.query(\"SELECT powersync_update_hooks('install')\");\n }\n async close() {\n await this.initializedPromise;\n await this.writeConnection.close();\n await this.readConnection.close();\n }\n generateLockContext(db) {\n const _query = async (query, params = []) => {\n var _a;\n const result = await db.query(query, params);\n const arrayResult = (_a = result.values) !== null && _a !== void 0 ? _a : [];\n return {\n rowsAffected: 0,\n rows: {\n _array: arrayResult,\n length: arrayResult.length,\n item: (idx) => arrayResult[idx]\n }\n };\n };\n const _execute = async (query, params = []) => {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n const platform = Capacitor.getPlatform();\n if (db.getConnectionReadOnly()) {\n return _query(query, params);\n }\n if (platform == 'android') {\n // Android: use query for SELECT and executeSet for mutations\n // We cannot use `run` here for both cases.\n if (query.toLowerCase().trim().startsWith('select')) {\n return _query(query, params);\n }\n else {\n const result = await db.executeSet([{ statement: query, values: params }], false);\n return {\n insertId: (_a = result.changes) === null || _a === void 0 ? void 0 : _a.lastId,\n rowsAffected: (_c = (_b = result.changes) === null || _b === void 0 ? void 0 : _b.changes) !== null && _c !== void 0 ? _c : 0,\n rows: {\n _array: [],\n length: 0,\n item: () => null\n }\n };\n }\n }\n // iOS (and other platforms): use run(\"all\")\n const result = await db.run(query, params, false, 'all');\n const resultSet = (_e = (_d = result.changes) === null || _d === void 0 ? void 0 : _d.values) !== null && _e !== void 0 ? _e : [];\n return {\n insertId: (_f = result.changes) === null || _f === void 0 ? void 0 : _f.lastId,\n rowsAffected: (_h = (_g = result.changes) === null || _g === void 0 ? void 0 : _g.changes) !== null && _h !== void 0 ? _h : 0,\n rows: {\n _array: resultSet,\n length: resultSet.length,\n item: (idx) => resultSet[idx]\n }\n };\n };\n const execute = this.options.debugMode\n ? (sql, params) => monitorQuery(sql, () => _execute(sql, params))\n : _execute;\n const executeQuery = this.options.debugMode\n ? (sql, params) => monitorQuery(sql, () => _query(sql, params))\n : _query;\n const getAll = async (query, params) => {\n var _a, _b;\n const result = await executeQuery(query, params);\n return (_b = (_a = result.rows) === null || _a === void 0 ? void 0 : _a._array) !== null && _b !== void 0 ? _b : [];\n };\n const getOptional = async (query, params) => {\n const results = await getAll(query, params);\n return results.length > 0 ? results[0] : null;\n };\n const get = async (query, params) => {\n const result = await getOptional(query, params);\n if (!result) {\n throw new Error(`No results for query: ${query}`);\n }\n return result;\n };\n const executeRaw = async (query, params) => {\n var _a, _b;\n // This is a workaround, we don't support multiple columns of the same name\n const results = await execute(query, params);\n return (_b = (_a = results.rows) === null || _a === void 0 ? void 0 : _a._array.map((row) => Object.values(row))) !== null && _b !== void 0 ? _b : [];\n };\n return {\n getAll,\n getOptional,\n get,\n executeRaw,\n execute\n };\n }\n execute(query, params) {\n return this.writeLock((tx) => tx.execute(query, params));\n }\n executeRaw(query, params) {\n return this.writeLock((tx) => tx.executeRaw(query, params));\n }\n async executeBatch(query, params = []) {\n return this.writeLock(async (tx) => {\n var _a, _b, _c;\n let result = await this.writeConnection.executeSet(params.map((param) => ({\n statement: query,\n values: param\n })));\n return {\n rowsAffected: (_b = (_a = result.changes) === null || _a === void 0 ? void 0 : _a.changes) !== null && _b !== void 0 ? _b : 0,\n insertId: (_c = result.changes) === null || _c === void 0 ? void 0 : _c.lastId\n };\n });\n }\n readLock(fn, options) {\n return mutexRunExclusive(this.readMutex, async () => {\n await this.initializedPromise;\n return await fn(this.generateLockContext(this.readConnection));\n }, options);\n }\n readTransaction(fn, options) {\n return this.readLock(async (ctx) => {\n return this.internalTransaction(ctx, fn);\n });\n }\n writeLock(fn, options) {\n return mutexRunExclusive(this.writeMutex, async () => {\n var _a;\n await this.initializedPromise;\n const result = await fn(this.generateLockContext(this.writeConnection));\n // Fetch table updates\n const updates = await this.writeConnection.query(\"SELECT powersync_update_hooks('get') AS table_name\");\n const jsonUpdates = (_a = updates.values) === null || _a === void 0 ? void 0 : _a[0];\n if (!jsonUpdates || !jsonUpdates.table_name) {\n throw new Error('Could not fetch table updates');\n }\n const notification = {\n rawUpdates: [],\n tables: JSON.parse(jsonUpdates.table_name),\n groupedUpdates: {}\n };\n this.iterateListeners((l) => { var _a; return (_a = l.tablesUpdated) === null || _a === void 0 ? void 0 : _a.call(l, notification); });\n return result;\n }, options);\n }\n writeTransaction(fn, options) {\n return this.writeLock(async (ctx) => {\n return this.internalTransaction(ctx, fn);\n });\n }\n refreshSchema() {\n return this.writeLock(async (writeTx) => {\n return this.readLock(async (readTx) => {\n const updateQuery = `PRAGMA table_info('sqlite_master')`;\n await writeTx.get(updateQuery);\n await readTx.get(updateQuery);\n });\n });\n }\n getAll(sql, parameters) {\n return this.readLock((tx) => tx.getAll(sql, parameters));\n }\n getOptional(sql, parameters) {\n return this.readLock((tx) => tx.getOptional(sql, parameters));\n }\n get(sql, parameters) {\n return this.readLock((tx) => tx.get(sql, parameters));\n }\n async internalTransaction(ctx, fn) {\n let finalized = false;\n const commit = async () => {\n if (finalized) {\n return { rowsAffected: 0 };\n }\n finalized = true;\n return ctx.execute('COMMIT');\n };\n const rollback = async () => {\n if (finalized) {\n return { rowsAffected: 0 };\n }\n finalized = true;\n return ctx.execute('ROLLBACK');\n };\n try {\n await ctx.execute('BEGIN');\n const result = await fn(Object.assign(Object.assign({}, ctx), { commit,\n rollback }));\n await commit();\n return result;\n }\n catch (ex) {\n try {\n await rollback();\n }\n catch (ex2) {\n // In rare cases, a rollback may fail.\n // Safe to ignore.\n }\n throw ex;\n }\n }\n}\n//# sourceMappingURL=CapacitorSQLiteAdapter.js.map","import { AbstractStreamingSyncImplementation, LockType, mutexRunExclusive } from '@powersync/web';\nimport { Mutex } from 'async-mutex';\nconst GLOBAL_MUTEX_STORE = new Map();\n/**\n * Used to identify multiple instances of CapacitorStreamingSyncImplementation\n */\nlet _CAPACITOR_STREAMING_SYNC_SEQUENCE = 0;\nexport class CapacitorStreamingSyncImplementation extends AbstractStreamingSyncImplementation {\n constructor() {\n super(...arguments);\n // A unique ID for tacking this specific instance of CapacitorStreamingSyncImplementation\n this.instanceId = _CAPACITOR_STREAMING_SYNC_SEQUENCE++;\n }\n async dispose() {\n await super.dispose();\n // Clear up any global mutexes which aren't used anymore\n for (const mutexEntry of GLOBAL_MUTEX_STORE.entries()) {\n const [identifier, mutex] = mutexEntry;\n if (!mutex.tracking.has(this.instanceId)) {\n continue;\n }\n mutex.tracking.delete(this.instanceId);\n if (mutex.tracking.size == 0) {\n GLOBAL_MUTEX_STORE.delete(identifier);\n }\n }\n }\n async obtainLock(lockOptions) {\n // If we don't have an identifier for some reason (should not happen), we use a shared Mutex\n const { identifier: baseIdentifier = 'DEFAULT' } = this.options;\n if (!GLOBAL_MUTEX_STORE.has(baseIdentifier)) {\n GLOBAL_MUTEX_STORE.set(baseIdentifier, {\n tracking: new Set([this.instanceId]),\n locks: {\n [LockType.CRUD]: new Mutex(),\n [LockType.SYNC]: new Mutex()\n }\n });\n }\n const mutexRecord = GLOBAL_MUTEX_STORE.get(baseIdentifier);\n mutexRecord.tracking.add(this.instanceId);\n const mutex = mutexRecord.locks[lockOptions.type];\n return mutexRunExclusive(mutex, async () => {\n var _a;\n if ((_a = lockOptions.signal) === null || _a === void 0 ? void 0 : _a.aborted) {\n throw new Error('Aborted');\n }\n return await lockOptions.callback();\n });\n }\n}\n//# sourceMappingURL=CapacitorSyncImplementation.js.map","import { Capacitor } from '@capacitor/core';\nimport { MEMORY_TRIGGER_CLAIM_MANAGER, PowerSyncDatabase as WebPowerSyncDatabase, WebRemote } from '@powersync/web';\nimport { CapacitorSQLiteAdapter } from './adapter/CapacitorSQLiteAdapter.js';\nimport { CapacitorStreamingSyncImplementation } from './sync/CapacitorSyncImplementation.js';\n/**\n * PowerSyncDatabase class for managing database connections and sync implementations.\n * This extends the WebPowerSyncDatabase to provide platform-specific implementations\n * for Capacitor environments (iOS and Android).\n *\n * @experimental\n * @alpha\n */\nexport class PowerSyncDatabase extends WebPowerSyncDatabase {\n get isNativeCapacitorPlatform() {\n const platform = Capacitor.getPlatform();\n return platform == 'ios' || platform == 'android';\n }\n openDBAdapter(options) {\n var _a, _b, _c;\n const platform = Capacitor.getPlatform();\n if (platform == 'ios' || platform == 'android') {\n if (options.database.dbLocation) {\n (_a = options.logger) === null || _a === void 0 ? void 0 : _a.warn(`\n dbLocation is ignored on iOS and Android platforms. \n The database directory can be configured in the Capacitor project.\n See https://github.com/capacitor-community/sqlite?tab=readme-ov-file#installation`);\n }\n (_b = options.logger) === null || _b === void 0 ? void 0 : _b.debug(`Using CapacitorSQLiteAdapter for platform: ${platform}`);\n return new CapacitorSQLiteAdapter(Object.assign({}, options.database));\n }\n else {\n (_c = options.logger) === null || _c === void 0 ? void 0 : _c.debug(`Using default web adapter for web platform`);\n return super.openDBAdapter(options);\n }\n }\n generateTriggerManagerConfig() {\n const config = super.generateTriggerManagerConfig();\n if (this.isNativeCapacitorPlatform) {\n /**\n * We usually only ever have a single tab for capacitor.\n * Avoiding navigator locks allows insecure contexts (during development).\n */\n config.claimManager = MEMORY_TRIGGER_CLAIM_MANAGER;\n }\n return config;\n }\n runExclusive(cb) {\n if (this.isNativeCapacitorPlatform) {\n // Use mutex for mobile platforms.\n // This is mainly for testing purposes since navigator.locks require secure contexts.\n return this.runExclusiveMutex.runExclusive(cb);\n }\n else {\n // Use navigator.locks for web platform\n return super.runExclusive(cb);\n }\n }\n generateSyncStreamImplementation(connector, options) {\n var _a;\n if (this.isNativeCapacitorPlatform) {\n // We don't want to support multi-tab on mobile platforms.\n // We technically can, but it's not a common use case and requires additional work/testing.\n this.logger.debug(`Using Capacitor sync implementation`);\n if ((_a = this.options.flags) === null || _a === void 0 ? void 0 : _a.enableMultiTabs) {\n this.logger.warn(`enableMultiTabs is not supported on Capacitor mobile platforms. Ignoring the flag.`);\n }\n const remote = new WebRemote(connector, this.logger);\n return new CapacitorStreamingSyncImplementation(Object.assign(Object.assign({}, this.options), { retryDelayMs: options.retryDelayMs, crudUploadThrottleMs: options.crudUploadThrottleMs, adapter: this.bucketStorageAdapter, remote, uploadCrud: async () => {\n await this.waitForReady();\n await connector.uploadData(this);\n }, identifier: this.database.name, logger: this.logger, subscriptions: options.subscriptions }));\n }\n else {\n this.logger.debug(`Using default web sync implementation for web platform`);\n return super.generateSyncStreamImplementation(connector, options);\n }\n }\n}\n//# sourceMappingURL=PowerSyncDatabase.js.map","import { WebPlugin } from '@capacitor/core';\nexport class PowerSyncWeb extends WebPlugin {\n async registerCore() {\n throw new Error('This code path is not supported on web.');\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","BaseObserver","Mutex","sqlite","SQLiteConnection","CapacitorSQLite","Capacitor","mutexRunExclusive","AbstractStreamingSyncImplementation","LockType","WebPowerSyncDatabase","MEMORY_TRIGGER_CLAIM_MANAGER","WebRemote","WebPlugin"],"mappings":";;;IACO,MAAM,aAAa,GAAGA,mBAAc,CAAC,WAAW,EAAE;IACzD,IAAI,GAAG,EAAE,MAAM,mDAAkB,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,YAAY,EAAE;IAClE,CAAC,CAAC;;ICHK,MAAM,mBAAmB,GAAG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,CAAC;IACtH,YAAY;IACZ,YAAY,MAAM,MAAM,GAAG,IAAIC,eAAS,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC;IAChE,YAAY,OAAO,IAAI,oCAAoC,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,CAAC,YAAY,EAAE,oBAAoB,EAAE,OAAO,CAAC,oBAAoB,EAAE,OAAO,EAAE,IAAI,CAAC,oBAAoB,EAAE,MAAM,EAAE,UAAU,EAAE,YAAY;IACzQ,oBAAoB,MAAM,IAAI,CAAC,YAAY,EAAE;IAC7C,oBAAoB,MAAM,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC;IACpD,gBAAgB,CAAC,EAAE,UAAU,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC;IAChH,QAAQ;IACR,aAAa;IACb,YAAY,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,sDAAsD,CAAC,CAAC;IACvF,YAAY,OAAO,KAAK,CAAC,gCAAgC,CAAC,SAAS,EAAE,OAAO,CAAC;IAC7E,QAAQ;IACR,IAAI;IACJ;;IC5EO,MAAM,YAAY,SAASC,cAAS,CAAC;IAC5C,IAAI,MAAM,YAAY,GAAG;IACzB,QAAQ,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC;IAClE,IAAI;IACJ;;;;;;;;;;;;;;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powersync/capacitor",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Adds PowerSync Capacitor support for iOS/Android",
5
5
  "publishConfig": {
6
6
  "registry": "https://registry.npmjs.org/",
@@ -57,7 +57,6 @@
57
57
  "@ionic/eslint-config": "^0.4.0",
58
58
  "@ionic/prettier-config": "^4.0.0",
59
59
  "@ionic/swiftlint-config": "^2.0.0",
60
- "@types/async-lock": "^1.4.0",
61
60
  "eslint": "^8.57.0",
62
61
  "prettier": "^3.7.4",
63
62
  "prettier-plugin-java": "^2.6.6",
@@ -68,7 +67,7 @@
68
67
  },
69
68
  "peerDependencies": {
70
69
  "@capacitor-community/sqlite": "^7.0.2",
71
- "@powersync/web": "^1.32.0"
70
+ "@powersync/web": "^1.34.0"
72
71
  },
73
72
  "swiftlint": "@ionic/swiftlint-config",
74
73
  "capacitor": {
@@ -82,7 +81,7 @@
82
81
  }
83
82
  },
84
83
  "dependencies": {
85
- "async-lock": "^1.4.1"
84
+ "async-mutex": "^0.5.0"
86
85
  },
87
86
  "scripts": {
88
87
  "verify": "pnpm verify:ios && pnpm verify:android && pnpm verify:web",
@@ -8,10 +8,11 @@ import {
8
8
  DBAdapterListener,
9
9
  DBLockOptions,
10
10
  LockContext,
11
+ mutexRunExclusive,
11
12
  QueryResult,
12
13
  Transaction
13
14
  } from '@powersync/web';
14
- import Lock from 'async-lock';
15
+ import { Mutex } from 'async-mutex';
15
16
  import { PowerSyncCore } from '../plugin/PowerSyncCore.js';
16
17
  import { messageForErrorCode } from '../plugin/PowerSyncPlugin.js';
17
18
  import { CapacitorSQLiteOpenFactoryOptions, DEFAULT_SQLITE_OPTIONS } from './CapacitorSQLiteOpenFactory.js';
@@ -39,13 +40,15 @@ export class CapacitorSQLiteAdapter extends BaseObserver<DBAdapterListener> impl
39
40
  protected _writeConnection: SQLiteDBConnection | null;
40
41
  protected _readConnection: SQLiteDBConnection | null;
41
42
  protected initializedPromise: Promise<void>;
42
- protected lock: Lock;
43
+ protected writeMutex: Mutex;
44
+ protected readMutex: Mutex;
43
45
 
44
46
  constructor(protected options: CapacitorSQLiteOpenFactoryOptions) {
45
47
  super();
46
48
  this._writeConnection = null;
47
49
  this._readConnection = null;
48
- this.lock = new Lock();
50
+ this.writeMutex = new Mutex();
51
+ this.readMutex = new Mutex();
49
52
  this.initializedPromise = this.init();
50
53
  }
51
54
 
@@ -237,10 +240,14 @@ export class CapacitorSQLiteAdapter extends BaseObserver<DBAdapterListener> impl
237
240
  }
238
241
 
239
242
  readLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions): Promise<T> {
240
- return this.lock.acquire('read_lock', async () => {
241
- await this.initializedPromise;
242
- return await fn(this.generateLockContext(this.readConnection));
243
- });
243
+ return mutexRunExclusive(
244
+ this.readMutex,
245
+ async () => {
246
+ await this.initializedPromise;
247
+ return await fn(this.generateLockContext(this.readConnection));
248
+ },
249
+ options
250
+ );
244
251
  }
245
252
 
246
253
  readTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions): Promise<T> {
@@ -250,24 +257,28 @@ export class CapacitorSQLiteAdapter extends BaseObserver<DBAdapterListener> impl
250
257
  }
251
258
 
252
259
  writeLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions): Promise<T> {
253
- return this.lock.acquire('write_lock', async () => {
254
- await this.initializedPromise;
255
- const result = await fn(this.generateLockContext(this.writeConnection));
256
-
257
- // Fetch table updates
258
- const updates = await this.writeConnection.query("SELECT powersync_update_hooks('get') AS table_name");
259
- const jsonUpdates = updates.values?.[0];
260
- if (!jsonUpdates || !jsonUpdates.table_name) {
261
- throw new Error('Could not fetch table updates');
262
- }
263
- const notification: BatchedUpdateNotification = {
264
- rawUpdates: [],
265
- tables: JSON.parse(jsonUpdates.table_name),
266
- groupedUpdates: {}
267
- };
268
- this.iterateListeners((l) => l.tablesUpdated?.(notification));
269
- return result;
270
- });
260
+ return mutexRunExclusive(
261
+ this.writeMutex,
262
+ async () => {
263
+ await this.initializedPromise;
264
+ const result = await fn(this.generateLockContext(this.writeConnection));
265
+
266
+ // Fetch table updates
267
+ const updates = await this.writeConnection.query("SELECT powersync_update_hooks('get') AS table_name");
268
+ const jsonUpdates = updates.values?.[0];
269
+ if (!jsonUpdates || !jsonUpdates.table_name) {
270
+ throw new Error('Could not fetch table updates');
271
+ }
272
+ const notification: BatchedUpdateNotification = {
273
+ rawUpdates: [],
274
+ tables: JSON.parse(jsonUpdates.table_name),
275
+ groupedUpdates: {}
276
+ };
277
+ this.iterateListeners((l) => l.tablesUpdated?.(notification));
278
+ return result;
279
+ },
280
+ options
281
+ );
271
282
  }
272
283
 
273
284
  writeTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions): Promise<T> {
@@ -1,12 +1,62 @@
1
- import { AbstractStreamingSyncImplementation, LockOptions } from '@powersync/web';
2
- import Lock from 'async-lock';
1
+ import { AbstractStreamingSyncImplementation, LockOptions, LockType, mutexRunExclusive } from '@powersync/web';
2
+ import { Mutex } from 'async-mutex';
3
+
4
+ type MutexMap = {
5
+ /**
6
+ * Used to track the consumers of this Mutex.
7
+ * It should be safe to dispose the Mutex if this is empty.
8
+ */
9
+ tracking: Set<number>;
10
+ locks: {
11
+ [Type in LockType]: Mutex;
12
+ };
13
+ };
14
+
15
+ const GLOBAL_MUTEX_STORE: Map<string, MutexMap> = new Map();
16
+
17
+ /**
18
+ * Used to identify multiple instances of CapacitorStreamingSyncImplementation
19
+ */
20
+ let _CAPACITOR_STREAMING_SYNC_SEQUENCE = 0;
3
21
 
4
22
  export class CapacitorStreamingSyncImplementation extends AbstractStreamingSyncImplementation {
5
- static GLOBAL_LOCK = new Lock();
23
+ // A unique ID for tacking this specific instance of CapacitorStreamingSyncImplementation
24
+ protected instanceId = _CAPACITOR_STREAMING_SYNC_SEQUENCE++;
25
+
26
+ async dispose(): Promise<void> {
27
+ await super.dispose();
28
+
29
+ // Clear up any global mutexes which aren't used anymore
30
+ for (const mutexEntry of GLOBAL_MUTEX_STORE.entries()) {
31
+ const [identifier, mutex] = mutexEntry;
32
+ if (!mutex.tracking.has(this.instanceId)) {
33
+ continue;
34
+ }
35
+ mutex.tracking.delete(this.instanceId);
36
+ if (mutex.tracking.size == 0) {
37
+ GLOBAL_MUTEX_STORE.delete(identifier);
38
+ }
39
+ }
40
+ }
6
41
 
7
42
  async obtainLock<T>(lockOptions: LockOptions<T>): Promise<T> {
8
- const identifier = `streaming-sync-${lockOptions.type}-${this.options.identifier}`;
9
- return CapacitorStreamingSyncImplementation.GLOBAL_LOCK.acquire(identifier, async () => {
43
+ // If we don't have an identifier for some reason (should not happen), we use a shared Mutex
44
+ const { identifier: baseIdentifier = 'DEFAULT' } = this.options;
45
+ if (!GLOBAL_MUTEX_STORE.has(baseIdentifier)) {
46
+ GLOBAL_MUTEX_STORE.set(baseIdentifier, {
47
+ tracking: new Set([this.instanceId]),
48
+ locks: {
49
+ [LockType.CRUD]: new Mutex(),
50
+ [LockType.SYNC]: new Mutex()
51
+ }
52
+ });
53
+ }
54
+
55
+ const mutexRecord = GLOBAL_MUTEX_STORE.get(baseIdentifier)!;
56
+ mutexRecord.tracking.add(this.instanceId);
57
+ const mutex = mutexRecord.locks[lockOptions.type];
58
+
59
+ return mutexRunExclusive(mutex, async () => {
10
60
  if (lockOptions.signal?.aborted) {
11
61
  throw new Error('Aborted');
12
62
  }