@powersync/web 0.0.0-dev-20260630141119 → 0.0.0-dev-20260708103617
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.
- package/bin/powersync.cjs +1 -1
- package/dist/index.umd.js +7821 -0
- package/dist/index.umd.js.map +1 -0
- package/dist/worker/SharedSyncImplementation.umd.js +16139 -0
- package/dist/worker/SharedSyncImplementation.umd.js.map +1 -0
- package/dist/worker/WASQLiteDB.umd.js +17434 -0
- package/dist/worker/WASQLiteDB.umd.js.map +1 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-9af0a7.umd.js +31 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-9af0a7.umd.js.map +1 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-bbf5a9.umd.js +31 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-bbf5a9.umd.js.map +1 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-c26e0f.umd.js +31 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-c26e0f.umd.js.map +1 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +31 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map +1 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-2fb422.umd.js +3562 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-2fb422.umd.js.map +1 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-833585.umd.js +1400 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-833585.umd.js.map +1 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-96fb23.umd.js +2478 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-96fb23.umd.js.map +1 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-c89911.umd.js +1681 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-c89911.umd.js.map +1 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-ec4eb1.umd.js +1820 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-ec4eb1.umd.js.map +1 -0
- package/lib/package.json +91 -0
- package/lib/src/attachments/IndexDBFileSystemAdapter.js.map +1 -0
- package/lib/{db → src/db}/NavigatorTriggerClaimManager.d.ts +1 -1
- package/lib/src/db/NavigatorTriggerClaimManager.js.map +1 -0
- package/lib/src/db/PowerSyncDatabase.d.ts +78 -0
- package/lib/{db → src/db}/PowerSyncDatabase.js +61 -47
- package/lib/src/db/PowerSyncDatabase.js.map +1 -0
- package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.d.ts +23 -0
- package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.js +27 -0
- package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.js.map +1 -0
- package/lib/src/db/adapters/AsyncWebAdapter.d.ts +50 -0
- package/lib/{db → src/db}/adapters/AsyncWebAdapter.js +14 -14
- package/lib/src/db/adapters/AsyncWebAdapter.js.map +1 -0
- package/lib/src/db/adapters/SSRDBAdapter.d.ts +30 -0
- package/lib/src/db/adapters/SSRDBAdapter.js +69 -0
- package/lib/src/db/adapters/SSRDBAdapter.js.map +1 -0
- package/lib/{db → src/db}/adapters/WebDBAdapter.d.ts +1 -1
- package/lib/src/db/adapters/WebDBAdapter.js.map +1 -0
- package/lib/{db → src/db}/adapters/wa-sqlite/ConcurrentConnection.d.ts +4 -3
- package/lib/{db → src/db}/adapters/wa-sqlite/ConcurrentConnection.js +2 -2
- package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js.map +1 -0
- package/lib/{db → src/db}/adapters/wa-sqlite/DatabaseClient.d.ts +4 -4
- package/lib/{db → src/db}/adapters/wa-sqlite/DatabaseClient.js +37 -11
- package/lib/src/db/adapters/wa-sqlite/DatabaseClient.js.map +1 -0
- package/lib/{db → src/db}/adapters/wa-sqlite/DatabaseServer.d.ts +5 -5
- package/lib/{db → src/db}/adapters/wa-sqlite/DatabaseServer.js +7 -11
- package/lib/src/db/adapters/wa-sqlite/DatabaseServer.js.map +1 -0
- package/lib/{db → src/db}/adapters/wa-sqlite/RawSqliteConnection.d.ts +12 -23
- package/lib/{db → src/db}/adapters/wa-sqlite/RawSqliteConnection.js +11 -17
- package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js.map +1 -0
- package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +45 -0
- package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +146 -0
- package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js.map +1 -0
- package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.d.ts +15 -0
- package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.js +22 -0
- package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.js.map +1 -0
- package/lib/src/db/adapters/wa-sqlite/vfs.d.ts +40 -0
- package/lib/src/db/adapters/wa-sqlite/vfs.js +95 -0
- package/lib/src/db/adapters/wa-sqlite/vfs.js.map +1 -0
- package/lib/src/db/adapters/web-sql-flags.d.ts +92 -0
- package/lib/src/db/adapters/web-sql-flags.js +37 -0
- package/lib/src/db/adapters/web-sql-flags.js.map +1 -0
- package/lib/{db → src/db}/sync/SSRWebStreamingSyncImplementation.d.ts +8 -4
- package/lib/{db → src/db}/sync/SSRWebStreamingSyncImplementation.js +11 -4
- package/lib/src/db/sync/SSRWebStreamingSyncImplementation.js.map +1 -0
- package/lib/{db → src/db}/sync/SharedWebStreamingSyncImplementation.d.ts +14 -13
- package/lib/{db → src/db}/sync/SharedWebStreamingSyncImplementation.js +66 -31
- package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js.map +1 -0
- package/lib/src/db/sync/WebRemote.d.ts +7 -0
- package/lib/src/db/sync/WebRemote.js +33 -0
- package/lib/src/db/sync/WebRemote.js.map +1 -0
- package/lib/{db → src/db}/sync/WebStreamingSyncImplementation.d.ts +4 -2
- package/lib/{db → src/db}/sync/WebStreamingSyncImplementation.js +2 -3
- package/lib/src/db/sync/WebStreamingSyncImplementation.js.map +1 -0
- package/lib/src/db/sync/userAgent.js.map +1 -0
- package/lib/{index.d.ts → src/index.d.ts} +3 -1
- package/lib/{index.js → src/index.js} +3 -1
- package/lib/src/index.js.map +1 -0
- package/lib/src/shared/navigator.js.map +1 -0
- package/lib/src/shared/tab_close_signal.js.map +1 -0
- package/lib/src/worker/db/MultiDatabaseServer.d.ts +17 -0
- package/lib/{worker → src/worker}/db/MultiDatabaseServer.js +18 -26
- package/lib/src/worker/db/MultiDatabaseServer.js.map +1 -0
- package/lib/src/worker/db/WASQLiteDB.worker.d.ts +4 -0
- package/lib/src/worker/db/WASQLiteDB.worker.js +31 -0
- package/lib/src/worker/db/WASQLiteDB.worker.js.map +1 -0
- package/lib/src/worker/db/open-worker-database.d.ts +14 -0
- package/lib/src/worker/db/open-worker-database.js +53 -0
- package/lib/src/worker/db/open-worker-database.js.map +1 -0
- package/lib/src/worker/sync/AbstractSharedSyncClientProvider.d.ts +19 -0
- package/lib/src/worker/sync/AbstractSharedSyncClientProvider.js.map +1 -0
- package/lib/src/worker/sync/BroadcastLogger.d.ts +47 -0
- package/lib/src/worker/sync/BroadcastLogger.js +129 -0
- package/lib/src/worker/sync/BroadcastLogger.js.map +1 -0
- package/lib/{worker → src/worker}/sync/SharedSyncImplementation.d.ts +15 -11
- package/lib/{worker → src/worker}/sync/SharedSyncImplementation.js +43 -42
- package/lib/src/worker/sync/SharedSyncImplementation.js.map +1 -0
- package/lib/src/worker/sync/SharedSyncImplementation.worker.js +12 -0
- package/lib/src/worker/sync/SharedSyncImplementation.worker.js.map +1 -0
- package/lib/{worker → src/worker}/sync/WorkerClient.d.ts +3 -3
- package/lib/{worker → src/worker}/sync/WorkerClient.js +2 -2
- package/lib/src/worker/sync/WorkerClient.js.map +1 -0
- package/lib/tsconfig.tsbuildinfo +1 -0
- package/package.json +29 -22
- package/src/db/NavigatorTriggerClaimManager.ts +1 -1
- package/src/db/PowerSyncDatabase.ts +122 -80
- package/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.ts +47 -0
- package/src/db/adapters/AsyncWebAdapter.ts +26 -17
- package/src/db/adapters/SSRDBAdapter.ts +64 -14
- package/src/db/adapters/WebDBAdapter.ts +1 -1
- package/src/db/adapters/wa-sqlite/ConcurrentConnection.ts +5 -4
- package/src/db/adapters/wa-sqlite/DatabaseClient.ts +56 -20
- package/src/db/adapters/wa-sqlite/DatabaseServer.ts +12 -15
- package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +24 -41
- package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +126 -63
- package/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.ts +24 -0
- package/src/db/adapters/wa-sqlite/vfs.ts +67 -54
- package/src/db/adapters/web-sql-flags.ts +141 -0
- package/src/db/sync/SSRWebStreamingSyncImplementation.ts +22 -4
- package/src/db/sync/SharedWebStreamingSyncImplementation.ts +77 -38
- package/src/db/sync/WebRemote.ts +26 -23
- package/src/db/sync/WebStreamingSyncImplementation.ts +5 -4
- package/src/index.ts +3 -1
- package/src/worker/db/MultiDatabaseServer.ts +25 -41
- package/src/worker/db/WASQLiteDB.worker.ts +35 -0
- package/src/worker/db/open-worker-database.ts +62 -0
- package/src/worker/sync/AbstractSharedSyncClientProvider.ts +10 -4
- package/src/worker/sync/BroadcastLogger.ts +103 -35
- package/src/worker/sync/SharedSyncImplementation.ts +63 -62
- package/src/worker/sync/SharedSyncImplementation.worker.ts +14 -0
- package/src/worker/sync/WorkerClient.ts +4 -4
- package/dist/index.react_native_web.js +0 -1879
- package/dist/index.react_native_web.js.map +0 -1
- package/dist/worker/AccessHandlePoolVFS-BPUHfZME.js +0 -2
- package/dist/worker/AccessHandlePoolVFS-BPUHfZME.js.map +0 -1
- package/dist/worker/FacadeVFS-d1ZDvud7.js +0 -2
- package/dist/worker/FacadeVFS-d1ZDvud7.js.map +0 -1
- package/dist/worker/IDBBatchAtomicVFS-DbkDb777.js +0 -2
- package/dist/worker/IDBBatchAtomicVFS-DbkDb777.js.map +0 -1
- package/dist/worker/OPFSCoopSyncVFS-DRKedN0p.js +0 -2
- package/dist/worker/OPFSCoopSyncVFS-DRKedN0p.js.map +0 -1
- package/dist/worker/OPFSWriteAheadVFS-BzodSqNq.js +0 -2
- package/dist/worker/OPFSWriteAheadVFS-BzodSqNq.js.map +0 -1
- package/dist/worker/mc-wa-sqlite-DiBqIVE5.js +0 -2
- package/dist/worker/mc-wa-sqlite-DiBqIVE5.js.map +0 -1
- package/dist/worker/mc-wa-sqlite-async-DUEhO9ef.js +0 -2
- package/dist/worker/mc-wa-sqlite-async-DUEhO9ef.js.map +0 -1
- package/dist/worker/wa-sqlite-BlSx7-_P.js +0 -2
- package/dist/worker/wa-sqlite-BlSx7-_P.js.map +0 -1
- package/dist/worker/wa-sqlite-async-BdR24Ucf.js +0 -2
- package/dist/worker/wa-sqlite-async-BdR24Ucf.js.map +0 -1
- package/dist/worker/websockets-Q8W_lerF.js +0 -9
- package/dist/worker/websockets-Q8W_lerF.js.map +0 -1
- package/dist/worker/worker.js +0 -7
- package/dist/worker/worker.js.map +0 -1
- package/lib/attachments/IndexDBFileSystemAdapter.js.map +0 -1
- package/lib/db/NavigatorTriggerClaimManager.js.map +0 -1
- package/lib/db/PowerSyncDatabase.d.ts +0 -67
- package/lib/db/PowerSyncDatabase.js.map +0 -1
- package/lib/db/adapters/AsyncWebAdapter.d.ts +0 -32
- package/lib/db/adapters/AsyncWebAdapter.js.map +0 -1
- package/lib/db/adapters/SSRDBAdapter.d.ts +0 -17
- package/lib/db/adapters/SSRDBAdapter.js +0 -37
- package/lib/db/adapters/SSRDBAdapter.js.map +0 -1
- package/lib/db/adapters/WebDBAdapter.js.map +0 -1
- package/lib/db/adapters/options.d.ts +0 -87
- package/lib/db/adapters/options.js +0 -6
- package/lib/db/adapters/options.js.map +0 -1
- package/lib/db/adapters/resolveAndValidateOptions.d.ts +0 -5
- package/lib/db/adapters/resolveAndValidateOptions.js +0 -33
- package/lib/db/adapters/resolveAndValidateOptions.js.map +0 -1
- package/lib/db/adapters/wa-sqlite/ConcurrentConnection.js.map +0 -1
- package/lib/db/adapters/wa-sqlite/DatabaseClient.js.map +0 -1
- package/lib/db/adapters/wa-sqlite/DatabaseServer.js.map +0 -1
- package/lib/db/adapters/wa-sqlite/RawSqliteConnection.js.map +0 -1
- package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +0 -18
- package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +0 -131
- package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.js.map +0 -1
- package/lib/db/adapters/wa-sqlite/vfs.d.ts +0 -50
- package/lib/db/adapters/wa-sqlite/vfs.js +0 -77
- package/lib/db/adapters/wa-sqlite/vfs.js.map +0 -1
- package/lib/db/sync/SSRWebStreamingSyncImplementation.js.map +0 -1
- package/lib/db/sync/SharedWebStreamingSyncImplementation.js.map +0 -1
- package/lib/db/sync/WebRemote.d.ts +0 -10
- package/lib/db/sync/WebRemote.js +0 -33
- package/lib/db/sync/WebRemote.js.map +0 -1
- package/lib/db/sync/WebStreamingSyncImplementation.js.map +0 -1
- package/lib/db/sync/userAgent.js.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/shared/navigator.js.map +0 -1
- package/lib/shared/tab_close_signal.js.map +0 -1
- package/lib/worker/SharedWorkerConnectionRequest.d.ts +0 -5
- package/lib/worker/SharedWorkerConnectionRequest.js +0 -2
- package/lib/worker/SharedWorkerConnectionRequest.js.map +0 -1
- package/lib/worker/client.d.ts +0 -15
- package/lib/worker/client.js +0 -77
- package/lib/worker/client.js.map +0 -1
- package/lib/worker/db/MultiDatabaseServer.d.ts +0 -22
- package/lib/worker/db/MultiDatabaseServer.js.map +0 -1
- package/lib/worker/sync/AbstractSharedSyncClientProvider.d.ts +0 -13
- package/lib/worker/sync/AbstractSharedSyncClientProvider.js.map +0 -1
- package/lib/worker/sync/BroadcastLogger.d.ts +0 -27
- package/lib/worker/sync/BroadcastLogger.js +0 -65
- package/lib/worker/sync/BroadcastLogger.js.map +0 -1
- package/lib/worker/sync/SharedSyncImplementation.js.map +0 -1
- package/lib/worker/sync/WorkerClient.js.map +0 -1
- package/lib/worker/worker.js +0 -34
- package/lib/worker/worker.js.map +0 -1
- package/src/db/adapters/options.ts +0 -100
- package/src/db/adapters/resolveAndValidateOptions.ts +0 -40
- package/src/worker/SharedWorkerConnectionRequest.ts +0 -6
- package/src/worker/client.ts +0 -100
- package/src/worker/worker.ts +0 -38
- /package/dist/{worker/assets/mc-wa-sqlite-async-D6idQS2r.wasm → 2075a31bb151adbb9767.wasm} +0 -0
- /package/dist/{worker/assets/wa-sqlite-XZW__iJk.wasm → 3322bc84de986b63c2cd.wasm} +0 -0
- /package/dist/{worker/assets/mc-wa-sqlite-CnHbhWvs.wasm → 8e97452e297be23b5e50.wasm} +0 -0
- /package/dist/{worker/assets/wa-sqlite-async-rHzzC98y.wasm → fbc178b70d530e8ce02b.wasm} +0 -0
- /package/lib/{attachments → src/attachments}/IndexDBFileSystemAdapter.d.ts +0 -0
- /package/lib/{attachments → src/attachments}/IndexDBFileSystemAdapter.js +0 -0
- /package/lib/{db → src/db}/NavigatorTriggerClaimManager.js +0 -0
- /package/lib/{db → src/db}/adapters/WebDBAdapter.js +0 -0
- /package/lib/{db → src/db}/sync/userAgent.d.ts +0 -0
- /package/lib/{db → src/db}/sync/userAgent.js +0 -0
- /package/lib/{shared → src/shared}/navigator.d.ts +0 -0
- /package/lib/{shared → src/shared}/navigator.js +0 -0
- /package/lib/{shared → src/shared}/tab_close_signal.d.ts +0 -0
- /package/lib/{shared → src/shared}/tab_close_signal.js +0 -0
- /package/lib/{worker → src/worker}/sync/AbstractSharedSyncClientProvider.js +0 -0
- /package/lib/{worker/worker.d.ts → src/worker/sync/SharedSyncImplementation.worker.d.ts} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"worker.js","sources":["../../../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs","../../../common/lib/utils/Logger.js","../../../common/lib/db/schema/Column.js","../../../common/lib/attachments/Schema.js","../../../common/lib/attachments/LocalStorageAdapter.js","../../../common/lib/client/sync/bucket/CrudEntry.js","../../../common/lib/client/sync/options.js","../../../common/lib/client/triggers/TriggerManager.js","../../../common/lib/client/watched/WatchedQuery.js","../../../common/lib/utils/BaseObserver.js","../../../common/lib/db/QueryResult.js","../../../common/lib/db/DBAdapter.js","../../lib/db/adapters/wa-sqlite/DatabaseServer.js","../../lib/shared/navigator.js","../../../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js","../../../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js","../../lib/db/adapters/wa-sqlite/vfs.js","../../lib/db/adapters/wa-sqlite/RawSqliteConnection.js","../../../shared-internals/lib/client/sync/bucket/BucketStorageAdapter.js","../../../shared-internals/lib/constants.js","../../../shared-internals/lib/db/crud/SyncProgress.js","../../../shared-internals/lib/db/crud/SyncStatus.js","../../../shared-internals/lib/client/sync/options.js","../../../shared-internals/lib/client/ConnectionManager.js","../../../shared-internals/lib/utils/queue.js","../../../shared-internals/lib/utils/mutex.js","../../../shared-internals/lib/client/sync/bucket/CrudEntry.js","../../../shared-internals/lib/utils/compatibility.js","../../../shared-internals/lib/utils/stream_transform.js","../../../shared-internals/lib/utils/async.js","../../../shared-internals/lib/client/sync/bucket/SqliteBucketStorage.js","../../../shared-internals/lib/utils/AbortOperation.js","../../../shared-internals/lib/version.js","../../../shared-internals/lib/client/sync/stream/AbstractRemote.js","../../../shared-internals/lib/client/sync/stream/core-instruction.js","../../../shared-internals/lib/client/sync/stream/AbstractStreamingSyncImplementation.js","../../../shared-internals/lib/db/ConnectionClosedError.js","../../lib/db/adapters/wa-sqlite/ConcurrentConnection.js","../../lib/worker/db/MultiDatabaseServer.js","../../lib/db/sync/WebRemote.js","../../lib/db/sync/userAgent.js","../../lib/db/sync/WebStreamingSyncImplementation.js","../../lib/worker/sync/BroadcastLogger.js","../../lib/db/adapters/wa-sqlite/DatabaseClient.js","../../lib/worker/sync/SharedSyncImplementation.js","../../lib/shared/tab_close_signal.js","../../lib/worker/sync/WorkerClient.js","../../lib/worker/worker.js"],"sourcesContent":["/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nconst proxyMarker = Symbol(\"Comlink.proxy\");\nconst createEndpoint = Symbol(\"Comlink.endpoint\");\nconst releaseProxy = Symbol(\"Comlink.releaseProxy\");\nconst finalizer = Symbol(\"Comlink.finalizer\");\nconst throwMarker = Symbol(\"Comlink.thrown\");\nconst isObject = (val) => (typeof val === \"object\" && val !== null) || typeof val === \"function\";\n/**\n * Internal transfer handle to handle objects marked to proxy.\n */\nconst proxyTransferHandler = {\n canHandle: (val) => isObject(val) && val[proxyMarker],\n serialize(obj) {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port1);\n return [port2, [port2]];\n },\n deserialize(port) {\n port.start();\n return wrap(port);\n },\n};\n/**\n * Internal transfer handler to handle thrown exceptions.\n */\nconst throwTransferHandler = {\n canHandle: (value) => isObject(value) && throwMarker in value,\n serialize({ value }) {\n let serialized;\n if (value instanceof Error) {\n serialized = {\n isError: true,\n value: {\n message: value.message,\n name: value.name,\n stack: value.stack,\n },\n };\n }\n else {\n serialized = { isError: false, value };\n }\n return [serialized, []];\n },\n deserialize(serialized) {\n if (serialized.isError) {\n throw Object.assign(new Error(serialized.value.message), serialized.value);\n }\n throw serialized.value;\n },\n};\n/**\n * Allows customizing the serialization of certain values.\n */\nconst transferHandlers = new Map([\n [\"proxy\", proxyTransferHandler],\n [\"throw\", throwTransferHandler],\n]);\nfunction isAllowedOrigin(allowedOrigins, origin) {\n for (const allowedOrigin of allowedOrigins) {\n if (origin === allowedOrigin || allowedOrigin === \"*\") {\n return true;\n }\n if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {\n return true;\n }\n }\n return false;\n}\nfunction expose(obj, ep = globalThis, allowedOrigins = [\"*\"]) {\n ep.addEventListener(\"message\", function callback(ev) {\n if (!ev || !ev.data) {\n return;\n }\n if (!isAllowedOrigin(allowedOrigins, ev.origin)) {\n console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);\n return;\n }\n const { id, type, path } = Object.assign({ path: [] }, ev.data);\n const argumentList = (ev.data.argumentList || []).map(fromWireValue);\n let returnValue;\n try {\n const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);\n const rawValue = path.reduce((obj, prop) => obj[prop], obj);\n switch (type) {\n case \"GET\" /* MessageType.GET */:\n {\n returnValue = rawValue;\n }\n break;\n case \"SET\" /* MessageType.SET */:\n {\n parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);\n returnValue = true;\n }\n break;\n case \"APPLY\" /* MessageType.APPLY */:\n {\n returnValue = rawValue.apply(parent, argumentList);\n }\n break;\n case \"CONSTRUCT\" /* MessageType.CONSTRUCT */:\n {\n const value = new rawValue(...argumentList);\n returnValue = proxy(value);\n }\n break;\n case \"ENDPOINT\" /* MessageType.ENDPOINT */:\n {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port2);\n returnValue = transfer(port1, [port1]);\n }\n break;\n case \"RELEASE\" /* MessageType.RELEASE */:\n {\n returnValue = undefined;\n }\n break;\n default:\n return;\n }\n }\n catch (value) {\n returnValue = { value, [throwMarker]: 0 };\n }\n Promise.resolve(returnValue)\n .catch((value) => {\n return { value, [throwMarker]: 0 };\n })\n .then((returnValue) => {\n const [wireValue, transferables] = toWireValue(returnValue);\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n if (type === \"RELEASE\" /* MessageType.RELEASE */) {\n // detach and deactive after sending release response above.\n ep.removeEventListener(\"message\", callback);\n closeEndPoint(ep);\n if (finalizer in obj && typeof obj[finalizer] === \"function\") {\n obj[finalizer]();\n }\n }\n })\n .catch((error) => {\n // Send Serialization Error To Caller\n const [wireValue, transferables] = toWireValue({\n value: new TypeError(\"Unserializable return value\"),\n [throwMarker]: 0,\n });\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n });\n });\n if (ep.start) {\n ep.start();\n }\n}\nfunction isMessagePort(endpoint) {\n return endpoint.constructor.name === \"MessagePort\";\n}\nfunction closeEndPoint(endpoint) {\n if (isMessagePort(endpoint))\n endpoint.close();\n}\nfunction wrap(ep, target) {\n const pendingListeners = new Map();\n ep.addEventListener(\"message\", function handleMessage(ev) {\n const { data } = ev;\n if (!data || !data.id) {\n return;\n }\n const resolver = pendingListeners.get(data.id);\n if (!resolver) {\n return;\n }\n try {\n resolver(data);\n }\n finally {\n pendingListeners.delete(data.id);\n }\n });\n return createProxy(ep, pendingListeners, [], target);\n}\nfunction throwIfProxyReleased(isReleased) {\n if (isReleased) {\n throw new Error(\"Proxy has been released and is not useable\");\n }\n}\nfunction releaseEndpoint(ep) {\n return requestResponseMessage(ep, new Map(), {\n type: \"RELEASE\" /* MessageType.RELEASE */,\n }).then(() => {\n closeEndPoint(ep);\n });\n}\nconst proxyCounter = new WeakMap();\nconst proxyFinalizers = \"FinalizationRegistry\" in globalThis &&\n new FinalizationRegistry((ep) => {\n const newCount = (proxyCounter.get(ep) || 0) - 1;\n proxyCounter.set(ep, newCount);\n if (newCount === 0) {\n releaseEndpoint(ep);\n }\n });\nfunction registerProxy(proxy, ep) {\n const newCount = (proxyCounter.get(ep) || 0) + 1;\n proxyCounter.set(ep, newCount);\n if (proxyFinalizers) {\n proxyFinalizers.register(proxy, ep, proxy);\n }\n}\nfunction unregisterProxy(proxy) {\n if (proxyFinalizers) {\n proxyFinalizers.unregister(proxy);\n }\n}\nfunction createProxy(ep, pendingListeners, path = [], target = function () { }) {\n let isProxyReleased = false;\n const proxy = new Proxy(target, {\n get(_target, prop) {\n throwIfProxyReleased(isProxyReleased);\n if (prop === releaseProxy) {\n return () => {\n unregisterProxy(proxy);\n releaseEndpoint(ep);\n pendingListeners.clear();\n isProxyReleased = true;\n };\n }\n if (prop === \"then\") {\n if (path.length === 0) {\n return { then: () => proxy };\n }\n const r = requestResponseMessage(ep, pendingListeners, {\n type: \"GET\" /* MessageType.GET */,\n path: path.map((p) => p.toString()),\n }).then(fromWireValue);\n return r.then.bind(r);\n }\n return createProxy(ep, pendingListeners, [...path, prop]);\n },\n set(_target, prop, rawValue) {\n throwIfProxyReleased(isProxyReleased);\n // FIXME: ES6 Proxy Handler `set` methods are supposed to return a\n // boolean. To show good will, we return true asynchronously ¯\\_(ツ)_/¯\n const [value, transferables] = toWireValue(rawValue);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"SET\" /* MessageType.SET */,\n path: [...path, prop].map((p) => p.toString()),\n value,\n }, transferables).then(fromWireValue);\n },\n apply(_target, _thisArg, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const last = path[path.length - 1];\n if (last === createEndpoint) {\n return requestResponseMessage(ep, pendingListeners, {\n type: \"ENDPOINT\" /* MessageType.ENDPOINT */,\n }).then(fromWireValue);\n }\n // We just pretend that `bind()` didn’t happen.\n if (last === \"bind\") {\n return createProxy(ep, pendingListeners, path.slice(0, -1));\n }\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"APPLY\" /* MessageType.APPLY */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n construct(_target, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"CONSTRUCT\" /* MessageType.CONSTRUCT */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n });\n registerProxy(proxy, ep);\n return proxy;\n}\nfunction myFlat(arr) {\n return Array.prototype.concat.apply([], arr);\n}\nfunction processArguments(argumentList) {\n const processed = argumentList.map(toWireValue);\n return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];\n}\nconst transferCache = new WeakMap();\nfunction transfer(obj, transfers) {\n transferCache.set(obj, transfers);\n return obj;\n}\nfunction proxy(obj) {\n return Object.assign(obj, { [proxyMarker]: true });\n}\nfunction windowEndpoint(w, context = globalThis, targetOrigin = \"*\") {\n return {\n postMessage: (msg, transferables) => w.postMessage(msg, targetOrigin, transferables),\n addEventListener: context.addEventListener.bind(context),\n removeEventListener: context.removeEventListener.bind(context),\n };\n}\nfunction toWireValue(value) {\n for (const [name, handler] of transferHandlers) {\n if (handler.canHandle(value)) {\n const [serializedValue, transferables] = handler.serialize(value);\n return [\n {\n type: \"HANDLER\" /* WireValueType.HANDLER */,\n name,\n value: serializedValue,\n },\n transferables,\n ];\n }\n }\n return [\n {\n type: \"RAW\" /* WireValueType.RAW */,\n value,\n },\n transferCache.get(value) || [],\n ];\n}\nfunction fromWireValue(value) {\n switch (value.type) {\n case \"HANDLER\" /* WireValueType.HANDLER */:\n return transferHandlers.get(value.name).deserialize(value.value);\n case \"RAW\" /* WireValueType.RAW */:\n return value.value;\n }\n}\nfunction requestResponseMessage(ep, pendingListeners, msg, transfers) {\n return new Promise((resolve) => {\n const id = generateUUID();\n pendingListeners.set(id, resolve);\n if (ep.start) {\n ep.start();\n }\n ep.postMessage(Object.assign({ id }, msg), transfers);\n });\n}\nfunction generateUUID() {\n return new Array(4)\n .fill(0)\n .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))\n .join(\"-\");\n}\n\nexport { createEndpoint, expose, finalizer, proxy, proxyMarker, releaseProxy, transfer, transferHandlers, windowEndpoint, wrap };\n//# sourceMappingURL=comlink.mjs.map\n","/**\n * @public\n */\nexport const LogLevels = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50\n};\n/**\n * A very simple {@link PowerSyncLogger} implementation forwarding messages to `console.log`.\n *\n * @param options - Options to configure a minimum severity of the logger or a prefix to make messages more recognizable.\n * @public\n */\nexport function createConsoleLogger(options) {\n const { prefix = 'PowerSync', minLevel = LogLevels.info } = options ?? {};\n return {\n prefix,\n minLevel,\n log({ level, message, error }) {\n if (level < this.minLevel)\n return;\n let emitter = console.log;\n if (level >= LogLevels.error) {\n emitter = console.error;\n }\n else if (level >= LogLevels.warn) {\n emitter = console.warn;\n }\n else if (level >= LogLevels.info) {\n emitter = console.info;\n }\n const messageWithPrefix = `[${prefix}]: ${message}`;\n if (error) {\n emitter(messageWithPrefix, error);\n }\n else {\n emitter(messageWithPrefix);\n }\n }\n };\n}\n//# sourceMappingURL=Logger.js.map","/**\n * @see https://www.sqlite.org/lang_expr.html#castexpr\n * @public\n */\nexport var ColumnType;\n(function (ColumnType) {\n ColumnType[\"TEXT\"] = \"TEXT\";\n ColumnType[\"INTEGER\"] = \"INTEGER\";\n ColumnType[\"REAL\"] = \"REAL\";\n})(ColumnType || (ColumnType = {}));\nconst text = {\n type: ColumnType.TEXT\n};\nconst integer = {\n type: ColumnType.INTEGER\n};\nconst real = {\n type: ColumnType.REAL\n};\n/**\n * @public\n */\nexport const column = {\n text,\n integer,\n real\n};\n/**\n * @public\n */\nexport class Column {\n options;\n constructor(options) {\n this.options = options;\n }\n get name() {\n return this.options.name;\n }\n get type() {\n return this.options.type;\n }\n toJSON() {\n return {\n name: this.name,\n type: this.type\n };\n }\n}\n//# sourceMappingURL=Column.js.map","import { column } from '../db/schema/Column.js';\nimport { Table } from '../db/schema/Table.js';\n/**\n * The default name of the local table storing attachment data.\n *\n * @alpha\n */\nexport const ATTACHMENT_TABLE = 'attachments';\n/**\n * Maps a database row to an AttachmentRecord.\n *\n * @param row - The database row object\n * @returns The corresponding AttachmentRecord\n *\n * @alpha\n */\nexport function attachmentFromSql(row) {\n return {\n id: row.id,\n filename: row.filename,\n localUri: row.local_uri,\n size: row.size,\n mediaType: row.media_type,\n timestamp: row.timestamp,\n metaData: row.meta_data,\n hasSynced: row.has_synced === 1,\n state: row.state\n };\n}\n/**\n * AttachmentState represents the current synchronization state of an attachment.\n *\n * @alpha\n */\nexport var AttachmentState;\n(function (AttachmentState) {\n AttachmentState[AttachmentState[\"QUEUED_UPLOAD\"] = 0] = \"QUEUED_UPLOAD\";\n AttachmentState[AttachmentState[\"QUEUED_DOWNLOAD\"] = 1] = \"QUEUED_DOWNLOAD\";\n AttachmentState[AttachmentState[\"QUEUED_DELETE\"] = 2] = \"QUEUED_DELETE\";\n AttachmentState[AttachmentState[\"SYNCED\"] = 3] = \"SYNCED\";\n AttachmentState[AttachmentState[\"ARCHIVED\"] = 4] = \"ARCHIVED\"; // Attachment has been orphaned, i.e. the associated record has been deleted\n})(AttachmentState || (AttachmentState = {}));\n/**\n * AttachmentTable defines the schema for the attachment queue table.\n *\n * @alpha\n */\nexport class AttachmentTable extends Table {\n constructor(options) {\n super({\n filename: column.text,\n local_uri: column.text,\n timestamp: column.integer,\n size: column.integer,\n media_type: column.text,\n state: column.integer, // Corresponds to AttachmentState\n has_synced: column.integer,\n meta_data: column.text\n }, {\n ...options,\n viewName: options?.viewName ?? ATTACHMENT_TABLE,\n localOnly: true,\n insertOnly: false\n });\n }\n}\n//# sourceMappingURL=Schema.js.map","/**\n * @alpha\n */\nexport var EncodingType;\n(function (EncodingType) {\n EncodingType[\"UTF8\"] = \"utf8\";\n EncodingType[\"Base64\"] = \"base64\";\n})(EncodingType || (EncodingType = {}));\n//# sourceMappingURL=LocalStorageAdapter.js.map","/**\n * Type of local change.\n *\n * @public\n */\nexport var UpdateType;\n(function (UpdateType) {\n /** Insert or replace existing row. All non-null columns are included in the data. Generated by INSERT statements. */\n UpdateType[\"PUT\"] = \"PUT\";\n /** Update existing row. Contains the id, and value of each changed column. Generated by UPDATE statements. */\n UpdateType[\"PATCH\"] = \"PATCH\";\n /** Delete existing row. Contains the id. Generated by DELETE statements. */\n UpdateType[\"DELETE\"] = \"DELETE\";\n})(UpdateType || (UpdateType = {}));\n//# sourceMappingURL=CrudEntry.js.map","/**\n * @public\n */\nexport var SyncStreamConnectionMethod;\n(function (SyncStreamConnectionMethod) {\n SyncStreamConnectionMethod[\"HTTP\"] = \"http\";\n SyncStreamConnectionMethod[\"WEB_SOCKET\"] = \"web-socket\";\n})(SyncStreamConnectionMethod || (SyncStreamConnectionMethod = {}));\n/**\n * @public\n */\nexport var FetchStrategy;\n(function (FetchStrategy) {\n /**\n * Queues multiple sync events before processing, reducing round-trips.\n * This comes at the cost of more processing overhead, which may cause ACK timeouts on older/weaker devices for big enough datasets.\n */\n FetchStrategy[\"Buffered\"] = \"buffered\";\n /**\n * Processes each sync event immediately before requesting the next.\n * This reduces processing overhead and improves real-time responsiveness.\n */\n FetchStrategy[\"Sequential\"] = \"sequential\";\n})(FetchStrategy || (FetchStrategy = {}));\n//# sourceMappingURL=options.js.map","/**\n * SQLite operations to track changes for with {@link TriggerManager}\n *\n * @experimental @alpha\n */\nexport var DiffTriggerOperation;\n(function (DiffTriggerOperation) {\n DiffTriggerOperation[\"INSERT\"] = \"INSERT\";\n DiffTriggerOperation[\"UPDATE\"] = \"UPDATE\";\n DiffTriggerOperation[\"DELETE\"] = \"DELETE\";\n})(DiffTriggerOperation || (DiffTriggerOperation = {}));\n//# sourceMappingURL=TriggerManager.js.map","/**\n * @public\n */\nexport var WatchedQueryListenerEvent;\n(function (WatchedQueryListenerEvent) {\n WatchedQueryListenerEvent[\"ON_DATA\"] = \"onData\";\n WatchedQueryListenerEvent[\"ON_ERROR\"] = \"onError\";\n WatchedQueryListenerEvent[\"ON_STATE_CHANGE\"] = \"onStateChange\";\n WatchedQueryListenerEvent[\"SETTINGS_WILL_UPDATE\"] = \"settingsWillUpdate\";\n WatchedQueryListenerEvent[\"CLOSED\"] = \"closed\";\n})(WatchedQueryListenerEvent || (WatchedQueryListenerEvent = {}));\n//# sourceMappingURL=WatchedQuery.js.map","/**\n * @public\n */\nexport class BaseObserver {\n listeners = new Set();\n constructor() { }\n dispose() {\n this.listeners.clear();\n }\n /**\n * Register a listener for updates to the PowerSync client.\n */\n registerListener(listener) {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n iterateListeners(cb) {\n for (const listener of this.listeners) {\n cb(listener);\n }\n }\n async iterateAsyncListeners(cb) {\n for (let i of Array.from(this.listeners.values())) {\n await cb(i);\n }\n }\n}\n//# sourceMappingURL=BaseObserver.js.map","function rowToRecord(columnNames, row) {\n const record = {};\n columnNames.forEach((name, idx) => (record[name] = row[idx]));\n return record;\n}\n/**\n * Creates a query result by mapping raw rows to JavaScript.\n *\n * This should not be used with libraries doing this mapping natively, as that is typically more performant.\n *\n * @public\n */\nexport function queryResultFromRaw(raw) {\n const { insertId, rowsAffected, columnNames, rawRows } = raw;\n let array;\n function loadAsArray() {\n if (array)\n return array;\n return (array = rawRows.map((row) => rowToRecord(columnNames, row)));\n }\n function getRow(idx) {\n if (array)\n return array[idx];\n return rowToRecord(columnNames, rawRows[idx]);\n }\n return {\n insertId,\n rowsAffected,\n get array() {\n return loadAsArray();\n },\n rows: {\n length: rawRows.length,\n get _array() {\n return loadAsArray();\n },\n item: getRow\n },\n [Symbol.iterator]() {\n let nextIndex = 0;\n return {\n next: function () {\n if (nextIndex >= rawRows.length) {\n return { done: true, value: undefined };\n }\n const row = getRow(nextIndex);\n nextIndex++;\n return { done: false, value: row };\n }\n };\n }\n };\n}\n/**\n * Creates a query result from rows that have already been mapped to JavaScript.\n *\n * @public\n */\nexport function queryResultFromMapped(base, rows) {\n if (rows == null)\n return queryResultWithoutRows(base);\n return {\n insertId: base.insertId,\n rowsAffected: base.rowsAffected,\n array: rows ?? [],\n rows: {\n length: rows.length,\n _array: rows,\n item(i) {\n return rows[i];\n }\n },\n [Symbol.iterator]() {\n return rows[Symbol.iterator]();\n }\n };\n}\n/**\n * Creates a {@link QueryResult} not containing any rows.\n *\n * @public\n */\nexport function queryResultWithoutRows(result) {\n return {\n ...result,\n array: [],\n [Symbol.iterator]() {\n return {\n next() {\n return { done: true, value: undefined };\n }\n };\n }\n };\n}\n//# sourceMappingURL=QueryResult.js.map","/**\n * Set of generic interfaces to allow PowerSync compatibility with\n * different SQLite DB implementations.\n */\nimport { BaseObserver } from '../utils/BaseObserver.js';\nimport { queryResultFromRaw, queryResultWithoutRows } from './QueryResult.js';\n/**\n * @public\n */\nexport class LockContext {\n async getAll(sql, parameters) {\n const rs = await this.execute(sql, parameters);\n return Array.from(rs);\n }\n async getOptional(sql, parameters) {\n const { array } = await this.execute(sql, parameters);\n if (array.length > 0) {\n return array[0];\n }\n return null;\n }\n async get(sql, parameters) {\n const row = await this.getOptional(sql, parameters);\n if (row == null) {\n throw new Error('Result set is empty');\n }\n return row;\n }\n async execute(query, params) {\n const raw = await this.executeRaw(query, params);\n return queryResultFromRaw(raw);\n }\n async executeBatch(query, params = []) {\n // Emulate executeBatch by running statements individually.\n let lastInsertId;\n let rowsAffected = 0;\n for (const set of params) {\n const result = await this.execute(query, set);\n lastInsertId = result.insertId;\n rowsAffected += result.rowsAffected ?? 0;\n }\n return queryResultWithoutRows({\n rowsAffected,\n insertId: lastInsertId\n });\n }\n}\n/**\n * @public\n */\nexport class DBAdapter extends BaseObserver {\n readTransaction(fn, options) {\n return this.readLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);\n }\n writeTransaction(fn, options) {\n return this.writeLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);\n }\n getAll(sql, parameters) {\n return this.readLock((ctx) => ctx.getAll(sql, parameters));\n }\n getOptional(sql, parameters) {\n return this.readLock((ctx) => ctx.getOptional(sql, parameters));\n }\n get(sql, parameters) {\n return this.readLock((ctx) => ctx.get(sql, parameters));\n }\n execute(query, params) {\n return this.writeLock((ctx) => ctx.execute(query, params));\n }\n executeRaw(query, params) {\n return this.writeLock((ctx) => ctx.executeRaw(query, params));\n }\n executeBatch(query, params) {\n return this.writeTransaction((tx) => tx.executeBatch(query, params));\n }\n}\nclass TransactionImplementation extends LockContext {\n inner;\n finalized = false;\n constructor(inner) {\n super();\n this.inner = inner;\n }\n async commit() {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n await this.inner.execute('COMMIT');\n }\n async rollback() {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n await this.inner.execute('ROLLBACK');\n }\n execute(query, params) {\n return this.inner.execute(query, params);\n }\n executeRaw(query, params) {\n return this.inner.executeRaw(query, params);\n }\n executeBatch(query, params) {\n return this.inner.executeBatch(query, params);\n }\n static async runWith(ctx, fn) {\n let tx = new TransactionImplementation(ctx);\n try {\n await ctx.execute('BEGIN IMMEDIATE');\n const result = await fn(tx);\n await tx.commit();\n return result;\n }\n catch (ex) {\n try {\n await tx.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=DBAdapter.js.map","import { LogLevels } from '@powersync/common';\n/**\n * Access to a WA-sqlite connection that can be shared with multiple clients sending queries over an RPC protocol built\n * with the Comlink package.\n */\nexport class DatabaseServer {\n #options;\n #nextClientId = 0;\n #activeClients = new Set();\n // TODO: Don't use a broadcast channel for connections managed by a shared worker.\n #updateBroadcastChannel;\n #clientTableListeners = new Set();\n constructor(options) {\n this.#options = options;\n const inner = options.inner;\n this.#updateBroadcastChannel = new BroadcastChannel(`${inner.options.filename}-table-updates`);\n this.#updateBroadcastChannel.onmessage = ({ data }) => {\n this.#pushTableUpdateToClients(data);\n };\n }\n #pushTableUpdateToClients(changedTables) {\n for (const listener of this.#clientTableListeners) {\n listener.postMessage(changedTables);\n }\n }\n get #inner() {\n return this.#options.inner;\n }\n get #logger() {\n return this.#options.logger;\n }\n /**\n * Called by clients when they wish to connect to this database.\n *\n * @param lockName A lock that is currently held by the client. When the lock is returned, we know the client is gone\n * and that we need to clean up resources.\n */\n async connect(lockName) {\n let isOpen = true;\n const clientId = this.#nextClientId++;\n this.#activeClients.add(clientId);\n let connectionLeases = new Map();\n let currentTableListener;\n function requireOpen() {\n if (!isOpen) {\n throw new Error('Client has already been closed');\n }\n }\n function requireOpenAndLease(lease) {\n requireOpen();\n const token = connectionLeases.get(lease);\n if (!token) {\n throw new Error('Attempted to use a connection lease that has already been returned.');\n }\n return token;\n }\n const close = async () => {\n if (isOpen) {\n isOpen = false;\n if (currentTableListener) {\n this.#clientTableListeners.delete(currentTableListener);\n }\n // If the client holds a connection lease it hasn't returned, return that now.\n for (const { lease } of connectionLeases.values()) {\n this.#logger.log({ level: LogLevels.debug, message: `Closing connection lease that hasn't been returned.` });\n await lease.returnLease();\n }\n this.#activeClients.delete(clientId);\n if (this.#activeClients.size == 0) {\n await this.forceClose();\n }\n else {\n this.#logger.log({\n level: LogLevels.debug,\n message: 'Keeping underlying connection active since its used by other clients.'\n });\n }\n }\n };\n if (lockName) {\n navigator.locks.request(lockName, {}, () => {\n close();\n });\n }\n return {\n close,\n debugIsAutoCommit: async () => {\n return this.#inner.unsafeUseInner().isAutoCommit();\n },\n requestAccess: async (write, timeoutMs) => {\n requireOpen();\n const lease = await this.#inner.acquireConnection(timeoutMs != null ? AbortSignal.timeout(timeoutMs) : undefined);\n if (!isOpen) {\n // Race between requestAccess and close(), the connection was closed while we tried to acquire a lease.\n await lease.returnLease();\n return requireOpen();\n }\n const token = crypto.randomUUID();\n connectionLeases.set(token, { lease, write });\n return token;\n },\n completeAccess: async (token) => {\n const lease = requireOpenAndLease(token);\n connectionLeases.delete(token);\n try {\n if (lease.write) {\n // Collect update hooks invoked while the client had the write connection.\n const { rawRows } = await lease.lease.use((conn) => conn.execute(`SELECT powersync_update_hooks('get')`));\n if (rawRows.length) {\n const updatedTables = JSON.parse(rawRows[0][0]);\n if (updatedTables.length) {\n this.#updateBroadcastChannel.postMessage(updatedTables);\n this.#pushTableUpdateToClients(updatedTables);\n }\n }\n }\n }\n finally {\n await lease.lease.returnLease();\n }\n },\n execute: async (token, sql, params) => {\n const { lease } = requireOpenAndLease(token);\n return await lease.use((db) => db.execute(sql, params));\n },\n executeBatch: async (token, sql, params) => {\n const { lease } = requireOpenAndLease(token);\n return await lease.use((db) => db.executeBatch(sql, params));\n },\n setUpdateListener: async (listener) => {\n requireOpen();\n if (currentTableListener) {\n this.#clientTableListeners.delete(currentTableListener);\n }\n currentTableListener = listener;\n if (listener) {\n this.#clientTableListeners.add(listener);\n }\n }\n };\n }\n async forceClose() {\n this.#logger.log({ level: LogLevels.debug, message: `Closing connection to ${this.#inner.options}.` });\n const connection = this.#inner;\n this.#options.onClose();\n this.#updateBroadcastChannel.close();\n await connection.close();\n }\n}\n//# sourceMappingURL=DatabaseServer.js.map","export const getNavigatorLocks = () => {\n if ('locks' in navigator && navigator.locks) {\n return navigator.locks;\n }\n throw new Error('Navigator locks are not available in an insecure context. Use a secure context such as HTTPS or http://localhost.');\n};\n//# sourceMappingURL=navigator.js.map","// Primary result codes.\n// https://www.sqlite.org/rescode.html\nexport const SQLITE_OK = 0;\nexport const SQLITE_ERROR = 1;\nexport const SQLITE_INTERNAL = 2;\nexport const SQLITE_PERM = 3;\nexport const SQLITE_ABORT = 4;\nexport const SQLITE_BUSY = 5;\nexport const SQLITE_LOCKED = 6;\nexport const SQLITE_NOMEM = 7;\nexport const SQLITE_READONLY = 8;\nexport const SQLITE_INTERRUPT = 9;\nexport const SQLITE_IOERR = 10;\nexport const SQLITE_CORRUPT = 11;\nexport const SQLITE_NOTFOUND = 12;\nexport const SQLITE_FULL = 13;\nexport const SQLITE_CANTOPEN = 14;\nexport const SQLITE_PROTOCOL = 15;\nexport const SQLITE_EMPTY = 16;\nexport const SQLITE_SCHEMA = 17;\nexport const SQLITE_TOOBIG = 18;\nexport const SQLITE_CONSTRAINT = 19;\nexport const SQLITE_MISMATCH = 20;\nexport const SQLITE_MISUSE = 21;\nexport const SQLITE_NOLFS = 22;\nexport const SQLITE_AUTH = 23;\nexport const SQLITE_FORMAT = 24;\nexport const SQLITE_RANGE = 25;\nexport const SQLITE_NOTADB = 26;\nexport const SQLITE_NOTICE = 27;\nexport const SQLITE_WARNING = 28;\nexport const SQLITE_ROW = 100;\nexport const SQLITE_DONE = 101;\n\n// Extended error codes.\nexport const SQLITE_IOERR_ACCESS = 3338;\nexport const SQLITE_IOERR_CHECKRESERVEDLOCK = 3594;\nexport const SQLITE_IOERR_CLOSE = 4106;\nexport const SQLITE_IOERR_DATA = 8202;\nexport const SQLITE_IOERR_DELETE = 2570;\nexport const SQLITE_IOERR_DELETE_NOENT = 5898;\nexport const SQLITE_IOERR_DIR_FSYNC = 1290;\nexport const SQLITE_IOERR_FSTAT = 1802;\nexport const SQLITE_IOERR_FSYNC = 1034;\nexport const SQLITE_IOERR_GETTEMPPATH = 6410;\nexport const SQLITE_IOERR_LOCK = 3850;\nexport const SQLITE_IOERR_NOMEM = 3082;\nexport const SQLITE_IOERR_READ = 266;\nexport const SQLITE_IOERR_RDLOCK = 2314;\nexport const SQLITE_IOERR_SEEK = 5642;\nexport const SQLITE_IOERR_SHORT_READ = 522;\nexport const SQLITE_IOERR_TRUNCATE = 1546;\nexport const SQLITE_IOERR_UNLOCK = 2058;\nexport const SQLITE_IOERR_VNODE = 6922;\nexport const SQLITE_IOERR_WRITE = 778;\nexport const SQLITE_IOERR_BEGIN_ATOMIC = 7434;\nexport const SQLITE_IOERR_COMMIT_ATOMIC = 7690;\nexport const SQLITE_IOERR_ROLLBACK_ATOMIC = 7946;\n\n// Other extended result codes.\nexport const SQLITE_CONSTRAINT_CHECK = 275;\nexport const SQLITE_CONSTRAINT_COMMITHOOK = 531;\nexport const SQLITE_CONSTRAINT_FOREIGNKEY = 787;\nexport const SQLITE_CONSTRAINT_FUNCTION = 1043;\nexport const SQLITE_CONSTRAINT_NOTNULL = 1299;\nexport const SQLITE_CONSTRAINT_PINNED = 2835;\nexport const SQLITE_CONSTRAINT_PRIMARYKEY = 1555;\nexport const SQLITE_CONSTRAINT_ROWID = 2579;\nexport const SQLITE_CONSTRAINT_TRIGGER = 1811;\nexport const SQLITE_CONSTRAINT_UNIQUE = 2067;\nexport const SQLITE_CONSTRAINT_VTAB = 2323;\n\n// Open flags.\n// https://www.sqlite.org/c3ref/c_open_autoproxy.html\nexport const SQLITE_OPEN_READONLY = 0x00000001;\nexport const SQLITE_OPEN_READWRITE = 0x00000002;\nexport const SQLITE_OPEN_CREATE = 0x00000004;\nexport const SQLITE_OPEN_DELETEONCLOSE = 0x00000008;\nexport const SQLITE_OPEN_EXCLUSIVE = 0x00000010;\nexport const SQLITE_OPEN_AUTOPROXY = 0x00000020;\nexport const SQLITE_OPEN_URI = 0x00000040;\nexport const SQLITE_OPEN_MEMORY = 0x00000080;\nexport const SQLITE_OPEN_MAIN_DB = 0x00000100;\nexport const SQLITE_OPEN_TEMP_DB = 0x00000200;\nexport const SQLITE_OPEN_TRANSIENT_DB = 0x00000400;\nexport const SQLITE_OPEN_MAIN_JOURNAL = 0x00000800;\nexport const SQLITE_OPEN_TEMP_JOURNAL = 0x00001000;\nexport const SQLITE_OPEN_SUBJOURNAL = 0x00002000;\nexport const SQLITE_OPEN_SUPER_JOURNAL = 0x00004000;\nexport const SQLITE_OPEN_NOMUTEX = 0x00008000;\nexport const SQLITE_OPEN_FULLMUTEX = 0x00010000;\nexport const SQLITE_OPEN_SHAREDCACHE = 0x00020000;\nexport const SQLITE_OPEN_PRIVATECACHE = 0x00040000;\nexport const SQLITE_OPEN_WAL = 0x00080000;\nexport const SQLITE_OPEN_NOFOLLOW = 0x01000000;\n\n// Locking levels.\n// https://www.sqlite.org/c3ref/c_lock_exclusive.html\nexport const SQLITE_LOCK_NONE = 0;\nexport const SQLITE_LOCK_SHARED = 1;\nexport const SQLITE_LOCK_RESERVED = 2;\nexport const SQLITE_LOCK_PENDING = 3;\nexport const SQLITE_LOCK_EXCLUSIVE = 4;\n\n// Device characteristics.\n// https://www.sqlite.org/c3ref/c_iocap_atomic.html\nexport const SQLITE_IOCAP_ATOMIC = 0x00000001;\nexport const SQLITE_IOCAP_ATOMIC512 = 0x00000002;\nexport const SQLITE_IOCAP_ATOMIC1K = 0x00000004;\nexport const SQLITE_IOCAP_ATOMIC2K = 0x00000008;\nexport const SQLITE_IOCAP_ATOMIC4K = 0x00000010;\nexport const SQLITE_IOCAP_ATOMIC8K = 0x00000020;\nexport const SQLITE_IOCAP_ATOMIC16K = 0x00000040;\nexport const SQLITE_IOCAP_ATOMIC32K = 0x00000080;\nexport const SQLITE_IOCAP_ATOMIC64K = 0x00000100;\nexport const SQLITE_IOCAP_SAFE_APPEND = 0x00000200;\nexport const SQLITE_IOCAP_SEQUENTIAL = 0x00000400;\nexport const SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN = 0x00000800;\nexport const SQLITE_IOCAP_POWERSAFE_OVERWRITE = 0x00001000;\nexport const SQLITE_IOCAP_IMMUTABLE = 0x00002000;\nexport const SQLITE_IOCAP_BATCH_ATOMIC = 0x00004000;\n\n// xAccess flags.\n// https://www.sqlite.org/c3ref/c_access_exists.html\nexport const SQLITE_ACCESS_EXISTS = 0;\nexport const SQLITE_ACCESS_READWRITE = 1;\nexport const SQLITE_ACCESS_READ = 2;\n\n// File control opcodes\n// https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlbeginatomicwrite\nexport const SQLITE_FCNTL_LOCKSTATE = 1; \nexport const SQLITE_FCNTL_GET_LOCKPROXYFILE = 2; \nexport const SQLITE_FCNTL_SET_LOCKPROXYFILE = 3; \nexport const SQLITE_FCNTL_LAST_ERRNO = 4; \nexport const SQLITE_FCNTL_SIZE_HINT = 5; \nexport const SQLITE_FCNTL_CHUNK_SIZE = 6; \nexport const SQLITE_FCNTL_FILE_POINTER = 7; \nexport const SQLITE_FCNTL_SYNC_OMITTED = 8; \nexport const SQLITE_FCNTL_WIN32_AV_RETRY = 9; \nexport const SQLITE_FCNTL_PERSIST_WAL = 10; \nexport const SQLITE_FCNTL_OVERWRITE = 11; \nexport const SQLITE_FCNTL_VFSNAME = 12; \nexport const SQLITE_FCNTL_POWERSAFE_OVERWRITE = 13; \nexport const SQLITE_FCNTL_PRAGMA = 14; \nexport const SQLITE_FCNTL_BUSYHANDLER = 15; \nexport const SQLITE_FCNTL_TEMPFILENAME = 16; \nexport const SQLITE_FCNTL_MMAP_SIZE = 18; \nexport const SQLITE_FCNTL_TRACE = 19; \nexport const SQLITE_FCNTL_HAS_MOVED = 20; \nexport const SQLITE_FCNTL_SYNC = 21; \nexport const SQLITE_FCNTL_COMMIT_PHASETWO = 22; \nexport const SQLITE_FCNTL_WIN32_SET_HANDLE = 23; \nexport const SQLITE_FCNTL_WAL_BLOCK = 24; \nexport const SQLITE_FCNTL_ZIPVFS = 25; \nexport const SQLITE_FCNTL_RBU = 26; \nexport const SQLITE_FCNTL_VFS_POINTER = 27; \nexport const SQLITE_FCNTL_JOURNAL_POINTER = 28; \nexport const SQLITE_FCNTL_WIN32_GET_HANDLE = 29; \nexport const SQLITE_FCNTL_PDB = 30; \nexport const SQLITE_FCNTL_BEGIN_ATOMIC_WRITE = 31; \nexport const SQLITE_FCNTL_COMMIT_ATOMIC_WRITE = 32; \nexport const SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE = 33; \nexport const SQLITE_FCNTL_LOCK_TIMEOUT = 34; \nexport const SQLITE_FCNTL_DATA_VERSION = 35; \nexport const SQLITE_FCNTL_SIZE_LIMIT = 36; \nexport const SQLITE_FCNTL_CKPT_DONE = 37; \nexport const SQLITE_FCNTL_RESERVE_BYTES = 38; \nexport const SQLITE_FCNTL_CKPT_START = 39;\n\n// Fundamental datatypes.\n// https://www.sqlite.org/c3ref/c_blob.html\nexport const SQLITE_INTEGER = 1;\nexport const SQLITE_FLOAT = 2;\nexport const SQLITE_TEXT = 3;\nexport const SQLITE_BLOB = 4;\nexport const SQLITE_NULL = 5;\n\n// Special destructor behavior.\n// https://www.sqlite.org/c3ref/c_static.html\nexport const SQLITE_STATIC = 0;\nexport const SQLITE_TRANSIENT = -1;\n\n// Text encodings.\n// https://sqlite.org/c3ref/c_any.html\nexport const SQLITE_UTF8 = 1; /* IMP: R-37514-35566 */\nexport const SQLITE_UTF16LE = 2; /* IMP: R-03371-37637 */\nexport const SQLITE_UTF16BE = 3; /* IMP: R-51971-34154 */\nexport const SQLITE_UTF16 = 4; /* Use native byte order */\n\n// Module constraint ops.\nexport const SQLITE_INDEX_CONSTRAINT_EQ = 2;\nexport const SQLITE_INDEX_CONSTRAINT_GT = 4;\nexport const SQLITE_INDEX_CONSTRAINT_LE = 8;\nexport const SQLITE_INDEX_CONSTRAINT_LT = 16;\nexport const SQLITE_INDEX_CONSTRAINT_GE = 32;\nexport const SQLITE_INDEX_CONSTRAINT_MATCH = 64;\nexport const SQLITE_INDEX_CONSTRAINT_LIKE = 65;\nexport const SQLITE_INDEX_CONSTRAINT_GLOB = 66;\nexport const SQLITE_INDEX_CONSTRAINT_REGEXP = 67;\nexport const SQLITE_INDEX_CONSTRAINT_NE = 68;\nexport const SQLITE_INDEX_CONSTRAINT_ISNOT = 69;\nexport const SQLITE_INDEX_CONSTRAINT_ISNOTNULL = 70;\nexport const SQLITE_INDEX_CONSTRAINT_ISNULL = 71;\nexport const SQLITE_INDEX_CONSTRAINT_IS = 72;\nexport const SQLITE_INDEX_CONSTRAINT_FUNCTION = 150;\nexport const SQLITE_INDEX_SCAN_UNIQUE = 1; /* Scan visits at most = 1 row */\n\n// Function flags\nexport const SQLITE_DETERMINISTIC = 0x000000800;\nexport const SQLITE_DIRECTONLY = 0x000080000;\nexport const SQLITE_SUBTYPE = 0x000100000;\nexport const SQLITE_INNOCUOUS = 0x000200000;\n\n// Sync flags\nexport const SQLITE_SYNC_NORMAL = 0x00002;\nexport const SQLITE_SYNC_FULL = 0x00003;\nexport const SQLITE_SYNC_DATAONLY = 0x00010;\n\n// Authorizer action codes\nexport const SQLITE_CREATE_INDEX = 1;\nexport const SQLITE_CREATE_TABLE = 2;\nexport const SQLITE_CREATE_TEMP_INDEX = 3;\nexport const SQLITE_CREATE_TEMP_TABLE = 4;\nexport const SQLITE_CREATE_TEMP_TRIGGER = 5;\nexport const SQLITE_CREATE_TEMP_VIEW = 6;\nexport const SQLITE_CREATE_TRIGGER = 7;\nexport const SQLITE_CREATE_VIEW = 8;\nexport const SQLITE_DELETE = 9;\nexport const SQLITE_DROP_INDEX = 10;\nexport const SQLITE_DROP_TABLE = 11;\nexport const SQLITE_DROP_TEMP_INDEX = 12;\nexport const SQLITE_DROP_TEMP_TABLE = 13;\nexport const SQLITE_DROP_TEMP_TRIGGER = 14;\nexport const SQLITE_DROP_TEMP_VIEW = 15;\nexport const SQLITE_DROP_TRIGGER = 16;\nexport const SQLITE_DROP_VIEW = 17;\nexport const SQLITE_INSERT = 18;\nexport const SQLITE_PRAGMA = 19;\nexport const SQLITE_READ = 20;\nexport const SQLITE_SELECT = 21;\nexport const SQLITE_TRANSACTION = 22;\nexport const SQLITE_UPDATE = 23;\nexport const SQLITE_ATTACH = 24;\nexport const SQLITE_DETACH = 25;\nexport const SQLITE_ALTER_TABLE = 26;\nexport const SQLITE_REINDEX = 27;\nexport const SQLITE_ANALYZE = 28;\nexport const SQLITE_CREATE_VTABLE = 29;\nexport const SQLITE_DROP_VTABLE = 30;\nexport const SQLITE_FUNCTION = 31;\nexport const SQLITE_SAVEPOINT = 32;\nexport const SQLITE_COPY = 0;\nexport const SQLITE_RECURSIVE = 33;\n\n// Authorizer return codes\nexport const SQLITE_DENY = 1;\nexport const SQLITE_IGNORE = 2;\n\n// Limit categories\nexport const SQLITE_LIMIT_LENGTH = 0;\nexport const SQLITE_LIMIT_SQL_LENGTH = 1;\nexport const SQLITE_LIMIT_COLUMN = 2;\nexport const SQLITE_LIMIT_EXPR_DEPTH = 3;\nexport const SQLITE_LIMIT_COMPOUND_SELECT = 4;\nexport const SQLITE_LIMIT_VDBE_OP = 5;\nexport const SQLITE_LIMIT_FUNCTION_ARG = 6;\nexport const SQLITE_LIMIT_ATTACHED = 7;\nexport const SQLITE_LIMIT_LIKE_PATTERN_LENGTH = 8;\nexport const SQLITE_LIMIT_VARIABLE_NUMBER = 9;\nexport const SQLITE_LIMIT_TRIGGER_DEPTH = 10;\nexport const SQLITE_LIMIT_WORKER_THREADS = 11;\n\nexport const SQLITE_PREPARE_PERSISTENT = 0x01;\nexport const SQLITE_PREPARE_NORMALIZED = 0x02;\nexport const SQLITE_PREPARE_NO_VTAB = 0x04;","// Copyright 2021 Roy T. Hashimoto. All Rights Reserved.\n\nimport * as SQLite from './sqlite-constants.js';\nexport * from './sqlite-constants.js';\n\n/**\n * Need to have a serializer for bigint\n * https://github.com/GoogleChromeLabs/jsbi/issues/30\n */\nif (typeof BigInt.prototype['toJSON'] == 'undefined') {\n BigInt.prototype['toJSON'] = function() {\n return this.toString();\n };\n}\n\nconst MAX_INT64 = 0x7fffffffffffffffn;\nconst MIN_INT64 = -0x8000000000000000n;\n\nconst AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;\n\nexport class SQLiteError extends Error {\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\n\nconst async = true;\n\n\n/**\n * Builds a Javascript API from the Emscripten module. This API is still\n * low-level and closely corresponds to the C API exported by the module,\n * but differs in some specifics like throwing exceptions on errors.\n * @param {*} Module SQLite Emscripten module\n * @returns {SQLiteAPI}\n */\nexport function Factory(Module) {\n /** @type {SQLiteAPI} */ const sqlite3 = {};\n\n Module.retryOps = [];\n Module.pendingOps = [];\n const sqliteFreeAddress = Module._getSqliteFree();\n\n // Allocate some space for 32-bit returned values.\n const tmp = Module._malloc(8);\n const tmpPtr = [tmp, tmp + 4];\n\n const textEncoder = new TextEncoder();\n // Convert a JS string to a C string. sqlite3_malloc is used to allocate\n // memory (use sqlite3_free to deallocate).\n function createUTF8(s) {\n if (typeof s !== 'string') return 0;\n const utf8 = textEncoder.encode(s);\n const zts = Module._sqlite3_malloc(utf8.byteLength + 1);\n Module.HEAPU8.set(utf8, zts);\n Module.HEAPU8[zts + utf8.byteLength] = 0;\n return zts;\n }\n\n /**\n * Concatenate 32-bit numbers into a 64-bit (signed) BigInt.\n * @param {number} lo32\n * @param {number} hi32\n * @returns {bigint}\n */\n function cvt32x2ToBigInt(lo32, hi32) {\n return (BigInt(hi32) << 32n) | (BigInt(lo32) & 0xffffffffn);\n }\n\n // /**\n // * Setup table change update callback\n // */\n // var onTableChangedFunctionPointer = Module.addFunction(onTableUpdate);\n // var passFnPointer = Module.cwrap('passFnPointer', 'undefined', ['number']);\n // passFnPointer(onTableChangedFunctionPointer);\n /**\n * Concatenate 32-bit numbers and return as number or BigInt, depending\n * on the value.\n * @param {number} lo32\n * @param {number} hi32\n * @returns {number|bigint}\n */\n const cvt32x2AsSafe = (function() {\n const hiMax = BigInt(Number.MAX_SAFE_INTEGER) >> 32n;\n const hiMin = BigInt(Number.MIN_SAFE_INTEGER) >> 32n;\n\n return function(lo32, hi32) {\n if (hi32 > hiMax || hi32 < hiMin) {\n // Can't be expressed as a Number so use BigInt.\n return cvt32x2ToBigInt(lo32, hi32);\n } else {\n // Combine the upper and lower 32-bit numbers. The complication is\n // that lo32 is a signed integer which makes manipulating its bits\n // a little tricky - the sign bit gets handled separately.\n return hi32 * 0x100000000 + (lo32 & 0x7fffffff) - (lo32 & 0x80000000);\n }\n };\n })();\n\n const databases = new Set();\n function verifyDatabase(db) {\n if (!databases.has(db)) {\n throw new SQLiteError('not a database', SQLite.SQLITE_MISUSE);\n }\n }\n\n const mapStmtToDB = new Map();\n function verifyStatement(stmt) {\n if (!mapStmtToDB.has(stmt)) {\n throw new SQLiteError('not a statement', SQLite.SQLITE_MISUSE);\n }\n }\n\n sqlite3.bind_collection = function(stmt, bindings) {\n verifyStatement(stmt);\n const isArray = Array.isArray(bindings);\n const nBindings = sqlite3.bind_parameter_count(stmt);\n for (let i = 1; i <= nBindings; ++i) {\n const key = isArray ? i - 1 : sqlite3.bind_parameter_name(stmt, i);\n const value = bindings[key];\n if (value !== undefined) {\n sqlite3.bind(stmt, i, value);\n }\n }\n return SQLite.SQLITE_OK;\n };\n\n sqlite3.bind = function(stmt, i, value) {\n verifyStatement(stmt);\n switch (typeof value) {\n case 'number':\n if (value === (value | 0)) {\n return sqlite3.bind_int(stmt, i, value);\n } else {\n return sqlite3.bind_double(stmt, i, value);\n }\n case 'string':\n return sqlite3.bind_text(stmt, i, value);\n case \"boolean\":\n return sqlite3.bind_int(stmt, i, value ? 1 : 0);\n default:\n if (value instanceof Uint8Array || Array.isArray(value)) {\n return sqlite3.bind_blob(stmt, i, value);\n } else if (value === null) {\n return sqlite3.bind_null(stmt, i);\n } else if (typeof value === 'bigint') {\n return sqlite3.bind_int64(stmt, i, value);\n } else if (value === undefined) {\n // Existing binding (or NULL) will be used.\n return SQLite.SQLITE_NOTICE;\n } else {\n console.warn('unknown binding converted to null', value);\n return sqlite3.bind_null(stmt, i);\n }\n }\n };\n\n sqlite3.bind_blob = (function() {\n const fname = 'sqlite3_bind_blob';\n const f = Module.cwrap(fname, ...decl('nnnnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n // @ts-ignore\n const byteLength = value.byteLength ?? value.length;\n const ptr = Module._sqlite3_malloc(byteLength);\n Module.HEAPU8.subarray(ptr).set(value);\n const result = f(stmt, i, ptr, byteLength, sqliteFreeAddress);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_parameter_count = (function() {\n const fname = 'sqlite3_bind_parameter_count';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return result;\n };\n })();\n\n sqlite3.bind_double = (function() {\n const fname = 'sqlite3_bind_double';\n const f = Module.cwrap(fname, ...decl('nnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n const result = f(stmt, i, value);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_int = (function() {\n const fname = 'sqlite3_bind_int';\n const f = Module.cwrap(fname, ...decl('nnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n if (value > 0x7fffffff || value < -0x80000000) return SQLite.SQLITE_RANGE;\n\n const result = f(stmt, i, value);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_int64 = (function() {\n const fname = 'sqlite3_bind_int64';\n const f = Module.cwrap(fname, ...decl('nnnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n if (value > MAX_INT64 || value < MIN_INT64) return SQLite.SQLITE_RANGE;\n\n const lo32 = value & 0xffffffffn;\n const hi32 = value >> 32n;\n const result = f(stmt, i, Number(lo32), Number(hi32));\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_null = (function() {\n const fname = 'sqlite3_bind_null';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, i) {\n verifyStatement(stmt);\n const result = f(stmt, i);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_parameter_name = (function() {\n const fname = 'sqlite3_bind_parameter_name';\n const f = Module.cwrap(fname, ...decl('n:s'));\n return function(stmt, i) {\n verifyStatement(stmt);\n const result = f(stmt, i);\n return result;\n };\n })();\n\n sqlite3.bind_text = (function() {\n const fname = 'sqlite3_bind_text';\n const f = Module.cwrap(fname, ...decl('nnnnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n const ptr = createUTF8(value);\n const result = f(stmt, i, ptr, -1, sqliteFreeAddress);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.changes = (function() {\n const fname = 'sqlite3_changes';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(db) {\n verifyDatabase(db);\n const result = f(db);\n return result;\n };\n })();\n\n sqlite3.clear_bindings = (function() {\n const fname = 'sqlite3_clear_bindings';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.last_insert_id = (function() {\n const fname = 'sqlite3_last_insert_rowid';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(db) {\n verifyDatabase(db);\n const result = f(db);\n // trace(fname, result);\n return result;\n };\n })();\n \n sqlite3.close = (function() {\n const fname = 'sqlite3_close';\n const f = Module.cwrap(fname, ...decl('n:n'), { async });\n return async function(db) {\n verifyDatabase(db);\n const result = await f(db);\n databases.delete(db);\n return check(fname, result, db);\n };\n })();\n\n sqlite3.column = function(stmt, iCol) {\n verifyStatement(stmt);\n const type = sqlite3.column_type(stmt, iCol);\n switch (type) {\n case SQLite.SQLITE_BLOB:\n return sqlite3.column_blob(stmt, iCol);\n case SQLite.SQLITE_FLOAT:\n return sqlite3.column_double(stmt, iCol);\n case SQLite.SQLITE_INTEGER:\n const lo32 = sqlite3.column_int(stmt, iCol);\n const hi32 = Module.getTempRet0();\n return cvt32x2AsSafe(lo32, hi32);\n case SQLite.SQLITE_NULL:\n return null;\n case SQLite.SQLITE_TEXT:\n return sqlite3.column_text(stmt, iCol);\n default:\n throw new SQLiteError('unknown type', type);\n }\n };\n\n sqlite3.column_blob = (function() {\n const fname = 'sqlite3_column_blob';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const nBytes = sqlite3.column_bytes(stmt, iCol);\n const address = f(stmt, iCol);\n const result = Module.HEAPU8.subarray(address, address + nBytes);\n return result;\n };\n })();\n\n sqlite3.column_bytes = (function() {\n const fname = 'sqlite3_column_bytes';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_count = (function() {\n const fname = 'sqlite3_column_count';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return result;\n };\n })();\n\n sqlite3.column_double = (function() {\n const fname = 'sqlite3_column_double';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_int = (function() {\n // Retrieve int64 but use only the lower 32 bits. The upper 32-bits are\n // accessible with Module.getTempRet0().\n const fname = 'sqlite3_column_int64';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_int64 = (function() {\n const fname = 'sqlite3_column_int64';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const lo32 = f(stmt, iCol);\n const hi32 = Module.getTempRet0();\n const result = cvt32x2ToBigInt(lo32, hi32);\n return result;\n };\n })();\n\n sqlite3.column_name = (function() {\n const fname = 'sqlite3_column_name';\n const f = Module.cwrap(fname, ...decl('nn:s'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_names = function(stmt) {\n const columns = [];\n const nColumns = sqlite3.column_count(stmt);\n for (let i = 0; i < nColumns; ++i) {\n columns.push(sqlite3.column_name(stmt, i));\n }\n return columns;\n };\n\n sqlite3.column_text = (function() {\n const fname = 'sqlite3_column_text';\n const f = Module.cwrap(fname, ...decl('nn:s'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_type = (function() {\n const fname = 'sqlite3_column_type';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.create_function = function(db, zFunctionName, nArg, eTextRep, pApp, xFunc, xStep, xFinal) {\n verifyDatabase(db);\n \n // Convert SQLite callback arguments to JavaScript-friendly arguments.\n function adapt(f) {\n return f instanceof AsyncFunction ?\n (async (ctx, n, values) => f(ctx, Module.HEAP32.subarray(values / 4, values / 4 + n))) :\n ((ctx, n, values) => f(ctx, Module.HEAP32.subarray(values / 4, values / 4 + n)));\n }\n\n const result = Module.create_function(\n db,\n zFunctionName,\n nArg,\n eTextRep,\n pApp,\n xFunc && adapt(xFunc),\n xStep && adapt(xStep),\n xFinal);\n return check('sqlite3_create_function', result, db);\n };\n\n sqlite3.data_count = (function() {\n const fname = 'sqlite3_data_count';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return result;\n };\n })();\n\n sqlite3.exec = async function(db, sql, callback) {\n for await (const stmt of sqlite3.statements(db, sql)) {\n let columns;\n while ((await sqlite3.step(stmt)) === SQLite.SQLITE_ROW) {\n if (callback) {\n columns = columns ?? sqlite3.column_names(stmt);\n const row = sqlite3.row(stmt);\n await callback(row, columns);\n }\n }\n }\n return SQLite.SQLITE_OK;\n };\n\n sqlite3.finalize = (function() {\n const fname = 'sqlite3_finalize';\n const f = Module.cwrap(fname, ...decl('n:n'), { async });\n return async function(stmt) {\n const result = await f(stmt);\n mapStmtToDB.delete(stmt)\n\n // Don't throw on error here. Typically the error has already been\n // thrown and finalize() is part of the cleanup.\n return result;\n };\n })();\n\n sqlite3.get_autocommit = (function() {\n const fname = 'sqlite3_get_autocommit';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(db) {\n const result = f(db);\n return result;\n };\n })();\n\n sqlite3.libversion = (function() {\n const fname = 'sqlite3_libversion';\n const f = Module.cwrap(fname, ...decl(':s'));\n return function() {\n const result = f();\n return result;\n };\n })();\n\n sqlite3.libversion_number = (function() {\n const fname = 'sqlite3_libversion_number';\n const f = Module.cwrap(fname, ...decl(':n'));\n return function() {\n const result = f();\n return result;\n };\n })();\n\n sqlite3.limit = (function() {\n const fname = 'sqlite3_limit';\n const f = Module.cwrap(fname, ...decl('nnn:n'));\n return function(db, id, newVal) {\n const result = f(db, id, newVal);\n return result;\n };\n })();\n\n sqlite3.open_v2 = (function() {\n const fname = 'sqlite3_open_v2';\n const f = Module.cwrap(fname, ...decl('snnn:n'), { async });\n return async function(zFilename, flags, zVfs) {\n flags = flags || SQLite.SQLITE_OPEN_CREATE | SQLite.SQLITE_OPEN_READWRITE;\n zVfs = createUTF8(zVfs);\n try {\n // Allow retry operations.\n const rc = await retry(() => f(zFilename, tmpPtr[0], flags, zVfs));\n\n const db = Module.getValue(tmpPtr[0], '*');\n databases.add(db);\n\n Module.ccall('RegisterExtensionFunctions', 'number', ['number'], [db]);\n check(fname, rc);\n return db;\n } finally {\n Module._sqlite3_free(zVfs);\n }\n };\n })();\n\n sqlite3.progress_handler = function(db, nProgressOps, handler, userData) {\n verifyDatabase(db);\n Module.progress_handler(db, nProgressOps, handler, userData);\n };;\n\n sqlite3.reset = (function() {\n const fname = 'sqlite3_reset';\n const f = Module.cwrap(fname, ...decl('n:n'), { async });\n return async function(stmt) {\n verifyStatement(stmt);\n const result = await f(stmt);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.result = function(context, value) {\n switch (typeof value) {\n case 'number':\n if (value === (value | 0)) {\n sqlite3.result_int(context, value);\n } else {\n sqlite3.result_double(context, value);\n }\n break;\n case 'string':\n sqlite3.result_text(context, value);\n break;\n default:\n if (value instanceof Uint8Array || Array.isArray(value)) {\n sqlite3.result_blob(context, value);\n } else if (value === null) {\n sqlite3.result_null(context);\n } else if (typeof value === 'bigint') {\n return sqlite3.result_int64(context, value);\n } else {\n console.warn('unknown result converted to null', value);\n sqlite3.result_null(context);\n }\n break;\n }\n };\n\n sqlite3.result_blob = (function() {\n const fname = 'sqlite3_result_blob';\n const f = Module.cwrap(fname, ...decl('nnnn:n'));\n return function(context, value) {\n // @ts-ignore\n const byteLength = value.byteLength ?? value.length;\n const ptr = Module._sqlite3_malloc(byteLength);\n Module.HEAPU8.subarray(ptr).set(value);\n f(context, ptr, byteLength, sqliteFreeAddress); // void return\n };\n })();\n\n sqlite3.result_double = (function() {\n const fname = 'sqlite3_result_double';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(context, value) {\n f(context, value); // void return\n };\n })();\n\n sqlite3.result_int = (function() {\n const fname = 'sqlite3_result_int';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(context, value) {\n f(context, value); // void return\n };\n })();\n\n sqlite3.result_int64 = (function() {\n const fname = 'sqlite3_result_int64';\n const f = Module.cwrap(fname, ...decl('nnn:n'));\n return function(context, value) {\n if (value > MAX_INT64 || value < MIN_INT64) return SQLite.SQLITE_RANGE;\n\n const lo32 = value & 0xffffffffn;\n const hi32 = value >> 32n;\n f(context, Number(lo32), Number(hi32)); // void return\n };\n })();\n\n sqlite3.result_null = (function() {\n const fname = 'sqlite3_result_null';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(context) {\n f(context); // void return\n };\n })();\n\n sqlite3.result_text = (function() {\n const fname = 'sqlite3_result_text';\n const f = Module.cwrap(fname, ...decl('nnnn:n'));\n return function(context, value) {\n const ptr = createUTF8(value);\n f(context, ptr, -1, sqliteFreeAddress); // void return\n };\n })();\n\n sqlite3.row = function(stmt) {\n const row = [];\n const nColumns = sqlite3.data_count(stmt);\n for (let i = 0; i < nColumns; ++i) {\n const value = sqlite3.column(stmt, i);\n\n // Copy blob if aliasing volatile WebAssembly memory. This avoids an\n // unnecessary copy if users monkey patch column_blob to copy.\n // @ts-ignore\n row.push(value?.buffer === Module.HEAPU8.buffer ? value.slice() : value);\n }\n return row;\n };\n\n sqlite3.set_authorizer = function(db, xAuth, pApp) {\n verifyDatabase(db);\n\n // Convert SQLite callback arguments to JavaScript-friendly arguments.\n function cvtArgs(_, iAction, p3, p4, p5, p6) {\n return [\n _,\n iAction,\n Module.UTF8ToString(p3),\n Module.UTF8ToString(p4),\n Module.UTF8ToString(p5),\n Module.UTF8ToString(p6)\n ];\n };\n function adapt(f) {\n return f instanceof AsyncFunction ?\n (async (_, iAction, p3, p4, p5, p6) => f(...cvtArgs(_, iAction, p3, p4, p5, p6))) :\n ((_, iAction, p3, p4, p5, p6) => f(...cvtArgs(_, iAction, p3, p4, p5, p6)));\n }\n\n const result = Module.set_authorizer(db, adapt(xAuth), pApp);\n return check('sqlite3_set_authorizer', result, db);\n };\n\n sqlite3.sql = (function() {\n const fname = 'sqlite3_sql';\n const f = Module.cwrap(fname, ...decl('n:s'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return result;\n };\n })();\n\n sqlite3.statements = function(db, sql, options = {}) {\n const prepare = Module.cwrap(\n 'sqlite3_prepare_v3',\n 'number',\n ['number', 'number', 'number', 'number', 'number', 'number'],\n { async: true });\n\n return (async function*() {\n const onFinally = [];\n try {\n // Encode SQL string to UTF-8.\n const utf8 = textEncoder.encode(sql);\n\n // Copy encoded string to WebAssembly memory. The SQLite docs say\n // zero-termination is a minor optimization so add room for that.\n // Also add space for the statement handle and SQL tail pointer.\n const allocSize = utf8.byteLength - (utf8.byteLength % 4) + 12;\n const pzHead = Module._sqlite3_malloc(allocSize);\n const pzEnd = pzHead + utf8.byteLength + 1;\n onFinally.push(() => Module._sqlite3_free(pzHead));\n Module.HEAPU8.set(utf8, pzHead);\n Module.HEAPU8[pzEnd - 1] = 0;\n \n // Use extra space for the statement handle and SQL tail pointer.\n const pStmt = pzHead + allocSize - 8;\n const pzTail = pzHead + allocSize - 4;\n\n // Ensure that statement handles are not leaked.\n let stmt;\n function maybeFinalize() {\n if (stmt && !options.unscoped) {\n sqlite3.finalize(stmt);\n }\n stmt = 0;\n }\n onFinally.push(maybeFinalize);\n \n // Loop over statements.\n Module.setValue(pzTail, pzHead, '*');\n do {\n // Reclaim resources for the previous iteration.\n maybeFinalize();\n\n // Call sqlite3_prepare_v3() for the next statement.\n // Allow retry operations.\n const zTail = Module.getValue(pzTail, '*');\n const rc = await retry(() => {\n return prepare(\n db,\n zTail,\n pzEnd - pzTail,\n options.flags || 0,\n pStmt,\n pzTail);\n });\n\n if (rc !== SQLite.SQLITE_OK) {\n check('sqlite3_prepare_v3', rc, db);\n }\n \n stmt = Module.getValue(pStmt, '*');\n if (stmt) {\n mapStmtToDB.set(stmt, db);\n yield stmt;\n }\n } while (stmt);\n } finally {\n while (onFinally.length) {\n onFinally.pop()();\n }\n }\n })();\n };\n\n sqlite3.step = (function() {\n const fname = 'sqlite3_step';\n const f = Module.cwrap(fname, ...decl('n:n'), { async });\n return async function(stmt) {\n verifyStatement(stmt);\n\n // Allow retry operations.\n const rc = await retry(() => f(stmt));\n\n return check(fname, rc, mapStmtToDB.get(stmt), [SQLite.SQLITE_ROW, SQLite.SQLITE_DONE]);\n };\n })();\n\n sqlite3.commit_hook = function(db, xCommitHook) {\n verifyDatabase(db);\n Module.commit_hook(db, xCommitHook);\n };\n\n sqlite3.update_hook = function(db, xUpdateHook) {\n verifyDatabase(db);\n\n // Convert SQLite callback arguments to JavaScript-friendly arguments.\n function cvtArgs(iUpdateType, dbName, tblName, lo32, hi32) {\n return [\n iUpdateType,\n Module.UTF8ToString(dbName),\n Module.UTF8ToString(tblName),\n\t\tcvt32x2ToBigInt(lo32, hi32)\n ];\n };\n function adapt(f) {\n return f instanceof AsyncFunction ?\n (async (iUpdateType, dbName, tblName, lo32, hi32) => f(...cvtArgs(iUpdateType, dbName, tblName, lo32, hi32))) :\n ((iUpdateType, dbName, tblName, lo32, hi32) => f(...cvtArgs(iUpdateType, dbName, tblName, lo32, hi32)));\n }\n\n Module.update_hook(db, adapt(xUpdateHook));\n };;\n\n sqlite3.value = function(pValue) {\n const type = sqlite3.value_type(pValue);\n switch (type) {\n case SQLite.SQLITE_BLOB:\n return sqlite3.value_blob(pValue);\n case SQLite.SQLITE_FLOAT:\n return sqlite3.value_double(pValue);\n case SQLite.SQLITE_INTEGER:\n const lo32 = sqlite3.value_int(pValue);\n const hi32 = Module.getTempRet0();\n return cvt32x2AsSafe(lo32, hi32);\n case SQLite.SQLITE_NULL:\n return null;\n case SQLite.SQLITE_TEXT:\n return sqlite3.value_text(pValue);\n default:\n throw new SQLiteError('unknown type', type);\n }\n };\n\n sqlite3.value_blob = (function() {\n const fname = 'sqlite3_value_blob';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const nBytes = sqlite3.value_bytes(pValue);\n const address = f(pValue);\n const result = Module.HEAPU8.subarray(address, address + nBytes);\n return result;\n };\n })();\n\n sqlite3.value_bytes = (function() {\n const fname = 'sqlite3_value_bytes';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.value_double = (function() {\n const fname = 'sqlite3_value_double';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.value_int = (function() {\n const fname = 'sqlite3_value_int64';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.value_int64 = (function() {\n const fname = 'sqlite3_value_int64';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const lo32 = f(pValue);\n const hi32 = Module.getTempRet0();\n const result = cvt32x2ToBigInt(lo32, hi32);\n return result;\n };\n })();\n\n sqlite3.value_text = (function() {\n const fname = 'sqlite3_value_text';\n const f = Module.cwrap(fname, ...decl('n:s'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.value_type = (function() {\n const fname = 'sqlite3_value_type';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.vfs_register = function(vfs, makeDefault) {\n const result = Module.vfs_register(vfs, makeDefault);\n return check('sqlite3_vfs_register', result);\n };\n\n function check(fname, result, db = null, allowed = [SQLite.SQLITE_OK]) {\n if (allowed.includes(result)) return result;\n const message = db ? Module.ccall('sqlite3_errmsg', 'string', ['number'], [db]) : fname;\n throw new SQLiteError(message, result);\n }\n\n // This function is used to automatically retry failed calls that\n // have pending retry operations that should allow the retry to\n // succeed.\n async function retry(f) {\n let rc;\n for (let retryCount = 0; retryCount < 2; ++retryCount) {\n // Wait for all pending retry operations to complete. This is\n // normally empty on the first loop iteration.\n if (Module.retryOps.length) {\n try {\n await Promise.all(Module.retryOps);\n } finally {\n Module.retryOps = [];\n }\n }\n \n rc = await f();\n if (rc === SQLite.SQLITE_OK || Module.retryOps.length === 0) {\n if (Module.pendingOps.length) {\n try {\n await Promise.all(Module.pendingOps);\n } catch (e) {\n console.error('Error in pendingOps:', e);\n return e.code || SQLite.SQLITE_ERROR;\n } finally {\n Module.pendingOps = [];\n }\n }\n return rc;\n }\n }\n return rc;\n }\n\n return sqlite3;\n}\n\n// Helper function to use a more compact signature specification.\nfunction decl(s) {\n const result = [];\n const m = s.match(/([ns@]*):([nsv@])/);\n switch (m[2]) {\n case 'n':\n result.push('number');\n break;\n case 's':\n result.push('string');\n break;\n case 'v':\n result.push(null);\n break;\n }\n\n const args = [];\n for (let c of m[1]) {\n switch (c) {\n case 'n':\n args.push('number');\n break;\n case 's':\n args.push('string');\n break;\n }\n }\n result.push(args);\n return result;\n}\n","/**\n * List of currently tested virtual filesystems\n */\nexport var WASQLiteVFS;\n(function (WASQLiteVFS) {\n WASQLiteVFS[\"IDBBatchAtomicVFS\"] = \"IDBBatchAtomicVFS\";\n WASQLiteVFS[\"OPFSCoopSyncVFS\"] = \"OPFSCoopSyncVFS\";\n WASQLiteVFS[\"AccessHandlePoolVFS\"] = \"AccessHandlePoolVFS\";\n WASQLiteVFS[\"OPFSWriteAheadVFS\"] = \"OPFSWriteAheadVFS\";\n})(WASQLiteVFS || (WASQLiteVFS = {}));\nexport function vfsRequiresDedicatedWorkers(vfs) {\n return vfs != WASQLiteVFS.IDBBatchAtomicVFS;\n}\nasync function asyncModuleFactory(encryptionKey) {\n if (encryptionKey) {\n const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs');\n return factory();\n }\n else {\n const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');\n return factory();\n }\n}\nasync function syncModuleFactory(encryptionKey) {\n if (encryptionKey) {\n const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs');\n return factory();\n }\n else {\n const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite.mjs');\n return factory();\n }\n}\n/**\n * @internal\n */\nexport const DEFAULT_MODULE_FACTORIES = {\n [WASQLiteVFS.IDBBatchAtomicVFS]: async (options) => {\n const module = await asyncModuleFactory(options.encryptionKey);\n const { IDBBatchAtomicVFS } = await import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');\n return {\n module,\n // @ts-expect-error The types for this static method are missing upstream\n vfs: await IDBBatchAtomicVFS.create(options.dbFileName, module, { lockPolicy: 'exclusive' })\n };\n },\n [WASQLiteVFS.AccessHandlePoolVFS]: async (options) => {\n const module = await syncModuleFactory(options.encryptionKey);\n // @ts-expect-error The types for this static method are missing upstream\n const { AccessHandlePoolVFS } = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');\n return {\n module,\n vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)\n };\n },\n [WASQLiteVFS.OPFSCoopSyncVFS]: async (options) => {\n const module = await syncModuleFactory(options.encryptionKey);\n // @ts-expect-error The types for this static method are missing upstream\n const { OPFSCoopSyncVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');\n const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);\n return {\n module,\n vfs\n };\n },\n [WASQLiteVFS.OPFSWriteAheadVFS]: async (options) => {\n const module = await syncModuleFactory(options.encryptionKey);\n // @ts-expect-error The types for this static method are missing upstream\n const { OPFSWriteAheadVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSWriteAheadVFS.js');\n const vfs = await OPFSWriteAheadVFS.create(options.dbFileName, module, {});\n return {\n module,\n vfs\n };\n }\n};\n//# sourceMappingURL=vfs.js.map","import { Factory as WaSqliteFactory, SQLITE_ROW } from '@journeyapps/wa-sqlite';\nimport { DEFAULT_MODULE_FACTORIES } from './vfs.js';\n/**\n * A small wrapper around WA-sqlite to help with opening databases and running statements by preparing them internally.\n *\n * This is an internal class, and it must never be used directly. Wrappers are required to ensure raw connections aren't\n * used concurrently across tabs.\n */\nexport class RawSqliteConnection {\n options;\n _sqliteAPI = null;\n /**\n * The `sqlite3*` connection pointer.\n */\n db = 0;\n _moduleFactory;\n constructor(options) {\n this.options = options;\n this._moduleFactory = DEFAULT_MODULE_FACTORIES[this.options.vfs];\n }\n get isOpen() {\n return this.db != 0;\n }\n async init() {\n const api = (this._sqliteAPI = await this.openSQLiteAPI());\n this.db = await api.open_v2(this.options.filename, this.options.readonly ? 1 /* SQLITE_OPEN_READONLY */ : 6 /* SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE */);\n await this.executeRaw(`PRAGMA temp_store = ${this.options.temporaryStorage};`);\n if (this.options.encryptionKey) {\n const escapedKey = this.options.encryptionKey.replace(\"'\", \"''\");\n await this.executeRaw(`PRAGMA key = '${escapedKey}'`);\n }\n await this.executeRaw(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);\n await this.executeRaw(`SELECT powersync_update_hooks('install');`);\n }\n async openSQLiteAPI() {\n const { module, vfs } = await this._moduleFactory({\n dbFileName: this.options.filename,\n encryptionKey: this.options.encryptionKey\n });\n const sqlite3 = WaSqliteFactory(module);\n sqlite3.vfs_register(vfs, true);\n /**\n * Register the PowerSync core SQLite extension\n */\n module.ccall('powersync_init_static', 'int', []);\n /**\n * Create the multiple cipher vfs if an encryption key is provided\n */\n if (this.options.encryptionKey) {\n const createResult = module.ccall('sqlite3mc_vfs_create', 'int', ['string', 'int'], [this.options.filename, 1]);\n if (createResult !== 0) {\n throw new Error('Failed to create multiple cipher vfs, Database encryption will not work');\n }\n }\n return sqlite3;\n }\n requireSqlite() {\n if (!this._sqliteAPI) {\n throw new Error(`Initialization has not completed`);\n }\n return this._sqliteAPI;\n }\n /**\n * Checks if the database connection is in autocommit mode.\n * @returns true if in autocommit mode, false if in a transaction\n */\n isAutoCommit() {\n return this.requireSqlite().get_autocommit(this.db) != 0;\n }\n async execute(sql, bindings) {\n const resultSet = await this.executeSingleStatementRaw(sql, bindings);\n return this.wrapQueryResults(this.requireSqlite(), resultSet);\n }\n async executeBatch(sql, bindings) {\n const results = [];\n const api = this.requireSqlite();\n for await (const stmt of api.statements(this.db, sql)) {\n let columns;\n for (const parameterSet of bindings) {\n const rs = await this.stepThroughStatement(api, stmt, parameterSet, columns, false);\n results.push(this.wrapQueryResults(api, rs));\n }\n // executeBatch can only use a single statement\n break;\n }\n return results;\n }\n wrapQueryResults(api, { rawRows, columnNames }) {\n return {\n rowsAffected: api.changes(this.db),\n insertId: api.last_insert_id(this.db),\n autocommit: api.get_autocommit(this.db) != 0,\n rawRows,\n columnNames\n };\n }\n /**\n * This executes a single statement using SQLite3 and returns the results as a {@link RawResultSet}.\n */\n async executeSingleStatementRaw(sql, bindings) {\n const results = await this.executeRaw(sql, bindings);\n return results.length ? results[0] : { columnNames: [], rawRows: [] };\n }\n async executeRaw(sql, bindings) {\n const results = [];\n const api = this.requireSqlite();\n for await (const stmt of api.statements(this.db, sql)) {\n let columns;\n const rs = await this.stepThroughStatement(api, stmt, bindings ?? [], columns);\n columns = rs.columnNames;\n if (columns.length) {\n results.push(rs);\n }\n // When binding parameters, only a single statement is executed.\n if (bindings) {\n break;\n }\n }\n return results;\n }\n async stepThroughStatement(api, stmt, bindings, knownColumns, includeResults = true) {\n // TODO not sure why this is needed currently, but booleans break\n bindings.forEach((b, index, arr) => {\n if (typeof b == 'boolean') {\n arr[index] = b ? 1 : 0;\n }\n });\n api.reset(stmt);\n if (bindings) {\n api.bind_collection(stmt, bindings);\n }\n const rows = [];\n while ((await api.step(stmt)) === SQLITE_ROW) {\n if (includeResults) {\n const row = api.row(stmt);\n rows.push(row);\n }\n }\n knownColumns ??= api.column_names(stmt);\n return { columnNames: knownColumns, rawRows: rows };\n }\n async close() {\n if (this.isOpen) {\n await this.requireSqlite().close(this.db);\n this.db = 0;\n }\n }\n}\n//# sourceMappingURL=RawSqliteConnection.js.map","export var PSInternalTable;\n(function (PSInternalTable) {\n PSInternalTable[\"DATA\"] = \"ps_data\";\n PSInternalTable[\"CRUD\"] = \"ps_crud\";\n PSInternalTable[\"BUCKETS\"] = \"ps_buckets\";\n PSInternalTable[\"OPLOG\"] = \"ps_oplog\";\n PSInternalTable[\"UNTYPED\"] = \"ps_untyped\";\n})(PSInternalTable || (PSInternalTable = {}));\nexport var PowerSyncControlCommand;\n(function (PowerSyncControlCommand) {\n PowerSyncControlCommand[\"PROCESS_TEXT_LINE\"] = \"line_text\";\n PowerSyncControlCommand[\"PROCESS_BSON_LINE\"] = \"line_binary\";\n PowerSyncControlCommand[\"STOP\"] = \"stop\";\n PowerSyncControlCommand[\"START\"] = \"start\";\n PowerSyncControlCommand[\"NOTIFY_TOKEN_REFRESHED\"] = \"refreshed_token\";\n PowerSyncControlCommand[\"NOTIFY_CRUD_UPLOAD_COMPLETED\"] = \"completed_upload\";\n PowerSyncControlCommand[\"UPDATE_SUBSCRIPTIONS\"] = \"update_subscriptions\";\n /**\n * An `established` or `end` event for response streams.\n */\n PowerSyncControlCommand[\"CONNECTION_STATE\"] = \"connection\";\n})(PowerSyncControlCommand || (PowerSyncControlCommand = {}));\n//# sourceMappingURL=BucketStorageAdapter.js.map","/**\n * @internal The priority used by the core extension to indicate that a full sync was completed.\n */\nexport const FULL_SYNC_PRIORITY = 2147483647;\nexport const MAX_OP_ID = '9223372036854775807';\n//# sourceMappingURL=constants.js.map","// (bucket, progress) pairs\nimport { FULL_SYNC_PRIORITY } from '../../constants.js';\nexport class SyncProgressImpl {\n internal;\n totalOperations;\n downloadedOperations;\n downloadedFraction;\n constructor(internal) {\n this.internal = internal;\n const untilCompletion = this.untilPriority(FULL_SYNC_PRIORITY);\n this.totalOperations = untilCompletion.totalOperations;\n this.downloadedOperations = untilCompletion.downloadedOperations;\n this.downloadedFraction = untilCompletion.downloadedFraction;\n }\n untilPriority(priority) {\n let total = 0;\n let downloaded = 0;\n for (const progress of Object.values(this.internal.buckets)) {\n // Include higher-priority buckets, which are represented by lower numbers.\n if (progress.priority <= priority) {\n downloaded += progress.since_last;\n total += progress.target_count - progress.at_last;\n }\n }\n let progress = total == 0 ? 0.0 : downloaded / total;\n return {\n totalOperations: total,\n downloadedOperations: downloaded,\n downloadedFraction: progress\n };\n }\n}\n//# sourceMappingURL=SyncProgress.js.map","import { SyncProgressImpl } from './SyncProgress.js';\nimport { FULL_SYNC_PRIORITY } from '../../constants.js';\nexport class SyncStatusSnapshot {\n core;\n jsState;\n constructor(core, jsState) {\n this.core = core;\n this.jsState = jsState;\n }\n get connected() {\n return this.core?.connected ?? false;\n }\n get connecting() {\n return this.core?.connecting ?? false;\n }\n get downloading() {\n return this.core?.downloading != null;\n }\n get uploading() {\n return this.jsState.uploading ?? false;\n }\n get downloadError() {\n return this.jsState.downloadError;\n }\n get uploadError() {\n return this.jsState.uploadError;\n }\n get dataFlowStatus() {\n return {\n downloading: this.downloading,\n uploading: this.uploading,\n downloadError: this.downloadError,\n uploadError: this.uploadError\n };\n }\n get lastSyncedAt() {\n return this.statusForPriority(FULL_SYNC_PRIORITY)?.lastSyncedAt;\n }\n get hasSynced() {\n return this.statusForPriority(FULL_SYNC_PRIORITY)?.hasSynced;\n }\n get syncStreams() {\n return this.core?.streams.map((core) => new SyncStreamStatusView(this, core));\n }\n forStream(stream) {\n const asJson = JSON.stringify(stream.parameters);\n const raw = this.core?.streams?.find((r) => r.name == stream.name && asJson == JSON.stringify(r.parameters));\n return raw && new SyncStreamStatusView(this, raw);\n }\n get priorityStatusEntries() {\n return this.core?.priority_status.map(priorityToJs);\n }\n get downloadProgress() {\n const internalProgress = this.core?.downloading;\n if (internalProgress == null) {\n return null;\n }\n return new SyncProgressImpl(internalProgress);\n }\n statusForPriority(priority) {\n const coreStatus = this.core?.priority_status;\n if (coreStatus == null)\n return undefined;\n // priorityStatusEntries are sorted by ascending priorities (so higher numbers to lower numbers).\n for (const known of coreStatus) {\n // We look for the first entry that doesn't have a higher priority.\n if (known.priority >= priority) {\n return priorityToJs(known);\n }\n }\n // If we get to this point, no priority entry exists so we never synced a priority that low.\n return {\n priority,\n lastSyncedAt: undefined,\n hasSynced: false\n };\n }\n isEqual(status) {\n /**\n * By default Error object are serialized to an empty object.\n * This replaces Errors with more useful information before serialization.\n */\n const replacer = (_, value) => {\n if (value instanceof Error) {\n return this.serializeError(value);\n }\n return value;\n };\n const options = { core: this.core, jsState: this.jsState };\n const otherStatus = status;\n const otherOptions = {\n core: otherStatus.core,\n jsState: otherStatus.jsState\n };\n return JSON.stringify(options, replacer) == JSON.stringify(otherOptions, replacer);\n }\n getMessage() {\n return `SyncStatus<connected: ${this.connected} connecting: ${this.connecting} lastSyncedAt: ${this.lastSyncedAt} hasSynced: ${this.hasSynced}. Downloading: ${this.downloading}. Uploading: ${this.uploading}. UploadError: ${this.uploadError}, DownloadError?: ${this.downloadError}>`;\n }\n /**\n * Serializes the SyncStatus instance to a plain object.\n *\n * @returns A plain object representation of the sync status\n */\n toJSON() {\n return {\n core: this.core,\n dataFlow: {\n uploading: this.uploading,\n uploadError: this.serializeError(this.uploadError),\n downloadError: this.serializeError(this.downloadError)\n }\n };\n }\n /**\n * Not all errors are serializable over a MessagePort. E.g. some `DomExceptions` fail to be passed across workers.\n * This explicitly serializes errors in the SyncStatus.\n */\n serializeError(error) {\n if (typeof error == 'undefined') {\n return undefined;\n }\n const serialized = {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n // `Error.cause` can be any value (the spec types it as unknown). Preserve it\n // so consumers reading uploadError/downloadError keep the failure context.\n // Recurse for Error causes so the whole chain is flattened the same way.\n if (typeof error.cause != 'undefined') {\n serialized.cause = error.cause instanceof Error ? this.serializeError(error.cause) : error.cause;\n }\n return serialized;\n }\n}\nfunction coreTimestampToDate(time) {\n return time == null ? undefined : new Date(time * 1000);\n}\nfunction priorityToJs(status) {\n return {\n priority: status.priority,\n hasSynced: status.has_synced ?? undefined,\n lastSyncedAt: coreTimestampToDate(status.last_synced_at)\n };\n}\nclass SyncStreamStatusView {\n status;\n core;\n subscription;\n constructor(status, core) {\n this.status = status;\n this.core = core;\n this.subscription = {\n name: core.name,\n parameters: core.parameters,\n active: core.active,\n isDefault: core.is_default,\n hasExplicitSubscription: core.has_explicit_subscription,\n expiresAt: core.expires_at != null ? new Date(core.expires_at * 1000) : null,\n hasSynced: core.last_synced_at != null,\n lastSyncedAt: core.last_synced_at != null ? new Date(core.last_synced_at * 1000) : null\n };\n }\n get progress() {\n if (this.status.core?.downloading == null) {\n // Don't make download progress public if we're not currently downloading.\n return null;\n }\n const { total, downloaded } = this.core.progress;\n const progress = total == 0 ? 0.0 : downloaded / total;\n return { totalOperations: total, downloadedOperations: downloaded, downloadedFraction: progress };\n }\n get priority() {\n return this.core.priority;\n }\n}\n//# sourceMappingURL=SyncStatus.js.map","import { FetchStrategy } from '@powersync/common';\n/**\n * @internal\n */\nexport function resolveSyncOptions(options, defaultConnectionMethod) {\n return {\n appMetadata: options.appMetadata ?? {},\n connectionMethod: options.connectionMethod ?? defaultConnectionMethod,\n fetchStrategy: options.fetchStrategy ?? FetchStrategy.Buffered,\n params: options.params ?? {},\n includeDefaultStreams: options.includeDefaultStreams ?? true,\n retryDelayMs: options.retryDelayMs ?? 5000,\n crudUploadThrottleMs: options.crudUploadThrottleMs ?? 1000\n };\n}\n//# sourceMappingURL=options.js.map","import { BaseObserver, LogLevels } from '@powersync/common';\nimport { resolveSyncOptions } from './sync/options.js';\n/**\n * @internal\n */\nexport class ConnectionManager extends BaseObserver {\n options;\n /**\n * Tracks active connection attempts\n */\n connectingPromise;\n /**\n * Tracks actively instantiating a streaming sync implementation.\n */\n syncStreamInitPromise;\n /**\n * Active disconnect operation. Calling disconnect multiple times\n * will resolve to the same operation.\n */\n disconnectingPromise;\n /**\n * Tracks the last parameters supplied to `connect` calls.\n * Calling `connect` multiple times in succession will result in:\n * - 1 pending connection operation which will be aborted.\n * - updating the last set of parameters while waiting for the pending\n * attempt to be aborted\n * - internally connecting with the last set of parameters\n */\n pendingConnectionOptions;\n currentOptions;\n syncStreamImplementation;\n /**\n * Additional cleanup function which is called after the sync stream implementation\n * is disposed.\n */\n syncDisposer;\n /**\n * Subscriptions managed in this connection manager.\n *\n * On the web, these local subscriptions are merged across tabs by a shared worker.\n */\n locallyActiveSubscriptions = new Map();\n constructor(options) {\n super();\n this.options = options;\n this.connectingPromise = null;\n this.syncStreamInitPromise = null;\n this.disconnectingPromise = null;\n this.pendingConnectionOptions = null;\n this.syncStreamImplementation = null;\n this.currentOptions = null;\n this.syncDisposer = null;\n }\n get connector() {\n return this.pendingConnectionOptions?.connector ?? null;\n }\n get connectionOptions() {\n return this.currentOptions ?? this.pendingConnectionOptions?.options ?? null;\n }\n get logger() {\n return this.options.logger;\n }\n async close() {\n await this.syncStreamImplementation?.dispose();\n await this.syncDisposer?.();\n }\n async connect(connector, options, serializedSchema) {\n // Keep track if there were pending operations before this call\n const hadPendingOptions = !!this.pendingConnectionOptions;\n // Update pending options to the latest values\n this.pendingConnectionOptions = {\n connector,\n options: resolveSyncOptions(options, this.options.defaultConnectionMethod),\n schema: serializedSchema\n };\n // Disconnecting here provides aborting in progress connection attempts.\n // The connectInternal method will clear pending options once it starts connecting (with the options).\n // We only need to trigger a disconnect here if we have already reached the point of connecting.\n // If we do already have pending options, a disconnect has already been performed.\n // The connectInternal method also does a sanity disconnect to prevent straggler connections.\n // We should also disconnect if we have already completed a connection attempt.\n if (!hadPendingOptions || this.syncStreamImplementation) {\n await this.disconnectInternal();\n }\n // Triggers a connect which checks if pending options are available after the connect completes.\n // The completion can be for a successful, unsuccessful or aborted connection attempt.\n // If pending options are available another connection will be triggered.\n const checkConnection = async () => {\n if (this.pendingConnectionOptions) {\n // Pending options have been placed while connecting.\n // Need to reconnect.\n this.connectingPromise = this.connectInternal()\n .catch(() => { })\n .finally(checkConnection);\n return this.connectingPromise;\n }\n else {\n // Clear the connecting promise, done.\n this.connectingPromise = null;\n return;\n }\n };\n this.connectingPromise ??= this.connectInternal()\n .catch(() => { })\n .finally(checkConnection);\n return this.connectingPromise;\n }\n async connectInternal() {\n let appliedOptions = null;\n // This method ensures a disconnect before any connection attempt\n await this.disconnectInternal();\n /**\n * This portion creates a sync implementation which can be racy when disconnecting or\n * if multiple tabs on web are in use.\n * This is protected in an exclusive lock.\n * The promise tracks the creation which is used to synchronize disconnect attempts.\n */\n this.syncStreamInitPromise = new Promise(async (resolve, reject) => {\n try {\n if (!this.pendingConnectionOptions) {\n this.logger.log({\n level: LogLevels.debug,\n message: 'No pending connection options found, not creating sync stream implementation'\n });\n // A disconnect could have cleared this.\n resolve();\n return;\n }\n if (this.disconnectingPromise) {\n resolve();\n return;\n }\n const { connector, options, schema } = this.pendingConnectionOptions;\n appliedOptions = options;\n this.currentOptions = options;\n this.pendingConnectionOptions = null;\n const { sync, onDispose } = await this.options.createSyncImplementation(connector, {\n subscriptions: this.activeStreams,\n serializedSchema: schema\n });\n this.iterateListeners((l) => l.syncStreamCreated?.(sync));\n this.syncStreamImplementation = sync;\n this.syncDisposer = onDispose;\n await this.syncStreamImplementation.waitForReady();\n resolve();\n }\n catch (error) {\n reject(error);\n }\n });\n await this.syncStreamInitPromise;\n this.syncStreamInitPromise = null;\n if (!appliedOptions) {\n // A disconnect could have cleared the options which did not create a syncStreamImplementation\n return;\n }\n // It might be possible that a disconnect triggered between the last check\n // and this point. Awaiting here allows the sync stream to be cleared if disconnected.\n await this.disconnectingPromise;\n this.logger.log({ level: LogLevels.debug, message: 'Attempting to connect to PowerSync instance' });\n await this.syncStreamImplementation?.connect(appliedOptions);\n }\n /**\n * Close the sync connection.\n *\n * Use {@link ConnectionManager.connect} to connect again.\n */\n async disconnect() {\n // This will help abort pending connects\n this.pendingConnectionOptions = null;\n this.currentOptions = null;\n await this.disconnectInternal();\n }\n async disconnectInternal() {\n if (this.disconnectingPromise) {\n // A disconnect is already in progress\n return this.disconnectingPromise;\n }\n this.disconnectingPromise = this.performDisconnect();\n await this.disconnectingPromise;\n this.disconnectingPromise = null;\n }\n async performDisconnect() {\n // Wait if a sync stream implementation is being created before closing it\n // (syncStreamImplementation must be assigned before we can properly dispose it)\n await this.syncStreamInitPromise;\n // Keep reference to the sync stream implementation and disposer\n // The class members will be cleared before we trigger the disconnect\n // to prevent any further calls to the sync stream implementation.\n const sync = this.syncStreamImplementation;\n this.syncStreamImplementation = null;\n const disposer = this.syncDisposer;\n this.syncDisposer = null;\n await sync?.disconnect();\n await sync?.dispose();\n await disposer?.();\n }\n stream(adapter, name, parameters) {\n const desc = { name, parameters };\n const waitForFirstSync = (abort) => {\n return adapter.firstStatusMatching((s) => s.forStream(desc)?.subscription.hasSynced, abort);\n };\n return {\n ...desc,\n subscribe: async (options) => {\n // NOTE: We also run this command if a subscription already exists, because this increases the expiry date\n // (relevant if the app is closed before connecting again, where the last subscribe call determines the ttl).\n await adapter.rustSubscriptionsCommand({\n subscribe: {\n stream: {\n name,\n params: parameters\n },\n ttl: options?.ttl,\n priority: options?.priority\n }\n });\n if (!this.syncStreamImplementation) {\n // We're not connected. So, update the offline sync status to reflect the new subscription.\n // (With an active iteration, the sync client would include it in its state).\n await adapter.resolveOfflineSyncStatus();\n }\n const key = `${name}|${JSON.stringify(parameters)}`;\n let subscription = this.locallyActiveSubscriptions.get(key);\n if (subscription == null) {\n const clearSubscription = () => {\n this.locallyActiveSubscriptions.delete(key);\n this.subscriptionsMayHaveChanged();\n };\n subscription = new ActiveSubscription(name, parameters, this.logger, waitForFirstSync, clearSubscription);\n this.locallyActiveSubscriptions.set(key, subscription);\n this.subscriptionsMayHaveChanged();\n }\n return new SyncStreamSubscriptionHandle(subscription);\n },\n unsubscribeAll: async () => {\n await adapter.rustSubscriptionsCommand({ unsubscribe: { name, params: parameters } });\n this.subscriptionsMayHaveChanged();\n }\n };\n }\n /**\n * @internal exposed for testing\n */\n get activeStreams() {\n return [...this.locallyActiveSubscriptions.values()].map((a) => ({ name: a.name, params: a.parameters }));\n }\n subscriptionsMayHaveChanged() {\n this.syncStreamImplementation?.updateSubscriptions(this.activeStreams);\n }\n}\nclass ActiveSubscription {\n name;\n parameters;\n logger;\n waitForFirstSync;\n clearSubscription;\n refcount = 0;\n constructor(name, parameters, logger, waitForFirstSync, clearSubscription) {\n this.name = name;\n this.parameters = parameters;\n this.logger = logger;\n this.waitForFirstSync = waitForFirstSync;\n this.clearSubscription = clearSubscription;\n }\n decrementRefCount() {\n this.refcount--;\n if (this.refcount == 0) {\n this.clearSubscription();\n }\n }\n}\nclass SyncStreamSubscriptionHandle {\n subscription;\n active = true;\n constructor(subscription) {\n this.subscription = subscription;\n subscription.refcount++;\n _finalizer?.register(this, subscription, this);\n }\n get name() {\n return this.subscription.name;\n }\n get parameters() {\n return this.subscription.parameters;\n }\n waitForFirstSync(abort) {\n return this.subscription.waitForFirstSync(abort);\n }\n unsubscribe() {\n if (this.active) {\n this.active = false;\n _finalizer?.unregister(this);\n this.subscription.decrementRefCount();\n }\n }\n}\nconst _finalizer = 'FinalizationRegistry' in globalThis\n ? new FinalizationRegistry((sub) => {\n sub.logger.log({\n level: LogLevels.warn,\n message: `A subscription to ${sub.name} with params ${JSON.stringify(sub.parameters)} leaked! Please ensure calling unsubscribe() when you don't need a subscription anymore. For global subscriptions, consider storing them in global fields to avoid this warning.`\n });\n })\n : null;\n//# sourceMappingURL=ConnectionManager.js.map","/**\n * A simple fixed-capacity queue implementation.\n *\n * Unlike a naive queue implemented by `array.push()` and `array.shift()`, this avoids moving array elements around\n * and is `O(1)` for {@link addLast} and {@link removeFirst}.\n */\nexport class Queue {\n table;\n // Index of the first element in the table.\n head;\n // Amount of items currently in the queue.\n _length;\n constructor(initialItems) {\n this.table = [...initialItems];\n this.head = 0;\n this._length = this.table.length;\n }\n get isEmpty() {\n return this.length == 0;\n }\n get length() {\n return this._length;\n }\n removeFirst() {\n if (this.isEmpty) {\n throw new Error('Queue is empty');\n }\n const result = this.table[this.head];\n this._length--;\n this.table[this.head] = undefined;\n this.head = (this.head + 1) % this.table.length;\n return result;\n }\n addLast(element) {\n if (this.length == this.table.length) {\n throw new Error('Queue is full');\n }\n this.table[(this.head + this._length) % this.table.length] = element;\n this._length++;\n }\n}\n//# sourceMappingURL=queue.js.map","import { Queue } from './queue.js';\n/**\n * An asynchronous semaphore implementation with associated items per lease.\n */\nexport class Semaphore {\n // Available items that are not currently assigned to a waiter.\n available;\n size;\n // Linked list of waiters. We don't expect the wait list to become particularly large, and this allows removing\n // aborted waiters from the middle of the list efficiently.\n firstWaiter;\n lastWaiter;\n constructor(elements) {\n this.available = new Queue(elements);\n this.size = this.available.length;\n }\n addWaiter(requestedItems, onAcquire) {\n const node = {\n isActive: true,\n acquiredItems: [],\n remainingItems: requestedItems,\n onAcquire,\n prev: this.lastWaiter\n };\n if (this.lastWaiter) {\n this.lastWaiter.next = node;\n this.lastWaiter = node;\n }\n else {\n // First waiter\n this.lastWaiter = this.firstWaiter = node;\n }\n return node;\n }\n deactivateWaiter(waiter) {\n const { prev, next } = waiter;\n waiter.isActive = false;\n if (prev)\n prev.next = next;\n if (next)\n next.prev = prev;\n if (waiter == this.firstWaiter)\n this.firstWaiter = next;\n if (waiter == this.lastWaiter)\n this.lastWaiter = prev;\n }\n requestPermits(amount, abort) {\n if (amount <= 0 || amount > this.size) {\n throw new Error(`Invalid amount of items requested (${amount}), must be between 1 and ${this.size}`);\n }\n return new Promise((resolve, reject) => {\n function rejectAborted() {\n reject(abort?.reason ?? new Error('Semaphore acquire aborted'));\n }\n if (abort?.aborted) {\n return rejectAborted();\n }\n let waiter;\n const markCompleted = () => {\n const items = waiter.acquiredItems;\n waiter.acquiredItems = []; // Avoid releasing items twice.\n for (const element of items) {\n // Give to next waiter, if possible.\n const nextWaiter = this.firstWaiter;\n if (nextWaiter) {\n nextWaiter.acquiredItems.push(element);\n nextWaiter.remainingItems--;\n if (nextWaiter.remainingItems == 0) {\n nextWaiter.onAcquire();\n }\n }\n else {\n // No pending waiter, return lease into pool.\n this.available.addLast(element);\n }\n }\n };\n const onAbort = () => {\n abort?.removeEventListener('abort', onAbort);\n if (waiter.isActive) {\n this.deactivateWaiter(waiter);\n rejectAborted();\n }\n };\n const resolvePromise = () => {\n this.deactivateWaiter(waiter);\n abort?.removeEventListener('abort', onAbort);\n const items = waiter.acquiredItems;\n resolve({ items, release: markCompleted });\n };\n waiter = this.addWaiter(amount, resolvePromise);\n // If there are items in the pool that haven't been assigned, we can pull them into this waiter. Note that this is\n // only the case if we're the first waiter (otherwise, items would have been assigned to an earlier waiter).\n while (!this.available.isEmpty && waiter.remainingItems > 0) {\n waiter.acquiredItems.push(this.available.removeFirst());\n waiter.remainingItems--;\n }\n if (waiter.remainingItems == 0) {\n return resolvePromise();\n }\n abort?.addEventListener('abort', onAbort);\n });\n }\n /**\n * Requests a single item from the pool.\n *\n * The returned `release` callback must be invoked to return the item into the pool.\n */\n async requestOne(abort) {\n const { items, release } = await this.requestPermits(1, abort);\n return { release, item: items[0] };\n }\n /**\n * Requests access to all items from the pool.\n *\n * The returned `release` callback must be invoked to return items into the pool.\n */\n requestAll(abort) {\n return this.requestPermits(this.size, abort);\n }\n}\n/**\n * An asynchronous mutex implementation.\n */\nexport class Mutex {\n inner = new Semaphore([null]);\n async acquire(abort) {\n const { release } = await this.inner.requestOne(abort);\n return release;\n }\n async runExclusive(fn, abort) {\n const returnMutex = await this.acquire(abort);\n try {\n return await fn();\n }\n finally {\n returnMutex();\n }\n }\n}\nexport function timeoutSignal(timeout) {\n if (timeout == null)\n return;\n if ('timeout' in AbortSignal)\n return AbortSignal.timeout(timeout);\n const controller = new AbortController();\n setTimeout(() => controller.abort(new Error('Timeout waiting for lock')), timeout);\n return controller.signal;\n}\n//# sourceMappingURL=mutex.js.map","/**\n * A single client-side change.\n *\n * @public\n */\nexport class CrudEntryImpl {\n clientId;\n id;\n op;\n opData;\n previousValues;\n table;\n transactionId;\n metadata;\n static fromRow(dbRow) {\n const data = JSON.parse(dbRow.data);\n return new CrudEntryImpl(parseInt(dbRow.id), data.op, data.type, data.id, dbRow.tx_id, data.data, data.old, data.metadata);\n }\n constructor(clientId, op, table, id, transactionId, opData, previousValues, metadata) {\n this.clientId = clientId;\n this.id = id;\n this.op = op;\n this.opData = opData;\n this.table = table;\n this.transactionId = transactionId;\n this.previousValues = previousValues;\n this.metadata = metadata;\n }\n toJSON() {\n return {\n op_id: this.clientId,\n op: this.op,\n type: this.table,\n id: this.id,\n tx_id: this.transactionId,\n data: this.opData,\n old: this.previousValues,\n metadata: this.metadata\n };\n }\n equals(entry) {\n return JSON.stringify(this.toComparisonArray()) == JSON.stringify(entry.toComparisonArray());\n }\n /**\n * Generates an array for use in deep comparison operations\n */\n toComparisonArray() {\n return [\n this.transactionId,\n this.clientId,\n this.op,\n this.table,\n this.id,\n this.opData,\n this.previousValues,\n this.metadata\n ];\n }\n}\n//# sourceMappingURL=CrudEntry.js.map","/**\n * Some JavaScript engines, in particular older versions of React Native, don't support Symbol.asyncIterator.\n *\n * For those, users relying on async generators typically lower them with a transpiler and [this polyfill](https://github.com/Azure/azure-sdk-for-js/blob/%40azure/core-asynciterator-polyfill_1.0.2/sdk/core/core-asynciterator-polyfill/src/index.ts#L4-L6).\n * This definition is compatible with that polyfill, so transpiled apps can use async iterables created by the PowerSync\n * SDK.\n */\nexport const symbolAsyncIterator = Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');\n//# sourceMappingURL=compatibility.js.map","export const doneResult = { done: true, value: undefined };\nexport function valueResult(value) {\n return { done: false, value };\n}\n/**\n * A variant of {@link Array.map} for async iterators.\n */\nexport function map(source, map) {\n return {\n next: async () => {\n const value = await source.next();\n if (value.done) {\n return value;\n }\n else {\n return { value: map(value.value) };\n }\n }\n };\n}\n/**\n * Expands a source async iterator by allowing to inject events asynchronously.\n *\n * The resulting iterator will emit all events from its source. Additionally though, events can be injected. These\n * events are dropped once the main iterator completes, but are otherwise forwarded.\n *\n * The iterator completes when its source completes, and it supports backpressure by only calling `next()` on the source\n * in response to a `next()` call from downstream if no pending injected events can be dispatched.\n */\nexport function injectable(source) {\n let sourceIsDone = false;\n let waiter = undefined; // An active, waiting next() call.\n // A pending upstream event that couldn't be dispatched because inject() has been called before it was resolved.\n let pendingSourceEvent = null;\n let sourceFetchInFlight = false;\n let pendingInjectedEvents = [];\n const consumeWaiter = () => {\n const pending = waiter;\n waiter = undefined;\n return pending;\n };\n const fetchFromSource = () => {\n const resolveWaiter = (propagate) => {\n sourceFetchInFlight = false;\n const active = consumeWaiter();\n if (active) {\n propagate(active);\n }\n else {\n pendingSourceEvent = propagate;\n }\n };\n sourceFetchInFlight = true;\n const nextFromSource = source.next();\n nextFromSource.then((value) => {\n sourceIsDone = value.done == true;\n resolveWaiter((w) => w.resolve(value));\n }, (error) => {\n resolveWaiter((w) => w.reject(error));\n });\n };\n return {\n next: () => {\n return new Promise((resolve, reject) => {\n // First priority: Dispatch ready upstream events.\n if (sourceIsDone) {\n return resolve(doneResult);\n }\n if (pendingSourceEvent) {\n pendingSourceEvent({ resolve, reject });\n pendingSourceEvent = null;\n return;\n }\n // Second priority: Dispatch injected events\n if (pendingInjectedEvents.length) {\n return resolve(valueResult(pendingInjectedEvents.shift()));\n }\n // Nothing pending? Fetch from source\n waiter = { resolve, reject };\n if (!sourceFetchInFlight) {\n fetchFromSource();\n }\n });\n },\n inject: (event) => {\n const pending = consumeWaiter();\n if (pending != null) {\n pending.resolve(valueResult(event));\n }\n else {\n pendingInjectedEvents.push(event);\n }\n }\n };\n}\n/**\n * Splits a byte stream at line endings, emitting each line as a string.\n */\nexport function extractJsonLines(source, decoder) {\n let buffer = '';\n const pendingLines = [];\n let isFinalEvent = false;\n return {\n next: async () => {\n while (true) {\n if (isFinalEvent) {\n return doneResult;\n }\n {\n const first = pendingLines.shift();\n if (first) {\n return { done: false, value: first };\n }\n }\n const { done, value } = await source.next();\n if (done) {\n const remaining = buffer.trim();\n if (remaining.length != 0) {\n isFinalEvent = true;\n return { done: false, value: remaining };\n }\n return doneResult;\n }\n const data = decoder.decode(value, { stream: true });\n buffer += data;\n const lines = buffer.split('\\n');\n for (let i = 0; i < lines.length - 1; i++) {\n const l = lines[i].trim();\n if (l.length > 0) {\n pendingLines.push(l);\n }\n }\n buffer = lines[lines.length - 1];\n }\n }\n };\n}\n/**\n * Splits a concatenated stream of BSON objects by emitting individual objects.\n */\nexport function extractBsonObjects(source) {\n // Fully read but not emitted yet.\n const completedObjects = [];\n // Whether source has returned { done: true }. We do the same once completed objects have been emitted.\n let isDone = false;\n const lengthBuffer = new DataView(new ArrayBuffer(4));\n let objectBody = null;\n // If we're parsing the length field, a number between 1 and 4 (inclusive) describing remaining bytes in the header.\n // If we're consuming a document, the bytes remaining.\n let remainingLength = 4;\n return {\n async next() {\n while (true) {\n // Before fetching new data from upstream, return completed objects.\n if (completedObjects.length) {\n return valueResult(completedObjects.shift());\n }\n if (isDone) {\n return doneResult;\n }\n const upstreamEvent = await source.next();\n if (upstreamEvent.done) {\n isDone = true;\n if (objectBody || remainingLength != 4) {\n throw new Error('illegal end of stream in BSON object');\n }\n return doneResult;\n }\n const chunk = upstreamEvent.value;\n for (let i = 0; i < chunk.length;) {\n const availableInData = chunk.length - i;\n if (objectBody) {\n // We're in the middle of reading a BSON document.\n const bytesToRead = Math.min(availableInData, remainingLength);\n const copySource = new Uint8Array(chunk.buffer, chunk.byteOffset + i, bytesToRead);\n objectBody.set(copySource, objectBody.length - remainingLength);\n i += bytesToRead;\n remainingLength -= bytesToRead;\n if (remainingLength == 0) {\n completedObjects.push(objectBody);\n // Prepare to read another document, starting with its length\n objectBody = null;\n remainingLength = 4;\n }\n }\n else {\n // Copy up to 4 bytes into lengthBuffer, depending on how many we still need.\n const bytesToRead = Math.min(availableInData, remainingLength);\n for (let j = 0; j < bytesToRead; j++) {\n lengthBuffer.setUint8(4 - remainingLength + j, chunk[i + j]);\n }\n i += bytesToRead;\n remainingLength -= bytesToRead;\n if (remainingLength == 0) {\n // Transition from reading length header to reading document. Subtracting 4 because the length of the\n // header is included in length.\n const length = lengthBuffer.getInt32(0, true /* little endian */);\n remainingLength = length - 4;\n if (remainingLength < 1) {\n throw new Error(`invalid length for bson: ${length}`);\n }\n objectBody = new Uint8Array(length);\n new DataView(objectBody.buffer).setInt32(0, length, true);\n }\n }\n }\n }\n }\n };\n}\n//# sourceMappingURL=stream_transform.js.map","import { symbolAsyncIterator } from './compatibility.js';\nimport { doneResult, valueResult } from './stream_transform.js';\n/**\n * Throttle a function to be called at most once every \"wait\" milliseconds,\n * on the trailing edge.\n *\n * Roughly equivalent to lodash/throttle with {leading: false, trailing: true}\n */\nexport function throttleTrailing(func, wait) {\n let timeoutId = null;\n const later = () => {\n func();\n timeoutId = null;\n };\n return function () {\n if (timeoutId == null) {\n timeoutId = setTimeout(later, wait);\n }\n };\n}\nexport function asyncNotifier() {\n const queue = new EventQueue();\n return {\n notify() {\n if (queue.countOutstandingEvents > 0) {\n // Already has an outstanding event, no need to buffer another one.\n }\n else {\n queue.notify();\n }\n },\n waitForNotification(signal) {\n return queue.waitForEvent(signal);\n }\n };\n}\nexport class EventQueue {\n options;\n waitingConsumer;\n outstandingEvents;\n constructor(options = {}) {\n this.options = options;\n this.outstandingEvents = [];\n }\n /**\n * The amount of buffered events not yet dispatched to listeners.\n */\n get countOutstandingEvents() {\n return this.outstandingEvents.length;\n }\n notifyInner(dispatch) {\n const existing = this.waitingConsumer;\n this.waitingConsumer = undefined;\n const dispatchAndNotifyListeners = (waiter) => {\n dispatch(waiter);\n this.options.eventDelivered?.();\n };\n if (existing) {\n dispatchAndNotifyListeners(existing);\n }\n else {\n this.outstandingEvents.push(dispatchAndNotifyListeners);\n }\n }\n notify(value) {\n this.notifyInner((l) => l.resolve(value));\n }\n notifyError(error) {\n this.notifyInner((l) => l.reject(error));\n }\n waitForEvent(signal) {\n return new Promise((resolve, reject) => {\n if (this.waitingConsumer != null) {\n throw new Error('Illegal call to waitForEvent, already has a waiter.');\n }\n const complete = () => {\n signal?.removeEventListener('abort', onAbort);\n };\n const onAbort = () => {\n complete();\n this.waitingConsumer = undefined;\n resolve(undefined);\n };\n const waiter = {\n resolve: (value) => {\n complete();\n resolve(value);\n },\n reject: (error) => {\n complete();\n reject(error);\n }\n };\n if (signal.aborted) {\n resolve(undefined);\n }\n else if (this.countOutstandingEvents > 0) {\n const [event] = this.outstandingEvents.splice(0, 1);\n event(waiter);\n }\n else {\n this.waitingConsumer = waiter;\n signal.addEventListener('abort', onAbort);\n }\n });\n }\n /**\n * Creates an async iterable backed by event queues.\n *\n * @param run A function invoked for every new listener. It receives a queue backing the async iterator.\n * @param abort An additional abort signal. The `run` callback will also be aborted when `AsyncIterator.return` is\n * called.\n * @returns An object conforming to the async iterable protocol.\n */\n static queueBasedAsyncIterable(run, abort) {\n return {\n [symbolAsyncIterator]: () => {\n const queue = new EventQueue();\n const controller = new AbortController();\n function dispose() {\n controller.abort();\n abort?.removeEventListener('abort', dispose);\n }\n if (abort) {\n if (abort.aborted) {\n controller.abort();\n }\n else {\n abort.addEventListener('abort', dispose);\n }\n }\n run(queue, controller.signal);\n return {\n async next() {\n const event = await queue.waitForEvent(controller.signal);\n return event == null ? doneResult : valueResult(event);\n },\n async return() {\n dispose();\n return doneResult;\n }\n };\n }\n };\n }\n}\n//# sourceMappingURL=async.js.map","import { BaseObserver, LogLevels } from '@powersync/common';\nimport { PSInternalTable } from './BucketStorageAdapter.js';\nimport { CrudEntryImpl } from './CrudEntry.js';\nimport { MAX_OP_ID } from '../../../constants.js';\n/**\n * @internal\n */\nexport class SqliteBucketStorage extends BaseObserver {\n db;\n logger;\n tableNames;\n updateListener;\n _clientId;\n constructor(db, logger) {\n super();\n this.db = db;\n this.logger = logger;\n this.tableNames = new Set();\n this.updateListener = db.registerListener({\n tablesUpdated: ({ tables }) => {\n if (tables.includes(PSInternalTable.CRUD)) {\n this.iterateListeners((l) => l.crudUpdate?.());\n }\n }\n });\n }\n async init() {\n const existingTableRows = await this.db.getAll(`SELECT name FROM sqlite_master WHERE type='table' AND name GLOB 'ps_data_*'`);\n for (const row of existingTableRows ?? []) {\n this.tableNames.add(row.name);\n }\n }\n async dispose() {\n this.updateListener?.();\n }\n async _getClientId() {\n const row = await this.db.get('SELECT powersync_client_id() as client_id');\n return row['client_id'];\n }\n getClientId() {\n if (this._clientId == null) {\n this._clientId = this._getClientId();\n }\n return this._clientId;\n }\n getMaxOpId() {\n return MAX_OP_ID;\n }\n async updateLocalTarget(cb) {\n const rs1 = await this.db.getAll(\"SELECT target_op FROM ps_buckets WHERE name = '$local' AND target_op = CAST(? as INTEGER)\", [MAX_OP_ID]);\n if (!rs1.length) {\n // Nothing to update\n return false;\n }\n const rs = await this.db.getOptional(\"SELECT seq FROM main.sqlite_sequence WHERE name = 'ps_crud'\");\n if (!rs) {\n // Nothing to update\n return false;\n }\n const seqBefore = rs.seq;\n const opId = await cb();\n return this.writeTransaction(async (tx) => {\n const anyData = await tx.execute('SELECT 1 FROM ps_crud LIMIT 1');\n if (anyData.rows?.length) {\n // if isNotEmpty\n this.logger.log({\n level: LogLevels.debug,\n message: `New data uploaded since write checkpoint ${opId} - need new write checkpoint`\n });\n return false;\n }\n const { seq: seqAfter } = await tx.get(\"SELECT seq FROM main.sqlite_sequence WHERE name = 'ps_crud'\");\n if (seqAfter != seqBefore) {\n this.logger.log({\n level: LogLevels.debug,\n message: `New data uploaded since write checpoint ${opId} - need new write checkpoint (sequence updated)`\n });\n // New crud data may have been uploaded since we got the checkpoint. Abort.\n return false;\n }\n this.logger.log({\n level: LogLevels.debug,\n message: `Updating target write checkpoint to ${opId}`\n });\n await tx.execute(\"UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'\", [opId]);\n return true;\n });\n }\n async nextCrudItem() {\n const next = await this.db.getOptional('SELECT * FROM ps_crud ORDER BY id ASC LIMIT 1');\n if (!next) {\n return;\n }\n return CrudEntryImpl.fromRow(next);\n }\n async hasCrud() {\n const anyData = await this.db.getOptional('SELECT 1 FROM ps_crud LIMIT 1');\n return !!anyData;\n }\n /**\n * Get a batch of objects to send to the server.\n * When the objects are successfully sent to the server, call .complete()\n */\n async getCrudBatch(limit = 100) {\n if (!(await this.hasCrud())) {\n return null;\n }\n const crudResult = await this.db.getAll('SELECT * FROM ps_crud ORDER BY id ASC LIMIT ?', [limit]);\n const all = [];\n for (const row of crudResult) {\n all.push(CrudEntryImpl.fromRow(row));\n }\n if (all.length === 0) {\n return null;\n }\n const last = all[all.length - 1];\n return {\n crud: all,\n haveMore: true,\n complete: async (writeCheckpoint) => {\n return this.writeTransaction(async (tx) => {\n await tx.execute('DELETE FROM ps_crud WHERE id <= ?', [last.clientId]);\n if (writeCheckpoint) {\n const crudResult = await tx.execute('SELECT 1 FROM ps_crud LIMIT 1');\n if (crudResult.rows?.length) {\n await tx.execute(\"UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'\", [\n writeCheckpoint\n ]);\n }\n }\n else {\n await tx.execute(\"UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'\", [\n this.getMaxOpId()\n ]);\n }\n });\n }\n };\n }\n async writeTransaction(callback, options) {\n return this.db.writeTransaction(callback, options);\n }\n async control(op, payload) {\n return await this.writeTransaction(async (tx) => {\n const { rawRows } = await tx.executeRaw('SELECT powersync_control(?, ?)', [op, payload]);\n return rawRows[0][0];\n });\n }\n async hasMigratedSubkeys() {\n const { r } = await this.db.get('SELECT EXISTS(SELECT * FROM ps_kv WHERE key = ?) as r', [\n SqliteBucketStorage._subkeyMigrationKey\n ]);\n return r != 0;\n }\n async migrateToFixedSubkeys() {\n await this.writeTransaction(async (tx) => {\n await tx.execute('UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);');\n await tx.execute('INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);', [\n SqliteBucketStorage._subkeyMigrationKey,\n '1'\n ]);\n });\n }\n static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';\n}\n//# sourceMappingURL=SqliteBucketStorage.js.map","/**\n * Calls to Abortcontroller.abort(reason: any) will result in the\n * `reason` being thrown. This is not necessarily an error,\n * but extends error for better logging purposes.\n *\n * @internal\n */\nexport class AbortOperation extends Error {\n reason;\n constructor(reason) {\n super(reason);\n this.reason = reason;\n // Set the prototype explicitly\n Object.setPrototypeOf(this, AbortOperation.prototype);\n // Capture stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, AbortOperation);\n }\n }\n}\n//# sourceMappingURL=AbortOperation.js.map","// Note: This file gets updated by tool/update_version.js script as part of the Changesets release workflow.\n// The update happens in the changesets PR, before the package is built.\nexport const POWERSYNC_JS_VERSION = 'unset before initial release';\n//# sourceMappingURL=version.js.map","import { FetchStrategy, LogLevels } from '@powersync/common';\nimport { AbortOperation } from '../../../utils/AbortOperation.js';\nimport { doneResult, extractBsonObjects, extractJsonLines } from '../../../utils/stream_transform.js';\nimport { EventQueue } from '../../../utils/async.js';\nimport { POWERSYNC_JS_VERSION } from '../../../version.js';\nconst POWERSYNC_TRAILING_SLASH_MATCH = /\\/+$/;\nconst webSocketPlatform = {\n LogLevels,\n EventQueue,\n AbortOperation\n};\nexport function lazyFetchImplementation(getFetch) {\n let resolved;\n return (request) => {\n const fetch = (resolved ??= getFetch());\n return fetch(request);\n };\n}\n/**\n * @internal\n */\nexport class AbstractRemote {\n connector;\n logger;\n credentials = null;\n constructor(connector, logger) {\n this.connector = connector;\n this.logger = logger;\n }\n /**\n * Get credentials currently cached, or fetch new credentials if none are\n * available.\n *\n * These credentials may have expired already.\n */\n async getCredentials() {\n if (this.credentials) {\n return this.credentials;\n }\n return this.prefetchCredentials();\n }\n /**\n * Fetch a new set of credentials and cache it.\n *\n * Until this call succeeds, `getCredentials` will still return the\n * old credentials.\n *\n * This may be called before the current credentials have expired.\n */\n async prefetchCredentials() {\n this.credentials = await this.fetchCredentials();\n return this.credentials;\n }\n /**\n * Get credentials for PowerSync.\n *\n * This should always fetch a fresh set of credentials - don't use cached\n * values.\n */\n async fetchCredentials() {\n const credentials = await this.connector.fetchCredentials();\n if (credentials?.endpoint.match(POWERSYNC_TRAILING_SLASH_MATCH)) {\n throw new Error(`A trailing forward slash \"/\" was found in the fetchCredentials endpoint: \"${credentials.endpoint}\". Remove the trailing forward slash \"/\" to fix this error.`);\n }\n return credentials;\n }\n /***\n * Immediately invalidate credentials.\n *\n * This may be called when the current credentials have expired.\n */\n invalidateCredentials() {\n this.credentials = null;\n this.connector.invalidateCredentials?.();\n }\n getUserAgent() {\n return `powersync-js/${POWERSYNC_JS_VERSION}`;\n }\n async buildRequest(path) {\n const credentials = await this.getCredentials();\n if (credentials != null && (credentials.endpoint == null || credentials.endpoint == '')) {\n throw new Error('PowerSync endpoint not configured');\n }\n else if (credentials?.token == null || credentials?.token == '') {\n const error = new Error(`Not signed in`);\n error.status = 401;\n throw error;\n }\n const userAgent = this.getUserAgent();\n return {\n url: credentials.endpoint + path,\n headers: {\n 'content-type': 'application/json',\n Authorization: `Token ${credentials.token}`,\n 'x-user-agent': userAgent\n },\n userAgent,\n path\n };\n }\n async get(path, headers) {\n const request = await this.buildRequest(path);\n const res = await this.fetch({\n resource: request.url,\n request: {\n method: 'GET',\n headers: {\n ...headers,\n ...request.headers\n }\n },\n expectStreamingResponse: false\n });\n if (res.status === 401) {\n this.invalidateCredentials();\n }\n if (!res.ok) {\n throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);\n }\n return res.json();\n }\n /**\n * @returns A text decoder decoding UTF-8. This is a method to allow patching it for Hermes which doesn't support the\n * builtin, without forcing us to bundle a polyfill with `@powersync/common`.\n */\n createTextDecoder() {\n return new TextDecoder();\n }\n createSocket(url) {\n return new WebSocket(url);\n }\n /**\n * Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.\n *\n * The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.\n */\n async socketStreamRaw(options) {\n const support = await this.loadWebSocketSupport(webSocketPlatform);\n const request = await this.buildRequest(options.path);\n request.url = request.url.replace(/^https?:\\/\\//, function (match) {\n return match === 'https://' ? 'wss://' : 'ws://';\n });\n const { fetchStrategy = FetchStrategy.Buffered, abortSignal, data } = options;\n return await support.webSocketSyncStream({\n remote: this,\n buffered: fetchStrategy == FetchStrategy.Buffered,\n abortSignal,\n requestPayload: data,\n request\n });\n }\n /**\n * Posts a `/sync/stream` request, asserts that it completes successfully and returns the streaming response as an\n * async iterator of byte blobs.\n *\n * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.\n */\n async fetchStreamRaw(options) {\n const { data, path, abortSignal } = options;\n const request = await this.buildRequest(path);\n /**\n * This abort controller will abort pending fetch requests.\n * If the request has resolved, it will be used to close the readable stream.\n * Which will cancel the network request.\n *\n * This nested controller is required since:\n * Aborting the active fetch request while it is being consumed seems to throw\n * an unhandled exception on the window level.\n */\n if (abortSignal.aborted) {\n throw new AbortOperation('Abort request received before making fetchStreamRaw request');\n }\n const controller = new AbortController();\n let reader = null;\n abortSignal.addEventListener('abort', () => {\n const reason = abortSignal.reason ??\n new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.');\n if (reader == null) {\n // Only abort via the abort controller if the request has not resolved yet\n controller.abort(reason);\n }\n else {\n reader.cancel(reason).catch(() => {\n // Cancelling the reader might rethrow an exception we would have handled by throwing in next(). So we can\n // ignore it here.\n });\n }\n });\n let res;\n let responseIsBson = false;\n try {\n const ndJson = 'application/x-ndjson';\n const bson = 'application/vnd.powersync.bson-stream';\n res = await this.fetch({\n resource: request.url,\n request: {\n method: 'POST',\n headers: {\n ...request.headers,\n accept: `${bson};q=0.9,${ndJson};q=0.8`\n },\n body: JSON.stringify(data),\n signal: controller.signal,\n cache: 'no-store'\n },\n expectStreamingResponse: true\n });\n if (!res.ok || !res.body) {\n const text = await res.text();\n const error = new Error(`HTTP ${res.statusText}: ${text}`);\n error.status = res.status;\n this.logger.log({\n level: LogLevels.error,\n message: `Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`,\n error\n });\n throw error;\n }\n const contentType = res.headers.get('content-type');\n responseIsBson = contentType == bson;\n }\n catch (ex) {\n if (ex.name == 'AbortError') {\n throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);\n }\n throw ex;\n }\n reader = res.body.getReader();\n const stream = {\n next: async () => {\n if (controller.signal.aborted) {\n return doneResult;\n }\n try {\n return await reader.read();\n }\n catch (ex) {\n if (controller.signal.aborted) {\n // .read() completes with an error if we cancel the reader, which we do to disconnect. So this is just\n // things working as intended, we can return a done event and consider the exception handled.\n return doneResult;\n }\n throw ex;\n }\n }\n };\n return { isBson: responseIsBson, stream };\n }\n /**\n * Posts a `/sync/stream` request.\n *\n * Depending on the `Content-Type` of the response, this returns strings for sync lines or encoded BSON documents as\n * `Uint8Array`s.\n */\n async fetchStream(options) {\n const { isBson, stream } = await this.fetchStreamRaw(options);\n if (isBson) {\n return extractBsonObjects(stream);\n }\n else {\n return extractJsonLines(stream, this.createTextDecoder());\n }\n }\n}\n//# sourceMappingURL=AbstractRemote.js.map","export function isInterruptingInstruction(instruction) {\n return 'EstablishSyncStream' in instruction || 'CloseSyncStream' in instruction;\n}\n//# sourceMappingURL=core-instruction.js.map","import { LogLevels, SyncStreamConnectionMethod, BaseObserver } from '@powersync/common';\nimport { AbortOperation } from '../../../utils/AbortOperation.js';\nimport { PowerSyncControlCommand } from '../bucket/BucketStorageAdapter.js';\nimport { isInterruptingInstruction } from './core-instruction.js';\nimport { doneResult, injectable, valueResult } from '../../../utils/stream_transform.js';\nimport { asyncNotifier } from '../../../utils/async.js';\nimport { SyncStatusSnapshot } from '../../../db/crud/SyncStatus.js';\n/**\n * @internal\n */\nexport var LockType;\n(function (LockType) {\n LockType[\"CRUD\"] = \"crud\";\n LockType[\"SYNC\"] = \"sync\";\n})(LockType || (LockType = {}));\n/**\n * @internal\n */\nexport class AbstractStreamingSyncImplementation extends BaseObserver {\n options;\n abortController;\n crudUpdateListener;\n streamingSyncPromise;\n logger;\n activeStreams;\n connectionMayHaveChanged = false;\n crudUploadNotifier = asyncNotifier();\n notifyCompletedUploads;\n handleActiveStreamsChange;\n syncStatus;\n constructor(options) {\n super();\n this.options = options;\n this.activeStreams = options.subscriptions;\n this.logger = options.logger;\n this.syncStatus = new SyncStatusSnapshot(null, {});\n this.abortController = null;\n }\n triggerCrudUpload() {\n this.crudUploadNotifier.notify();\n }\n async waitForReady() { }\n waitUntilStatusMatches(predicate) {\n return new Promise((resolve) => {\n if (predicate(this.syncStatus)) {\n resolve();\n return;\n }\n const l = this.registerListener({\n statusChanged: () => {\n if (predicate(this.syncStatus)) {\n resolve();\n l?.();\n }\n }\n });\n });\n }\n get lastSyncedAt() {\n const lastSynced = this.syncStatus.lastSyncedAt;\n return lastSynced && new Date(lastSynced);\n }\n get isConnected() {\n return this.syncStatus.connected;\n }\n async dispose() {\n super.dispose();\n this.crudUpdateListener?.();\n this.crudUpdateListener = undefined;\n }\n async getWriteCheckpoint() {\n const clientId = await this.options.adapter.getClientId();\n let path = `/write-checkpoint2.json?client_id=${clientId}`;\n const response = await this.options.remote.get(path);\n const checkpoint = response['data']['write_checkpoint'];\n this.logger.log({ level: LogLevels.debug, message: `Created write checkpoint: ${checkpoint}` });\n return checkpoint;\n }\n async crudUploadLoop(signal, options) {\n while (!signal.aborted) {\n await Promise.all([\n // Start the initial CRUD upload on connect. Then, keep polling until we're done.\n this._uploadAllCrud(signal, options),\n this.delayRetry(signal, options.crudUploadThrottleMs)\n ]);\n await this.crudUploadNotifier.waitForNotification(signal);\n }\n }\n async _uploadAllCrud(signal, options) {\n return this.obtainLock({\n type: LockType.CRUD,\n callback: async () => {\n /**\n * Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.\n */\n let checkedCrudItem;\n while (!signal.aborted) {\n try {\n /**\n * This is the first item in the FIFO CRUD queue.\n */\n const nextCrudItem = await this.options.adapter.nextCrudItem();\n if (nextCrudItem) {\n this.updateJsSyncState({ uploading: true });\n if (nextCrudItem.clientId == checkedCrudItem?.clientId) {\n // This will force a higher log level than exceptions which are caught here.\n this.logger.log({\n level: LogLevels.warn,\n message: `Potentially previously uploaded CRUD entries are still present in the upload queue.\nMake sure to handle uploads and complete CRUD transactions or batches by calling and awaiting their [.complete()] method.\nThe next upload iteration will be delayed.`\n });\n throw new Error('Delaying due to previously encountered CRUD item.');\n }\n checkedCrudItem = nextCrudItem;\n await this.options.uploadCrud();\n this.updateJsSyncState({ uploadError: undefined });\n }\n else {\n // Uploading is completed\n const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());\n if (neededUpdate) {\n this.notifyCompletedUploads?.();\n }\n else if (checkedCrudItem != null) {\n // Only log this if there was something to upload\n this.logger.log({ level: LogLevels.debug, message: 'Upload complete, no write checkpoint needed.' });\n }\n break;\n }\n }\n catch (ex) {\n checkedCrudItem = undefined;\n this.updateJsSyncState({ uploading: false, uploadError: ex });\n await this.delayRetry(signal, options.retryDelayMs);\n if (!this.isConnected) {\n // Exit the upload loop if the sync stream is no longer connected\n break;\n }\n this.logger.log({\n level: LogLevels.debug,\n message: `Caught exception when uploading. Upload will retry after a delay.`,\n error: ex\n });\n }\n finally {\n this.updateJsSyncState({ uploading: false });\n }\n }\n }\n });\n }\n async connect(options) {\n if (this.abortController) {\n await this.disconnect();\n }\n const controller = new AbortController();\n this.abortController = controller;\n this.streamingSyncPromise = Promise.all([\n this.crudUploadLoop(controller.signal, options).catch((error) => this.logger.log({ level: LogLevels.error, message: 'Error in crud upload loop', error })),\n this.streamingSync(controller.signal, options)\n ]);\n // Return a promise that resolves when the connection status is updated to indicate that we're connected. We do this\n // by waiting for connecting to be true and then false again.\n return new Promise((resolve) => {\n let sawStartOfConnection = false;\n const disposer = this.registerListener({\n statusChanged: (snapshot) => {\n if (snapshot.connecting) {\n sawStartOfConnection = true;\n }\n if (snapshot.downloadError != null) {\n this.logger.log({\n level: LogLevels.warn,\n message: 'Initial connect attempt did not successfully connect to server'\n });\n }\n else if (!sawStartOfConnection || snapshot.connecting) {\n // Still connecting.\n return;\n }\n disposer();\n resolve();\n }\n });\n });\n }\n async disconnect() {\n if (!this.abortController) {\n return;\n }\n // This might be called multiple times\n if (!this.abortController.signal.aborted) {\n this.abortController.abort(new AbortOperation('Disconnect has been requested'));\n }\n // Await any pending operations before completing the disconnect operation\n try {\n await this.streamingSyncPromise;\n }\n catch (ex) {\n // The operation might have failed, all we care about is if it has completed\n this.logger.log({ level: LogLevels.warn, message: 'Error in sync while disconnecting', error: ex });\n }\n this.streamingSyncPromise = undefined;\n this.abortController = null;\n this.markAsDisconnected();\n }\n markAsDisconnected() {\n const current = this.syncStatus.core;\n this.updateSyncStatus({\n connected: false,\n connecting: false,\n priority_status: current?.priority_status ?? [],\n downloading: null,\n streams: current?.streams ?? []\n });\n }\n async streamingSync(signal, options) {\n /**\n * Listen for CRUD updates and trigger upstream uploads\n */\n this.crudUpdateListener = this.options.adapter.registerListener({\n crudUpdate: () => this.triggerCrudUpload()\n });\n /**\n * Create a new abort controller which aborts items downstream.\n * This is needed to close any previous connections on exception.\n */\n let nestedAbortController = new AbortController();\n signal.addEventListener('abort', () => {\n /**\n * A request for disconnect was received upstream. Relay the request\n * to the nested abort controller.\n */\n nestedAbortController.abort(signal?.reason ?? new AbortOperation('Received command to disconnect from upstream'));\n this.crudUpdateListener?.();\n this.crudUpdateListener = undefined;\n this.markAsDisconnected();\n });\n /**\n * This loops runs until [retry] is false or the abort signal is set to aborted.\n * Aborting the nestedAbortController will:\n * - Abort any pending fetch requests\n * - Close any sync stream ReadableStreams (which will also close any established network requests)\n */\n while (true) {\n let shouldDelayRetry = true;\n let result = null;\n try {\n if (signal?.aborted) {\n break;\n }\n result = await this.streamingSyncIteration(nestedAbortController.signal, options);\n // Continue immediately, streamingSyncIteration will wait before completing if necessary.\n }\n catch (ex) {\n /**\n * Either:\n * - A network request failed with a failed connection or not OKAY response code.\n * - There was a sync processing error.\n * - The connection was aborted.\n * This loop will retry after a delay if the connection was not aborted.\n * The nested abort controller will cleanup any open network requests and streams.\n * The WebRemote should only abort pending fetch requests or close active Readable streams.\n */\n if (ex instanceof AbortOperation) {\n this.logger.log({ level: LogLevels.warn, message: 'Sync aborted', error: ex });\n shouldDelayRetry = false;\n // A disconnect was requested, we should not delay since there is no explicit retry\n }\n else if (this.connectionMayHaveChanged && ex.message?.indexOf('No iteration is active') >= 0) {\n this.connectionMayHaveChanged = false;\n this.logger.log({\n level: LogLevels.info,\n message: 'Sync error after changed connection, retrying immediately'\n });\n shouldDelayRetry = false;\n }\n else {\n this.logger.log({ level: LogLevels.error, message: 'Sync error', error: ex });\n }\n this.updateJsSyncState({ downloadError: ex });\n }\n finally {\n this.notifyCompletedUploads = undefined;\n if (!signal.aborted) {\n nestedAbortController.abort(new AbortOperation('Closing sync stream network requests before retry.'));\n nestedAbortController = new AbortController();\n }\n if (result?.immediateRestart != true) {\n this.markAsDisconnected();\n // On error, wait a little before retrying\n if (shouldDelayRetry) {\n await this.delayRetry(nestedAbortController.signal, options.retryDelayMs);\n }\n }\n }\n }\n // Mark as disconnected if here\n this.markAsDisconnected();\n }\n markConnectionMayHaveChanged() {\n // By setting this field, we'll immediately retry if the next sync event causes an error triggered by us not having\n // an active sync iteration on the connection in use.\n this.connectionMayHaveChanged = true;\n // This triggers a `powersync_control` invocation if a sync iteration is currently active. This is a cheap call to\n // make when no subscriptions have actually changed, we're mainly interested in this immediately throwing if no\n // iteration is active. That allows us to reconnect ASAP, instead of having to wait for the next sync line.\n this.handleActiveStreamsChange?.();\n }\n /**\n * Older versions of the JS SDK used to encode subkeys as JSON in `OplogEntry.toJSON`.\n * Because subkeys are always strings, this leads to quotes being added around them in `ps_oplog`.\n * While this is not a problem as long as it's done consistently, it causes issues when a database\n * created by the JS SDK is used with other SDKs, or (more likely) when the new Rust sync client\n * is enabled.\n *\n * So, we add a migration from the old key format (with quotes) to the new one (no quotes). The\n * migration is only triggered when necessary (for now). The function returns whether the new format\n * should be used, so that the JS SDK is able to write to updated databases.\n *\n * @param requireFixedKeyFormat - Whether we require the new format or also support the old one.\n * The Rust client requires the new subkey format.\n * @returns Whether the database is now using the new, fixed subkey format.\n */\n async requireKeyFormat(requireFixedKeyFormat) {\n const hasMigrated = await this.options.adapter.hasMigratedSubkeys();\n if (requireFixedKeyFormat && !hasMigrated) {\n await this.options.adapter.migrateToFixedSubkeys();\n return true;\n }\n else {\n return hasMigrated;\n }\n }\n streamingSyncIteration(signal, options) {\n return this.obtainLock({\n type: LockType.SYNC,\n signal,\n callback: async () => {\n // Validate app metadata\n const invalidMetadata = Object.entries(options.appMetadata).filter(([_, value]) => typeof value != 'string');\n if (invalidMetadata.length > 0) {\n throw new Error(`Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`);\n }\n await this.requireKeyFormat(true);\n return await this.rustSyncIteration(signal, options);\n }\n });\n }\n receiveSyncLines(data) {\n const { options, connection } = data;\n const remote = this.options.remote;\n const openInner = async () => {\n if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {\n return await remote.fetchStream(options);\n }\n else {\n return await this.options.remote.socketStreamRaw({\n ...options,\n ...{ fetchStrategy: connection.fetchStrategy }\n });\n }\n };\n let inner;\n let done = false;\n return {\n async next() {\n if (done) {\n return doneResult;\n }\n else if (inner == null) {\n inner = await openInner();\n // We're connected here, so we can tell the core extension about it.\n return valueResult({\n command: PowerSyncControlCommand.CONNECTION_STATE,\n payload: 'established'\n });\n }\n else {\n const event = await inner.next();\n if (event.done) {\n done = true;\n return valueResult({ command: PowerSyncControlCommand.CONNECTION_STATE, payload: 'end' });\n }\n else {\n return valueResult({\n command: typeof event.value == 'string'\n ? PowerSyncControlCommand.PROCESS_TEXT_LINE\n : PowerSyncControlCommand.PROCESS_BSON_LINE,\n payload: event.value\n });\n }\n }\n }\n };\n }\n async rustSyncIteration(signal, resolvedOptions) {\n const syncImplementation = this;\n const adapter = this.options.adapter;\n const remote = this.options.remote;\n let hideDisconnectOnRestart = false;\n let notifyTokenRefreshed;\n if (signal.aborted) {\n throw new AbortOperation('Connection request has been aborted');\n }\n const serializedSchema = this.options.serializedSchema;\n function startCommand() {\n const options = {\n parameters: resolvedOptions.params,\n app_metadata: resolvedOptions.appMetadata,\n active_streams: syncImplementation.activeStreams,\n include_defaults: resolvedOptions.includeDefaultStreams\n };\n if (serializedSchema) {\n options.schema = serializedSchema;\n }\n return invokePowerSyncControl(PowerSyncControlCommand.START, JSON.stringify(options));\n }\n async function stop() {\n const instructions = await invokePowerSyncControl(PowerSyncControlCommand.STOP);\n for (const instruction of instructions) {\n // We don't need to handle interrupting instructions since we're unconditionally ending the sync iteration at\n // this point.\n if (isInterruptingInstruction(instruction))\n continue;\n await handleInstruction(instruction);\n }\n }\n async function invokePowerSyncControl(op, payload) {\n const rawResponse = await adapter.control(op, payload ?? null);\n const payloadDesc = payload == null || typeof payload == 'string' ? payload : '<bytes>';\n syncImplementation.logger.log({\n level: LogLevels.trace,\n message: `powersync_control(${op}, ${payloadDesc}) -> ${rawResponse}`\n });\n if (op != PowerSyncControlCommand.STOP) {\n // Evidently we have a working connection here, otherwise powersync_control would have failed.\n syncImplementation.connectionMayHaveChanged = false;\n }\n return JSON.parse(rawResponse);\n }\n async function handleInstruction(instruction) {\n if ('LogLine' in instruction) {\n const { severity, line } = instruction.LogLine;\n switch (severity) {\n case 'DEBUG':\n syncImplementation.logger.log({\n level: LogLevels.debug,\n message: line\n });\n break;\n case 'INFO':\n syncImplementation.logger.log({\n level: LogLevels.info,\n message: line\n });\n break;\n case 'WARNING':\n syncImplementation.logger.log({\n level: LogLevels.warn,\n message: line\n });\n break;\n }\n }\n else if ('UpdateSyncStatus' in instruction) {\n syncImplementation.updateSyncStatus(instruction.UpdateSyncStatus.status);\n }\n else if ('FetchCredentials' in instruction) {\n if (instruction.FetchCredentials.did_expire) {\n remote.invalidateCredentials();\n }\n else {\n remote.invalidateCredentials();\n // Restart iteration after the credentials have been refreshed.\n remote.fetchCredentials().then((_) => {\n notifyTokenRefreshed?.();\n }, (err) => {\n syncImplementation.logger.log({\n level: LogLevels.warn,\n message: 'Could not prefetch credentials',\n error: err\n });\n });\n }\n }\n else if ('FlushFileSystem' in instruction) {\n // Not necessary on JS platforms.\n }\n else if ('DidCompleteSync' in instruction) {\n syncImplementation.updateJsSyncState({ downloadError: undefined });\n }\n }\n try {\n const defaultResult = { immediateRestart: false };\n // Pending sync lines received from the service, as well as local events that trigger a powersync_control\n // invocation (local events include refreshed tokens and completed uploads).\n // This is a single data stream so that we can handle all control calls from a single place.\n let controlInvocations = null;\n for (const startInstruction of await startCommand()) {\n if ('EstablishSyncStream' in startInstruction) {\n const syncOptions = {\n path: '/sync/stream',\n abortSignal: signal,\n data: startInstruction.EstablishSyncStream.request\n };\n controlInvocations = injectable(syncImplementation.receiveSyncLines({\n options: syncOptions,\n connection: resolvedOptions\n }));\n }\n else if ('CloseSyncStream' in startInstruction) {\n return defaultResult;\n }\n else {\n await handleInstruction(startInstruction);\n }\n }\n if (controlInvocations == null)\n return defaultResult;\n this.notifyCompletedUploads = () => {\n controlInvocations.inject({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });\n };\n this.handleActiveStreamsChange = () => {\n controlInvocations.inject({\n command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,\n payload: JSON.stringify(this.activeStreams)\n });\n };\n notifyTokenRefreshed = () => {\n controlInvocations.inject({\n command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED\n });\n };\n let hadSyncLine = false;\n loop: while (true) {\n const { done, value } = await controlInvocations.next();\n if (done)\n break;\n if (!hadSyncLine) {\n // Trigger a local CRUD upload when the first sync line has been received, this allows uploading local changes\n // that have been made while offline or disconnected.\n if (value.command == PowerSyncControlCommand.PROCESS_TEXT_LINE ||\n value.command == PowerSyncControlCommand.PROCESS_BSON_LINE) {\n hadSyncLine = true;\n this.triggerCrudUpload?.();\n }\n }\n const instructions = await invokePowerSyncControl(value.command, value.payload);\n for (const instruction of instructions) {\n if ('EstablishSyncStream' in instruction) {\n throw new Error('Received EstablishSyncStream while already connected.');\n }\n else if ('CloseSyncStream' in instruction) {\n hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;\n break loop;\n }\n else {\n await handleInstruction(instruction);\n }\n }\n }\n }\n finally {\n this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;\n notifyTokenRefreshed = undefined;\n await stop();\n }\n return { immediateRestart: hideDisconnectOnRestart };\n }\n updateSyncStatus(core, jsState) {\n const updated = new SyncStatusSnapshot(core, {\n ...this.syncStatus.jsState,\n ...jsState\n });\n if (!this.syncStatus.isEqual(updated)) {\n this.syncStatus = updated;\n // Only trigger this is there was a change\n this.iterateListeners((cb) => cb.statusChanged?.(updated));\n }\n }\n updateJsSyncState(state) {\n this.updateSyncStatus(this.syncStatus.core, state);\n }\n async delayRetry(signal, delay) {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n // If the signal is already aborted, resolve immediately\n resolve();\n return;\n }\n let timeoutId;\n const endDelay = () => {\n resolve();\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n }\n signal?.removeEventListener('abort', endDelay);\n };\n signal?.addEventListener('abort', endDelay, { once: true });\n timeoutId = setTimeout(endDelay, delay);\n });\n }\n updateSubscriptions(subscriptions) {\n this.activeStreams = subscriptions;\n this.handleActiveStreamsChange?.();\n }\n}\n//# sourceMappingURL=AbstractStreamingSyncImplementation.js.map","/**\n * Thrown when an underlying database connection is closed.\n * This is particularly relevant when worker connections are marked as closed while\n * operations are still in progress.\n *\n * @internal\n */\nexport class ConnectionClosedError extends Error {\n static NAME = 'ConnectionClosedError';\n static MATCHES(input) {\n /**\n * If there are weird package issues which cause multiple versions of classes to be present, the instanceof\n * check might fail. This also performs a failsafe check.\n * This might also happen if the Error is serialized and parsed over a bridging channel like a MessagePort.\n */\n return (input instanceof ConnectionClosedError || (input instanceof Error && input.name == ConnectionClosedError.NAME));\n }\n constructor(message) {\n super(message);\n this.name = ConnectionClosedError.NAME;\n }\n}\n//# sourceMappingURL=ConnectionClosedError.js.map","import { Mutex } from '@powersync/shared-internals';\n/**\n * A wrapper around a {@link RawSqliteConnection} allowing multiple tabs to access it.\n *\n * To allow potentially concurrent accesses from different clients, this requires a local mutex implementation here.\n *\n * Note that instances of this class are not safe to proxy across context boundaries with comlink! We need to be able to\n * rely on mutexes being returned reliably, so additional checks to detect say a client tab closing are required to\n * avoid deadlocks.\n */\nexport class ConcurrentSqliteConnection {\n inner;\n /**\n * An outer mutex ensuring at most one {@link ConnectionLeaseToken} can exist for this connection at a time.\n *\n * If null, we'll use navigator locks instead.\n */\n leaseMutex;\n /**\n * @param needsNavigatorLocks Whether access to the database needs an additional navigator lock guard.\n *\n * While {@link ConcurrentSqliteConnection} prevents concurrent access to a database _connection_, it's possible we\n * might have multiple connections to the same physical database (e.g. if multiple tabs use dedicated workers).\n * In those setups, we use navigator locks instead of an internal mutex to guard access..\n */\n constructor(inner, needsNavigatorLocks) {\n this.inner = inner;\n this.leaseMutex = needsNavigatorLocks ? null : new Mutex();\n }\n get options() {\n return this.inner.options;\n }\n acquireMutex(abort) {\n if (this.leaseMutex) {\n return this.leaseMutex.acquire(abort);\n }\n return new Promise((resolve, reject) => {\n const options = { signal: abort };\n navigator.locks\n .request(`db-lock-${this.options.filename}`, options, (_) => {\n return new Promise((returnLock) => {\n return resolve(() => {\n returnLock();\n });\n });\n })\n .catch(reject);\n });\n }\n // Unsafe, unguarded access to the SQLite connection.\n unsafeUseInner() {\n return this.inner;\n }\n /**\n * @returns A {@link ConnectionLeaseToken}. Until that token is returned, no other client can use the database.\n */\n async acquireConnection(abort) {\n const returnMutex = await this.acquireMutex(abort);\n const token = new ConnectionLeaseToken(returnMutex, this.inner);\n try {\n // Assert that the inner connection is initialized at this point, fail early if it's not.\n this.inner.requireSqlite();\n // If a previous client was interrupted in the middle of a transaction AND this is a shared worker, it's possible\n // for the connection to still be in a transaction. To avoid inconsistent state, we roll back connection leases\n // that haven't been comitted.\n if (!this.inner.isAutoCommit()) {\n await this.inner.executeRaw('ROLLBACK');\n }\n }\n catch (e) {\n returnMutex();\n throw e;\n }\n return token;\n }\n async close() {\n const returnMutex = await this.acquireMutex();\n try {\n await this.inner.close();\n }\n finally {\n returnMutex();\n }\n }\n}\n/**\n * An instance representing temporary exclusive access to a {@link ConcurrentSqliteConnection}.\n */\nexport class ConnectionLeaseToken {\n returnMutex;\n connection;\n /** Ensures that the client with access to this token can't run statements concurrently. */\n useMutex = new Mutex();\n closed = false;\n constructor(returnMutex, connection) {\n this.returnMutex = returnMutex;\n this.connection = connection;\n }\n /**\n * Returns this lease, allowing another client to use the database connection.\n */\n async returnLease() {\n await this.useMutex.runExclusive(async () => {\n if (!this.closed) {\n this.closed = true;\n this.returnMutex();\n }\n });\n }\n /**\n * This should only be used internally, since the callback must not use the raw connection after resolving.\n */\n async use(callback) {\n return await this.useMutex.runExclusive(async () => {\n if (this.closed) {\n throw new Error('lease token has already been closed');\n }\n return await callback(this.connection);\n });\n }\n}\n//# sourceMappingURL=ConcurrentConnection.js.map","import { LogLevels } from '@powersync/common';\nimport * as Comlink from 'comlink';\nimport { DatabaseServer } from '../../db/adapters/wa-sqlite/DatabaseServer.js';\nimport { getNavigatorLocks } from '../../shared/navigator.js';\nimport { RawSqliteConnection } from '../../db/adapters/wa-sqlite/RawSqliteConnection.js';\nimport { ConcurrentSqliteConnection } from '../../db/adapters/wa-sqlite/ConcurrentConnection.js';\nconst OPEN_DB_LOCK = 'open-wasqlite-db';\n/**\n * Shared state to manage multiple database connections hosted by a worker.\n */\nexport class MultiDatabaseServer {\n logger;\n activeDatabases = new Map();\n constructor(logger) {\n this.logger = logger;\n }\n async handleConnection({ logLevel, database, lockName }) {\n const logger = {\n log: (record) => {\n if (record.level >= logLevel)\n this.logger.log(record);\n }\n };\n return Comlink.proxy(await this.openConnectionLocally(logger, database, lockName));\n }\n async connectToExisting(name, lockName) {\n return getNavigatorLocks().request(OPEN_DB_LOCK, async () => {\n const server = this.activeDatabases.get(name);\n if (server == null) {\n throw new Error(`connectToExisting(${name}) failed because the worker doesn't own a database with that name.`);\n }\n return Comlink.proxy(await server.connect(lockName));\n });\n }\n async openConnectionLocally(logger, options, lockName) {\n // Especially on Firefox, we're sometimes seeing \"NoModificationAllowedError\"s when opening OPFS databases we can\n // work around by retrying.\n const maxAttempts = 3;\n let server;\n for (let count = 0; count < maxAttempts - 1; count++) {\n try {\n server = await this.databaseOpenAttempt(logger, options);\n }\n catch (error) {\n this.logger.log({\n level: LogLevels.warn,\n message: `Attempt ${count + 1} of ${maxAttempts} to open database failed, retrying in 1 second...`,\n error\n });\n await new Promise((resolve) => setTimeout(resolve, 1000));\n }\n }\n // Final attempt if we haven't been able to open the server - rethrow errors if we still can't open.\n server ??= await this.databaseOpenAttempt(logger, options);\n return server.connect(lockName);\n }\n async databaseOpenAttempt(logger, options) {\n return getNavigatorLocks().request(OPEN_DB_LOCK, async () => {\n const { filename } = options;\n let server = this.activeDatabases.get(filename);\n if (server == null) {\n // We don't need navigator locks for shared workers because all queries run in this shared worker exclusively.\n // For read-only connections, we use a VFS that supports concurrent reads (so a single lock on the connection is\n // fine).\n const needsNavigatorLocks = !(isSharedWorker || options.readonly);\n const connection = new RawSqliteConnection(options);\n const withSafeConcurrency = new ConcurrentSqliteConnection(connection, needsNavigatorLocks);\n // Initializing the RawSqliteConnection will run some pragmas that might write to the database file, so we want\n // to do that in an exclusive lock. Note that OPEN_DB_LOCK is not enough for that, as another tab might have\n // already created a connection (and is thus outside of OPEN_DB_LOCK) while currently writing to it.\n const returnLease = await withSafeConcurrency.acquireMutex();\n try {\n await connection.init();\n }\n catch (e) {\n returnLease();\n await connection.close();\n throw e;\n }\n returnLease();\n const onClose = () => this.activeDatabases.delete(filename);\n server = new DatabaseServer({\n inner: withSafeConcurrency,\n logger,\n onClose\n });\n this.activeDatabases.set(filename, server);\n }\n return server;\n });\n }\n closeAll() {\n const existingDatabases = [...this.activeDatabases.values()];\n return Promise.all(existingDatabases.map((db) => {\n db.forceClose();\n }));\n }\n}\nexport const isSharedWorker = 'SharedWorkerGlobalScope' in globalThis;\n//# sourceMappingURL=MultiDatabaseServer.js.map","import { LogLevels } from '@powersync/common';\nimport { AbstractRemote } from '@powersync/shared-internals';\nimport { getUserAgentInfo } from './userAgent.js';\nexport class WebRemote extends AbstractRemote {\n connector;\n constructor(connector, logger) {\n super(connector, logger);\n this.connector = connector;\n }\n fetch({ resource, request }) {\n return fetch(resource, request);\n }\n async loadWebSocketSupport(platform) {\n if (!websockets) {\n // loadWebSocketSupport being called concurrently is safe, the import resolves to the same module in that case.\n const module = await import('@powersync/shared-internals/websockets');\n websockets = new module.WebSocketSupport(platform);\n }\n return websockets;\n }\n getUserAgent() {\n let ua = [super.getUserAgent(), `powersync-web`];\n try {\n ua.push(...getUserAgentInfo());\n }\n catch (error) {\n this.logger.log({ level: LogLevels.warn, message: 'Failed to get user agent info', error });\n }\n return ua.join(' ');\n }\n}\nlet websockets;\n//# sourceMappingURL=WebRemote.js.map","/**\n * Get a minimal representation of browser, version and operating system.\n *\n * The goal is to get enough environemnt info to reproduce issues, but no\n * more.\n */\nexport function getUserAgentInfo(nav) {\n nav ??= navigator;\n const browser = getBrowserInfo(nav);\n const os = getOsInfo(nav);\n // The cast below is to cater for TypeScript < 5.5.0\n return [browser, os].filter((v) => v != null);\n}\nfunction getBrowserInfo(nav) {\n const brands = nav.userAgentData?.brands;\n if (brands != null) {\n const tests = [\n { name: 'Google Chrome', value: 'Chrome' },\n { name: 'Opera', value: 'Opera' },\n { name: 'Edge', value: 'Edge' },\n { name: 'Chromium', value: 'Chromium' }\n ];\n for (let { name, value } of tests) {\n const brand = brands.find((b) => b.brand == name);\n if (brand != null) {\n return `${value}/${brand.version}`;\n }\n }\n }\n const ua = nav.userAgent;\n const regexps = [\n { re: /(?:firefox|fxios)\\/(\\d+)/i, value: 'Firefox' },\n { re: /(?:edg|edge|edga|edgios)\\/(\\d+)/i, value: 'Edge' },\n { re: /opr\\/(\\d+)/i, value: 'Opera' },\n { re: /(?:chrome|chromium|crios)\\/(\\d+)/i, value: 'Chrome' },\n { re: /version\\/(\\d+).*safari/i, value: 'Safari' }\n ];\n for (let { re, value } of regexps) {\n const match = re.exec(ua);\n if (match != null) {\n return `${value}/${match[1]}`;\n }\n }\n return null;\n}\nfunction getOsInfo(nav) {\n if (nav.userAgentData?.platform != null) {\n return nav.userAgentData.platform.toLowerCase();\n }\n const ua = nav.userAgent;\n const regexps = [\n { re: /windows/i, value: 'windows' },\n { re: /android/i, value: 'android' },\n { re: /linux/i, value: 'linux' },\n { re: /iphone|ipad|ipod/i, value: 'ios' },\n { re: /macintosh|mac os x/i, value: 'macos' }\n ];\n for (let { re, value } of regexps) {\n if (re.test(ua)) {\n return value;\n }\n }\n return null;\n}\n//# sourceMappingURL=userAgent.js.map","import { LogLevels } from '@powersync/common';\nimport { AbstractStreamingSyncImplementation, LockType } from '@powersync/shared-internals';\nimport { getNavigatorLocks } from '../../shared/navigator.js';\nexport class WebStreamingSyncImplementation extends AbstractStreamingSyncImplementation {\n constructor(options) {\n // Super will store and provide default values for options\n super(options);\n }\n get webOptions() {\n return this.options;\n }\n async obtainLock(lockOptions) {\n const identifier = `streaming-sync-${lockOptions.type}-${this.webOptions.identifier}`;\n if (lockOptions.type == LockType.SYNC) {\n this.logger.log({ level: LogLevels.debug, message: `requesting lock for ${identifier}` });\n }\n return getNavigatorLocks().request(identifier, { signal: lockOptions.signal }, lockOptions.callback);\n }\n}\n//# sourceMappingURL=WebStreamingSyncImplementation.js.map","import { LogLevels, createConsoleLogger } from '@powersync/common';\n/**\n * Broadcasts logs to all clients\n */\nexport class BroadcastLogger {\n clients;\n inner;\n currentLevel = LogLevels.info;\n sendBroadcasts = true;\n constructor(prefix, clients) {\n this.clients = clients;\n this.inner = createConsoleLogger({ prefix: prefix });\n }\n log(record) {\n this.inner.log(record);\n if (this.sendBroadcasts && record.level >= this.currentLevel) {\n const sanitized = this.sanitizeRecord(record);\n this.iterateClients((client) => client.clientProvider.log(sanitized));\n }\n }\n /**\n * Set the global log level.\n */\n setLevel(level) {\n this.inner.minLevel = level;\n this.currentLevel = level;\n }\n /**\n * Iterates all clients, catches individual client exceptions\n * and proceeds to execute for all clients.\n */\n async iterateClients(callback) {\n for (const client of this.clients) {\n try {\n await callback(client);\n }\n catch (ex) {\n console.error('Caught exception when iterating client', ex);\n }\n }\n }\n /**\n * Guards against any logging errors.\n * We don't want a logging exception to cause further issues upstream\n */\n sanitizeRecord(record) {\n if (!record.error) {\n return record;\n }\n let error;\n try {\n // Try and clone here first. If it fails it won't be passable over a MessagePort\n error = structuredClone(record.error);\n }\n catch (ex) {\n console.error(ex);\n error = 'Could not serialize log params. Check shared worker logs for more details.';\n }\n return {\n ...record,\n error\n };\n }\n}\n//# sourceMappingURL=BroadcastLogger.js.map","import { LockContext, DBAdapter, queryResultWithoutRows } from '@powersync/common';\nimport * as Comlink from 'comlink';\nimport { ConnectionClosedError } from '@powersync/shared-internals';\n/**\n * A single-connection {@link ConnectionPool} implementation based on a worker connection.\n */\nexport class DatabaseClient extends DBAdapter {\n options;\n config;\n #connection;\n #shareConnectionAbortController = new AbortController();\n #receiveTableUpdates;\n constructor(options, config) {\n super();\n this.options = options;\n this.config = config;\n this.#connection = {\n connection: options.connection,\n notifyRemoteClosed: options.remoteCanCloseUnexpectedly ? new AbortController() : undefined,\n traceQueries: config.debugMode === true\n };\n const { port1, port2 } = new MessageChannel();\n options.connection.setUpdateListener(Comlink.transfer(port1, [port1]));\n this.#receiveTableUpdates = port2;\n port2.onmessage = (event) => {\n const tables = event.data;\n const notification = {\n tables\n };\n this.iterateListeners((l) => {\n l.tablesUpdated && l.tablesUpdated(notification);\n });\n };\n }\n get name() {\n return this.config.dbFilename;\n }\n /**\n * Marks the remote as closed.\n *\n * This can sometimes happen outside of our control, e.g. when a shared worker requests a connection from a tab. When\n * it happens, all outstanding requests on this pool would never resolve. To avoid livelocks in this scenario, we\n * throw on all outstanding promises and forbid new calls.\n */\n markRemoteClosed() {\n // Can non-null assert here because this function is only supposed to be called when remoteCanCloseUnexpectedly was\n // set.\n this.#connection.notifyRemoteClosed.abort();\n }\n async close() {\n // This connection is no longer shared, so we can close locks held for shareConnection calls.\n this.#shareConnectionAbortController.abort();\n this.#receiveTableUpdates.close();\n await useConnectionState(this.#connection, (c) => c.close(), true);\n this.options.onClose?.();\n this.options.source?.[Comlink.releaseProxy]();\n }\n readLock(fn, options) {\n return this.#lock(false, fn, options);\n }\n writeLock(fn, options) {\n return this.#lock(true, fn, options);\n }\n async #lock(write, fn, options) {\n const token = await useConnectionState(this.#connection, (c) => c.requestAccess(write, options?.timeoutMs));\n try {\n return await fn(new ClientLockContext(this.#connection, token));\n }\n finally {\n await useConnectionState(this.#connection, (c) => c.completeAccess(token));\n }\n }\n async refreshSchema() {\n // Currently a no-op on the web.\n }\n async shareConnection() {\n /**\n * Hold a navigator lock in order to avoid features such as Chrome's frozen tabs,\n * or Edge's sleeping tabs from pausing the thread for this connection.\n * This promise resolves once a lock is obtained.\n * This lock will be held as long as this connection is open.\n * The `shareConnection` method should not be called on multiple tabs concurrently.\n */\n const abort = this.#shareConnectionAbortController;\n const source = this.options.source;\n if (source == null) {\n throw new Error(`shareConnection() is only available for connections based by workers.`);\n }\n await new Promise((resolve, reject) => navigator.locks\n .request(`shared-connection-${this.name}-${Date.now()}-${Math.round(Math.random() * 10000)}`, {\n signal: abort.signal\n }, async () => {\n resolve();\n // Free the lock when the connection is already closed.\n if (abort.signal.aborted) {\n return;\n }\n // Hold the lock while the shared connection is in use.\n await new Promise((releaseLock) => {\n abort.signal.addEventListener('abort', () => {\n releaseLock();\n });\n });\n })\n // We aren't concerned with abort errors here\n .catch((ex) => {\n if (ex.name == 'AbortError') {\n resolve();\n }\n else {\n reject(ex);\n }\n }));\n const newPort = await source[Comlink.createEndpoint]();\n return { port: newPort, identifier: this.name };\n }\n getConfiguration() {\n return this.config;\n }\n}\n/**\n * A {@link LockContext} implemented by sending commands to a worker.\n *\n * While an instance is active, it has exclusive access to the underlying database connection (as represented by its\n * token).\n */\nclass ClientLockContext extends LockContext {\n #connection;\n #token;\n constructor(connection, token) {\n super();\n this.#connection = connection;\n this.#token = token;\n }\n /**\n * Requests an operation from the worker, potentially tracing it if that option has been enabled.\n */\n async maybeTrace(fn, describeForTrace) {\n if (this.#connection.traceQueries) {\n const start = performance.now();\n const description = describeForTrace();\n try {\n const r = await useConnectionState(this.#connection, fn);\n performance.measure(`[SQL] ${description}`, { start });\n return r;\n }\n catch (e) {\n performance.measure(`[SQL] [ERROR: ${e.message}] ${description}`, { start });\n throw e;\n }\n }\n else {\n return useConnectionState(this.#connection, fn);\n }\n }\n async executeRaw(query, params) {\n return await this.#executeOnWorker(query, params);\n }\n async #executeOnWorker(query, params) {\n return this.maybeTrace((c) => c.execute(this.#token, query, params), () => query);\n }\n async executeBatch(query, params = []) {\n const results = await this.maybeTrace((c) => c.executeBatch(this.#token, query, params), () => `${query} (batch of ${params.length})`);\n const result = { insertId: undefined, rowsAffected: 0 };\n for (const source of results) {\n result.insertId = source.insertId;\n result.rowsAffected = (result.rowsAffected ?? 0) + source.rowsAffected;\n }\n return queryResultWithoutRows(result);\n }\n}\nasync function useConnectionState(state, workerPromise, fireActionOnAbort = false) {\n const controller = state.notifyRemoteClosed;\n if (controller) {\n return new Promise((resolve, reject) => {\n if (controller.signal.aborted) {\n reject(new ConnectionClosedError('Called operation on closed remote'));\n if (!fireActionOnAbort) {\n // Don't run the operation if we're going to reject\n // We might want to fire-and-forget the operation in some cases (like a close operation)\n return;\n }\n }\n function handleAbort() {\n reject(new ConnectionClosedError('Remote peer closed with request in flight'));\n }\n function completePromise(action) {\n controller.signal.removeEventListener('abort', handleAbort);\n action();\n }\n controller.signal.addEventListener('abort', handleAbort);\n workerPromise(state.connection)\n .then((data) => completePromise(() => resolve(data)))\n .catch((e) => completePromise(() => reject(e)));\n });\n }\n else {\n // Can't close, so just return the inner worker promise unguarded.\n return workerPromise(state.connection);\n }\n}\n//# sourceMappingURL=DatabaseClient.js.map","import { BaseObserver, DBAdapter, LogLevels, SyncStreamConnectionMethod } from '@powersync/common';\nimport { AbortOperation, ConnectionManager, SqliteBucketStorage, Mutex } from '@powersync/shared-internals';\nimport * as Comlink from 'comlink';\nimport { WebRemote } from '../../db/sync/WebRemote.js';\nimport { WebStreamingSyncImplementation } from '../../db/sync/WebStreamingSyncImplementation.js';\nimport { BroadcastLogger } from './BroadcastLogger.js';\nimport { DatabaseClient } from '../../db/adapters/wa-sqlite/DatabaseClient.js';\nimport { generateTabCloseSignal } from '../../shared/tab_close_signal.js';\n/**\n * @internal\n * Manual message events for shared sync clients\n */\nexport var SharedSyncClientEvent;\n(function (SharedSyncClientEvent) {\n /**\n * This client requests the shared sync manager should\n * close it's connection to the client.\n */\n SharedSyncClientEvent[\"CLOSE_CLIENT\"] = \"close-client\";\n SharedSyncClientEvent[\"CLOSE_ACK\"] = \"close-ack\";\n})(SharedSyncClientEvent || (SharedSyncClientEvent = {}));\n/**\n * HACK: The shared implementation wraps and provides its own\n * PowerSyncBackendConnector when generating the streaming sync implementation.\n * We provide this unused placeholder when connecting with the ConnectionManager.\n */\nconst CONNECTOR_PLACEHOLDER = {};\n/**\n * @internal\n * Shared sync implementation which runs inside a shared webworker\n */\nexport class SharedSyncImplementation extends BaseObserver {\n ports;\n isInitialized;\n statusListener;\n fetchCredentialsController;\n uploadDataController;\n syncParams;\n lastConnectOptions;\n portMutex;\n subscriptions = [];\n connectionManager;\n syncStatus;\n logger;\n database = this.generateReconnectableDatabase();\n constructor() {\n super();\n this.ports = [];\n this.syncParams = null;\n this.lastConnectOptions = undefined;\n this.portMutex = new Mutex();\n this.isInitialized = new Promise((resolve) => {\n const callback = this.registerListener({\n initialized: () => {\n resolve();\n callback?.();\n }\n });\n });\n this.logger = new BroadcastLogger('shared-sync', this.ports);\n this.connectionManager = new ConnectionManager({\n createSyncImplementation: async () => {\n await this.waitForReady();\n const sync = this.generateStreamingImplementation();\n const onDispose = sync.registerListener({\n statusChanged: (snapshot) => {\n this.syncStatus = snapshot;\n const json = snapshot.toJSON();\n this.ports.forEach((p) => p.clientProvider.statusChanged(json));\n }\n });\n return {\n sync,\n onDispose\n };\n },\n logger: this.logger,\n defaultConnectionMethod: SyncStreamConnectionMethod.HTTP\n });\n }\n get isConnected() {\n return this.connectionManager.syncStreamImplementation?.isConnected ?? false;\n }\n /**\n * Gets the last client port which we know is safe from unexpected closes.\n */\n async getLastWrappedPort() {\n // Find the last port which is not closing\n return await this.portMutex.runExclusive(() => {\n for (let i = this.ports.length - 1; i >= 0; i--) {\n if (!this.ports[i].isClosing) {\n return this.ports[i];\n }\n }\n return;\n });\n }\n /**\n * In some very rare cases a specific tab might not respond to requests.\n * This returns a random port which is not closing.\n */\n async getRandomWrappedPort() {\n return await this.portMutex.runExclusive(() => {\n const nonClosingPorts = this.ports.filter((p) => !p.isClosing);\n return nonClosingPorts[Math.floor(Math.random() * nonClosingPorts.length)];\n });\n }\n async waitUntilStatusMatches(predicate) {\n return this.withSyncImplementation(async (sync) => {\n return sync.waitUntilStatusMatches(predicate);\n });\n }\n async waitForReady() {\n return this.isInitialized;\n }\n collectActiveSubscriptions() {\n this.logger.log({ level: LogLevels.debug, message: 'Collecting active stream subscriptions across tabs' });\n const active = new Map();\n for (const port of this.ports) {\n for (const stream of port.currentSubscriptions) {\n const serializedKey = JSON.stringify(stream);\n active.set(serializedKey, stream);\n }\n }\n this.subscriptions = [...active.values()];\n this.logger.log({\n level: LogLevels.debug,\n message: `Collected stream subscriptions, ${JSON.stringify(this.subscriptions)}`\n });\n this.connectionManager.syncStreamImplementation?.updateSubscriptions(this.subscriptions);\n }\n updateSubscriptions(port, subscriptions) {\n port.currentSubscriptions = subscriptions;\n this.collectActiveSubscriptions();\n }\n setLogLevel(level) {\n this.logger.setLevel(level);\n }\n /**\n * Configures the DBAdapter connection and a streaming sync client.\n */\n async setParams(params) {\n await this.portMutex.runExclusive(async () => {\n this.collectActiveSubscriptions();\n });\n if (this.syncParams) {\n // Cannot modify already existing sync implementation params\n return;\n }\n // First time setting params\n this.syncParams = params;\n this.logger.sendBroadcasts = params.enableBroadcastLogs;\n // Ensure we have a usable database connection, the reconnectable database will connect lazily on first use.\n await this.database.readLock(async () => { });\n self.onerror = (event) => {\n // Share any uncaught events on the broadcast logger\n this.logger.log({\n level: LogLevels.error,\n message: 'Uncaught exception in PowerSync shared sync worker',\n error: event\n });\n };\n this.iterateListeners((l) => l.initialized?.());\n }\n async dispose() {\n await this.waitForReady();\n this.statusListener?.();\n return this.connectionManager.close();\n }\n /**\n * Connects to the PowerSync backend instance.\n * Multiple tabs can safely call this in their initialization.\n * The connection will simply be reconnected whenever a new tab\n * connects.\n */\n async connect(options, serializedSchema) {\n this.lastConnectOptions = options;\n return this.connectionManager.connect(CONNECTOR_PLACEHOLDER, options ?? {}, serializedSchema);\n }\n async disconnect() {\n return this.connectionManager.disconnect();\n }\n /**\n * Adds a new client tab's message port to the list of connected ports\n */\n async addPort(port) {\n return await this.portMutex.runExclusive(() => {\n const portProvider = {\n port,\n clientProvider: Comlink.wrap(port),\n currentSubscriptions: [],\n closeListeners: [],\n isClosing: false\n };\n this.ports.push(portProvider);\n // Give the newly connected client the latest status\n const status = this.syncStatus;\n if (status) {\n portProvider.clientProvider.statusChanged(status.toJSON());\n }\n return portProvider;\n });\n }\n /**\n * Removes a message port client from this manager's managed\n * clients.\n */\n async removePort(port) {\n // Ports might be removed faster than we can process them.\n port.isClosing = true;\n // Remove the port within a mutex context.\n // Warns if the port is not found. This should not happen in practice.\n // We return early if the port is not found.\n return await this.portMutex.runExclusive(async () => {\n const index = this.ports.findIndex((p) => p == port);\n if (index < 0) {\n this.logger.log({\n level: LogLevels.warn,\n message: `Could not remove port ${port} since it is not present in active ports.`\n });\n return () => { };\n }\n const trackedPort = this.ports[index];\n // Remove from the list of active ports\n this.ports.splice(index, 1);\n /**\n * The port might currently be in use. Any active functions might\n * not resolve. Abort them here.\n */\n [this.fetchCredentialsController, this.uploadDataController].forEach((abortController) => {\n if (abortController?.activePort == port) {\n abortController.controller.abort(new AbortOperation('Closing pending requests after client port is removed'));\n }\n });\n // Close the worker wrapped database connection, we can't accurately rely on this connection\n for (const closeListener of trackedPort.closeListeners) {\n await closeListener();\n }\n this.collectActiveSubscriptions();\n return () => trackedPort.clientProvider[Comlink.releaseProxy]();\n });\n }\n triggerCrudUpload() {\n this.withSyncImplementation(async (sync) => {\n sync.triggerCrudUpload();\n });\n }\n async getWriteCheckpoint() {\n return this.withSyncImplementation(async (sync) => {\n return sync.getWriteCheckpoint();\n });\n }\n async withSyncImplementation(callback) {\n await this.waitForReady();\n if (this.connectionManager.syncStreamImplementation) {\n return callback(this.connectionManager.syncStreamImplementation);\n }\n const sync = await new Promise((resolve) => {\n const dispose = this.connectionManager.registerListener({\n syncStreamCreated: (sync) => {\n resolve(sync);\n dispose?.();\n }\n });\n });\n return callback(sync);\n }\n generateStreamingImplementation() {\n // This should only be called after initialization has completed\n const syncParams = this.syncParams;\n // Create a new StreamingSyncImplementation for each connect call. This is usually done is all SDKs.\n return new WebStreamingSyncImplementation({\n adapter: new SqliteBucketStorage(this.database, this.logger),\n remote: new WebRemote({\n invalidateCredentials: async () => {\n const lastPort = await this.getLastWrappedPort();\n if (!lastPort) {\n throw new Error('No client port found to invalidate credentials');\n }\n try {\n this.logger.log({\n level: LogLevels.info,\n message: 'calling the last port client provider to invalidate credentials'\n });\n lastPort.clientProvider.invalidateCredentials();\n }\n catch (error) {\n this.logger.log({ level: LogLevels.error, message: 'error invalidating credentials', error });\n }\n },\n fetchCredentials: async () => {\n const lastPort = await this.getLastWrappedPort();\n if (!lastPort) {\n throw new Error('No client port found to fetch credentials');\n }\n return new Promise(async (resolve, reject) => {\n const abortController = new AbortController();\n this.fetchCredentialsController = {\n controller: abortController,\n activePort: lastPort\n };\n abortController.signal.onabort = reject;\n try {\n this.logger.log({\n level: LogLevels.info,\n message: 'calling the last port client provider for credentials'\n });\n resolve(await lastPort.clientProvider.fetchCredentials());\n }\n catch (ex) {\n reject(ex);\n }\n finally {\n this.fetchCredentialsController = undefined;\n }\n });\n }\n }, this.logger),\n uploadCrud: async () => {\n const lastPort = await this.getLastWrappedPort();\n if (!lastPort) {\n throw new Error('No client port found to upload crud');\n }\n return new Promise(async (resolve, reject) => {\n const abortController = new AbortController();\n this.uploadDataController = {\n controller: abortController,\n activePort: lastPort\n };\n // Resolving will make it retry\n abortController.signal.onabort = () => resolve();\n try {\n resolve(await lastPort.clientProvider.uploadCrud());\n }\n catch (ex) {\n reject(ex);\n }\n finally {\n this.uploadDataController = undefined;\n }\n });\n },\n ...syncParams.streamOptions,\n subscriptions: this.subscriptions,\n // Logger cannot be transferred just yet\n logger: this.logger\n });\n }\n /**\n * Requests a random client to share its database connection with us.\n */\n async openInternalDB(handleClosed) {\n const client = await this.getRandomWrappedPort();\n if (!client) {\n // Should not really happen in practice\n throw new Error(`Could not open DB connection since no client is connected.`);\n }\n // Fail-safe timeout for opening a database connection.\n const timeout = setTimeout(() => {\n abortController.abort();\n }, 10_000);\n /**\n * Handle cases where the client might close while opening a connection.\n */\n const abortController = new AbortController();\n const closeListener = () => {\n abortController.abort();\n };\n const removeCloseListener = () => {\n const index = client.closeListeners.indexOf(closeListener);\n if (index >= 0) {\n client.closeListeners.splice(index, 1);\n }\n };\n client.closeListeners.push(closeListener);\n const workerPort = await withAbort({\n action: () => client.clientProvider.getDBWorkerPort(),\n signal: abortController.signal,\n cleanupOnAbort: (port) => {\n port.close();\n }\n }).catch((ex) => {\n removeCloseListener();\n throw ex;\n });\n const remote = Comlink.wrap(workerPort);\n const identifier = this.syncParams.dbParams.dbFilename;\n const clientLockName = await generateTabCloseSignal();\n /**\n * The open could fail if the tab is closed while we're busy opening the database.\n * This operation is typically executed inside an exclusive portMutex lock.\n * We typically execute the closeListeners using the portMutex in a different context.\n * We can't rely on the closeListeners to abort the operation if the tab is closed.\n */\n const db = await withAbort({\n action: async () => {\n const clientView = await remote.connectToExisting({ identifier, lockName: clientLockName });\n return new DatabaseClient({\n connection: clientView,\n source: remote,\n // It's possible for this worker to outlive the client hosting the database for us. We need to be prepared for\n // that and ensure pending requests are aborted when the tab is closed.\n remoteCanCloseUnexpectedly: true\n }, this.syncParams.dbParams);\n },\n signal: abortController.signal,\n cleanupOnAbort: (db) => {\n db.close();\n }\n }).finally(() => {\n // We can remove the close listener here since we no longer need it past this point.\n removeCloseListener();\n });\n clearTimeout(timeout);\n client.closeListeners.push(async () => {\n this.logger.log({ level: LogLevels.info, message: 'Aborting open connection because associated tab closed.' });\n handleClosed(db);\n /**\n * Don't await this close operation. It might never resolve if the tab is closed.\n * We mark the remote as closed first, this will reject any pending requests.\n * We then call close. The close operation is configured to fire-and-forget, the main promise will reject immediately.\n */\n db.markRemoteClosed();\n db.close().catch((error) => this.logger.log({ level: LogLevels.warn, message: 'error closing database connection', error }));\n });\n return db;\n }\n generateReconnectableDatabase() {\n const syncParams = this.syncParams;\n const sharedSync = this;\n return new (class extends DBAdapter {\n connectionState = null;\n get name() {\n return syncParams?.dbParams.dbFilename;\n }\n async connect() {\n if (this.connectionState == null) {\n const handleClosed = this.handleClientClosed.bind(this);\n this.connectionState = (async () => {\n try {\n const db = await sharedSync.openInternalDB(handleClosed);\n db.registerListener({\n tablesUpdated: (notification) => {\n this.iterateListeners((l) => l.tablesUpdated?.(notification));\n }\n });\n this.connectionState = db;\n return db;\n }\n catch (e) {\n // Allow reconnecting when the database is used again.\n this.connectionState = null;\n throw e;\n }\n })();\n }\n return await this.connectionState;\n }\n async close() {\n if (this.connectionState != null) {\n await (await this.connectionState).close();\n }\n }\n handleClientClosed(client) {\n if (client === this.connectionState) {\n this.connectionState = null;\n // We may have missed some table updates while the database was closed.\n // We can poke the crud in case we missed any updates.\n const impl = sharedSync.connectionManager.syncStreamImplementation;\n impl?.triggerCrudUpload();\n // The Rust client implementation stores sync state on the connection level. Reopening the database causes a\n // disruption of the connection state and forces us to reconnect. We want to do that as soon as possible to\n // minimize downtime.\n impl?.markConnectionMayHaveChanged();\n }\n }\n async readLock(fn, options) {\n const db = await this.connect();\n return db.readLock(fn, options);\n }\n async writeLock(fn, options) {\n const db = await this.connect();\n return db.writeLock(fn, options);\n }\n async refreshSchema() {\n // Not used by sync client.\n }\n })();\n }\n}\n/**\n * Runs the action with an abort controller.\n */\nfunction withAbort(options) {\n const { action, signal, cleanupOnAbort } = options;\n return new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(new AbortOperation('Operation aborted by abort controller'));\n return;\n }\n function handleAbort() {\n signal.removeEventListener('abort', handleAbort);\n reject(new AbortOperation('Operation aborted by abort controller'));\n }\n signal.addEventListener('abort', handleAbort, { once: true });\n function completePromise(action) {\n signal.removeEventListener('abort', handleAbort);\n action();\n }\n action()\n .then((data) => {\n // We already rejected due to the abort, allow for cleanup\n if (signal.aborted) {\n return completePromise(() => cleanupOnAbort?.(data));\n }\n completePromise(() => resolve(data));\n })\n .catch((e) => completePromise(() => reject(e)));\n });\n}\n//# sourceMappingURL=SharedSyncImplementation.js.map","import { getNavigatorLocks } from './navigator.js';\n/**\n * Requests a random lock that will be released once the optional signal is aborted (or, if no signal is given, when the\n * tab is closed).\n *\n * This allows sending the name of the lock to another context (e.g. a shared worker), which will also attempt to\n * acquire it. Since the lock is returned when the tab is closed, this allows the shared worker to free resources\n * assocatiated with this tab.\n *\n * We take hold of this lock as soon-as-possible in order to cater for potentially closed tabs.\n */\nexport function generateTabCloseSignal(abort) {\n return new Promise((resolve, reject) => {\n const options = { signal: abort };\n getNavigatorLocks()\n .request(`tab-close-signal-${crypto.randomUUID()}`, options, (lock) => {\n resolve(lock.name);\n return new Promise((resolve) => {\n if (abort) {\n abort.addEventListener('abort', () => resolve());\n }\n });\n })\n .catch(reject);\n });\n}\n//# sourceMappingURL=tab_close_signal.js.map","import * as Comlink from 'comlink';\nimport { getNavigatorLocks } from '../../shared/navigator.js';\nimport { SharedSyncClientEvent } from './SharedSyncImplementation.js';\n/**\n * A client to the shared sync worker.\n *\n * The shared sync implementation needs a per-client view of subscriptions so that subscriptions of closed tabs can\n * automatically be evicted later.\n */\nexport class WorkerClient {\n sync;\n port;\n resolvedPort = null;\n resolvedPortPromise = null;\n constructor(sync, port) {\n this.sync = sync;\n this.port = port;\n Comlink.expose(this, this.port);\n /**\n * Adds an extra listener which can remove this port\n * from the list of monitored ports.\n */\n this.port.addEventListener('message', async (event) => {\n const payload = event.data;\n if (payload?.event == SharedSyncClientEvent.CLOSE_CLIENT) {\n await this.removePort();\n }\n });\n }\n async removePort() {\n if (this.resolvedPort) {\n const resolved = this.resolvedPort;\n this.resolvedPort = null;\n const release = await this.sync.removePort(resolved);\n this.resolvedPort = null;\n this.port.postMessage({\n event: SharedSyncClientEvent.CLOSE_ACK,\n data: {}\n });\n release?.();\n }\n }\n /**\n * Called by a client after obtaining a lock with a random name.\n *\n * When the client tab is closed, its lock will be returned. So when the shared worker attempts to acquire the lock,\n * it can consider the connection to be closed.\n */\n async addLockBasedCloseSignal(name) {\n // Only add the port once the lock has been obtained on the client.\n this.resolvedPort = await this.sync.addPort(this.port);\n // Don't await this lock request\n getNavigatorLocks().request(name, async () => {\n await this.removePort();\n });\n }\n setLogLevel(level) {\n this.sync.setLogLevel(level);\n }\n triggerCrudUpload() {\n return this.sync.triggerCrudUpload();\n }\n setParams(params, subscriptions) {\n this.resolvedPort.currentSubscriptions = subscriptions;\n return this.sync.setParams(params);\n }\n getWriteCheckpoint() {\n return this.sync.getWriteCheckpoint();\n }\n connect(options, schema) {\n return this.sync.connect(options, schema);\n }\n updateSubscriptions(subscriptions) {\n if (this.resolvedPort) {\n this.sync.updateSubscriptions(this.resolvedPort, subscriptions);\n }\n }\n disconnect() {\n return this.sync.disconnect();\n }\n}\n//# sourceMappingURL=WorkerClient.js.map","import * as Comlink from 'comlink';\nimport { createConsoleLogger, LogLevels } from '@powersync/common';\nimport { isSharedWorker, MultiDatabaseServer } from './db/MultiDatabaseServer.js';\nimport { SharedSyncImplementation } from './sync/SharedSyncImplementation.js';\nimport { WorkerClient } from './sync/WorkerClient.js';\nconst server = new MultiDatabaseServer(createConsoleLogger({ prefix: 'db-worker', minLevel: LogLevels.trace }));\nconst exposedDatabaseFunctions = {\n connect: (config) => server.handleConnection(config),\n connectToExisting: ({ identifier, lockName }) => server.connectToExisting(identifier, lockName)\n};\nif (isSharedWorker) {\n const sharedSyncImplementation = new SharedSyncImplementation();\n // A shared worker can either be an IndexedDB-VFS database server or a shared sync coordinator.\n // To be able to know what service a client is connecting to, we let clients send an inner MessagePort through the\n // top-level port along with a tag describing what they need.\n const _self = self;\n _self.onconnect = (outerEvent) => {\n const port = outerEvent.ports[0];\n port.onmessage = (event) => {\n const { service, port } = event.data;\n if (service === 'database') {\n Comlink.expose(exposedDatabaseFunctions, port);\n }\n else if (service === 'sync') {\n new WorkerClient(sharedSyncImplementation, port);\n }\n };\n };\n}\nelse {\n // Dedicated workers are only used for databases, so we don't need an intermediate layer.\n Comlink.expose(exposedDatabaseFunctions);\n}\n//# sourceMappingURL=worker.js.map"],"names":["proxyMarker","Symbol","createEndpoint","releaseProxy","finalizer","throwMarker","isObject","val","transferHandlers","Map","canHandle","serialize","obj","port1","port2","MessageChannel","expose","deserialize","port","start","wrap","value","serialized","Error","isError","message","name","stack","Object","assign","ep","globalThis","allowedOrigins","addEventListener","callback","ev","data","origin","allowedOrigin","RegExp","test","isAllowedOrigin","console","warn","id","type","path","argumentList","map","fromWireValue","returnValue","parent","slice","reduce","prop","rawValue","apply","proxy","transfer","undefined","Promise","resolve","catch","then","wireValue","transferables","toWireValue","postMessage","removeEventListener","closeEndPoint","error","TypeError","endpoint","constructor","isMessagePort","close","target","pendingListeners","resolver","get","delete","createProxy","throwIfProxyReleased","isReleased","releaseEndpoint","requestResponseMessage","proxyCounter","WeakMap","proxyFinalizers","FinalizationRegistry","newCount","set","isProxyReleased","Proxy","_target","unregister","unregisterProxy","clear","length","r","p","toString","bind","_thisArg","rawArgumentList","last","processArguments","construct","register","registerProxy","processed","v","arr","Array","prototype","concat","transferCache","transfers","handler","serializedValue","msg","fill","Math","floor","random","Number","MAX_SAFE_INTEGER","join","LogLevels","trace","debug","info","createConsoleLogger","options","prefix","minLevel","log","level","this","emitter","messageWithPrefix","ColumnType","AttachmentState","EncodingType","UpdateType","SyncStreamConnectionMethod","FetchStrategy","DiffTriggerOperation","WatchedQueryListenerEvent","TEXT","INTEGER","REAL","BaseObserver","listeners","Set","dispose","registerListener","listener","add","iterateListeners","cb","iterateAsyncListeners","i","from","values","rowToRecord","columnNames","row","record","forEach","idx","queryResultWithoutRows","result","array","iterator","next","done","LockContext","getAll","sql","parameters","rs","execute","getOptional","query","params","raw","insertId","rowsAffected","rawRows","loadAsArray","getRow","rows","_array","item","nextIndex","queryResultFromRaw","executeRaw","executeBatch","lastInsertId","DBAdapter","readTransaction","fn","readLock","ctx","TransactionImplementation","runWith","writeTransaction","writeLock","tx","inner","finalized","super","commit","rollback","ex","ex2","DatabaseServer","nextClientId","activeClients","updateBroadcastChannel","clientTableListeners","BroadcastChannel","filename","onmessage","pushTableUpdateToClients","changedTables","logger","connect","lockName","isOpen","clientId","currentTableListener","connectionLeases","requireOpen","requireOpenAndLease","lease","token","async","returnLease","size","forceClose","navigator","locks","request","debugIsAutoCommit","unsafeUseInner","isAutoCommit","requestAccess","write","timeoutMs","acquireConnection","AbortSignal","timeout","crypto","randomUUID","completeAccess","use","conn","updatedTables","JSON","parse","db","setUpdateListener","connection","onClose","getNavigatorLocks","SQLITE_OK","SQLITE_ERROR","SQLITE_BUSY","SQLITE_IOERR","SQLITE_NOTFOUND","SQLITE_CANTOPEN","SQLITE_IOERR_ACCESS","SQLITE_IOERR_CHECKRESERVEDLOCK","SQLITE_IOERR_CLOSE","SQLITE_IOERR_DELETE","SQLITE_IOERR_FSTAT","SQLITE_IOERR_FSYNC","SQLITE_IOERR_LOCK","SQLITE_IOERR_READ","SQLITE_IOERR_SHORT_READ","SQLITE_IOERR_TRUNCATE","SQLITE_IOERR_UNLOCK","SQLITE_IOERR_WRITE","SQLITE_OPEN_CREATE","SQLITE_OPEN_DELETEONCLOSE","SQLITE_OPEN_URI","SQLITE_OPEN_MAIN_DB","SQLITE_OPEN_TEMP_DB","SQLITE_OPEN_MAIN_JOURNAL","SQLITE_OPEN_SUPER_JOURNAL","SQLITE_OPEN_WAL","SQLITE_LOCK_NONE","SQLITE_LOCK_SHARED","SQLITE_LOCK_RESERVED","SQLITE_LOCK_EXCLUSIVE","SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN","SQLITE_IOCAP_BATCH_ATOMIC","SQLITE_FCNTL_OVERWRITE","SQLITE_FCNTL_PRAGMA","SQLITE_FCNTL_SYNC","SQLITE_FCNTL_BEGIN_ATOMIC_WRITE","SQLITE_FCNTL_COMMIT_ATOMIC_WRITE","SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE","BigInt","MAX_INT64","MIN_INT64","AsyncFunction","getPrototypeOf","SQLiteError","code","decl","s","m","match","push","args","c","WASQLiteVFS","syncModuleFactory","encryptionKey","default","factory","import","DEFAULT_MODULE_FACTORIES","IDBBatchAtomicVFS","module","asyncModuleFactory","vfs","create","dbFileName","lockPolicy","AccessHandlePoolVFS","OPFSCoopSyncVFS","OPFSWriteAheadVFS","RawSqliteConnection","_sqliteAPI","_moduleFactory","init","api","openSQLiteAPI","open_v2","readonly","temporaryStorage","escapedKey","replace","cacheSizeKb","sqlite3","Module","retryOps","pendingOps","sqliteFreeAddress","_getSqliteFree","tmp","_malloc","tmpPtr","textEncoder","TextEncoder","createUTF8","utf8","encode","zts","_sqlite3_malloc","byteLength","HEAPU8","cvt32x2ToBigInt","lo32","hi32","cvt32x2AsSafe","hiMax","hiMin","MIN_SAFE_INTEGER","databases","verifyDatabase","has","mapStmtToDB","verifyStatement","stmt","check","fname","allowed","includes","ccall","retry","f","rc","retryCount","all","e","bind_collection","bindings","isArray","nBindings","bind_parameter_count","bind_parameter_name","bind_int","bind_double","bind_text","Uint8Array","bind_blob","bind_null","bind_int64","cwrap","ptr","subarray","changes","clear_bindings","last_insert_id","column","iCol","column_type","column_blob","column_double","column_int","getTempRet0","column_text","nBytes","column_bytes","address","column_count","column_int64","column_name","column_names","columns","nColumns","create_function","zFunctionName","nArg","eTextRep","pApp","xFunc","xStep","xFinal","adapt","n","HEAP32","data_count","exec","statements","step","finalize","get_autocommit","libversion","libversion_number","limit","newVal","zFilename","flags","zVfs","SQLite.SQLITE_OPEN_CREATE","getValue","_sqlite3_free","progress_handler","nProgressOps","userData","reset","context","result_int","result_double","result_text","result_blob","result_null","result_int64","buffer","set_authorizer","xAuth","cvtArgs","_","iAction","p3","p4","p5","p6","UTF8ToString","prepare","onFinally","allocSize","pzHead","pzEnd","pStmt","pzTail","maybeFinalize","unscoped","setValue","zTail","pop","commit_hook","xCommitHook","update_hook","xUpdateHook","iUpdateType","dbName","tblName","pValue","value_type","value_blob","value_double","value_int","value_text","value_bytes","value_int64","vfs_register","makeDefault","WaSqliteFactory","requireSqlite","resultSet","executeSingleStatementRaw","wrapQueryResults","results","parameterSet","stepThroughStatement","autocommit","knownColumns","includeResults","b","index","PSInternalTable","PowerSyncControlCommand","FULL_SYNC_PRIORITY","MAX_OP_ID","SyncProgressImpl","internal","totalOperations","downloadedOperations","downloadedFraction","untilCompletion","untilPriority","priority","total","downloaded","progress","buckets","since_last","target_count","at_last","SyncStatusSnapshot","core","jsState","connected","connecting","downloading","uploading","downloadError","uploadError","dataFlowStatus","lastSyncedAt","statusForPriority","hasSynced","syncStreams","streams","SyncStreamStatusView","forStream","stream","asJson","stringify","find","priorityStatusEntries","priority_status","priorityToJs","downloadProgress","internalProgress","coreStatus","known","isEqual","status","replacer","serializeError","otherStatus","otherOptions","getMessage","toJSON","dataFlow","cause","has_synced","time","last_synced_at","Date","subscription","active","isDefault","is_default","hasExplicitSubscription","has_explicit_subscription","expiresAt","expires_at","resolveSyncOptions","defaultConnectionMethod","appMetadata","connectionMethod","fetchStrategy","Buffered","includeDefaultStreams","retryDelayMs","crudUploadThrottleMs","ConnectionManager","connectingPromise","syncStreamInitPromise","disconnectingPromise","pendingConnectionOptions","currentOptions","syncStreamImplementation","syncDisposer","locallyActiveSubscriptions","connector","connectionOptions","serializedSchema","hadPendingOptions","schema","disconnectInternal","checkConnection","connectInternal","finally","appliedOptions","reject","sync","onDispose","createSyncImplementation","subscriptions","activeStreams","l","syncStreamCreated","waitForReady","disconnect","performDisconnect","disposer","adapter","desc","waitForFirstSync","abort","firstStatusMatching","subscribe","rustSubscriptionsCommand","ttl","resolveOfflineSyncStatus","key","clearSubscription","subscriptionsMayHaveChanged","ActiveSubscription","SyncStreamSubscriptionHandle","unsubscribeAll","unsubscribe","a","updateSubscriptions","refcount","decrementRefCount","_finalizer","sub","Queue","table","head","_length","initialItems","isEmpty","removeFirst","addLast","element","Semaphore","available","firstWaiter","lastWaiter","elements","addWaiter","requestedItems","onAcquire","node","isActive","acquiredItems","remainingItems","prev","deactivateWaiter","waiter","requestPermits","amount","rejectAborted","reason","aborted","markCompleted","items","nextWaiter","onAbort","resolvePromise","release","requestOne","requestAll","Mutex","acquire","runExclusive","returnMutex","CrudEntryImpl","op","opData","previousValues","transactionId","metadata","fromRow","dbRow","parseInt","tx_id","old","op_id","equals","entry","toComparisonArray","symbolAsyncIterator","asyncIterator","for","doneResult","valueResult","injectable","source","sourceIsDone","pendingSourceEvent","sourceFetchInFlight","pendingInjectedEvents","consumeWaiter","pending","shift","resolveWaiter","propagate","w","fetchFromSource","inject","event","EventQueue","waitingConsumer","outstandingEvents","countOutstandingEvents","notifyInner","dispatch","existing","dispatchAndNotifyListeners","eventDelivered","notify","notifyError","waitForEvent","signal","complete","splice","queueBasedAsyncIterable","run","queue","controller","AbortController","SqliteBucketStorage","tableNames","updateListener","_clientId","tablesUpdated","tables","CRUD","crudUpdate","existingTableRows","_getClientId","getClientId","getMaxOpId","updateLocalTarget","seqBefore","seq","opId","anyData","seqAfter","nextCrudItem","hasCrud","getCrudBatch","crudResult","crud","haveMore","writeCheckpoint","control","payload","hasMigratedSubkeys","_subkeyMigrationKey","migrateToFixedSubkeys","static","AbortOperation","setPrototypeOf","captureStackTrace","POWERSYNC_TRAILING_SLASH_MATCH","webSocketPlatform","AbstractRemote","credentials","getCredentials","prefetchCredentials","fetchCredentials","invalidateCredentials","getUserAgent","buildRequest","userAgent","url","headers","Authorization","res","fetch","resource","method","expectStreamingResponse","ok","statusText","text","json","createTextDecoder","TextDecoder","createSocket","WebSocket","socketStreamRaw","support","loadWebSocketSupport","abortSignal","webSocketSyncStream","remote","buffered","requestPayload","fetchStreamRaw","reader","cancel","responseIsBson","ndJson","bson","accept","body","cache","getReader","isBson","read","fetchStream","completedObjects","isDone","lengthBuffer","DataView","ArrayBuffer","objectBody","remainingLength","upstreamEvent","chunk","availableInData","bytesToRead","min","copySource","byteOffset","j","setUint8","getInt32","setInt32","extractBsonObjects","decoder","pendingLines","isFinalEvent","first","remaining","trim","decode","lines","split","extractJsonLines","isInterruptingInstruction","instruction","LockType","AbstractStreamingSyncImplementation","abortController","crudUpdateListener","streamingSyncPromise","connectionMayHaveChanged","crudUploadNotifier","waitForNotification","asyncNotifier","notifyCompletedUploads","handleActiveStreamsChange","syncStatus","triggerCrudUpload","waitUntilStatusMatches","predicate","statusChanged","lastSynced","isConnected","getWriteCheckpoint","checkpoint","crudUploadLoop","_uploadAllCrud","delayRetry","obtainLock","checkedCrudItem","updateJsSyncState","uploadCrud","streamingSync","sawStartOfConnection","snapshot","markAsDisconnected","current","updateSyncStatus","nestedAbortController","shouldDelayRetry","streamingSyncIteration","indexOf","immediateRestart","markConnectionMayHaveChanged","requireKeyFormat","requireFixedKeyFormat","hasMigrated","SYNC","invalidMetadata","entries","filter","rustSyncIteration","receiveSyncLines","openInner","HTTP","command","CONNECTION_STATE","PROCESS_TEXT_LINE","PROCESS_BSON_LINE","resolvedOptions","syncImplementation","notifyTokenRefreshed","hideDisconnectOnRestart","invokePowerSyncControl","rawResponse","payloadDesc","STOP","handleInstruction","severity","line","LogLine","UpdateSyncStatus","FetchCredentials","did_expire","err","defaultResult","controlInvocations","startInstruction","app_metadata","active_streams","include_defaults","START","startCommand","syncOptions","EstablishSyncStream","NOTIFY_CRUD_UPLOAD_COMPLETED","UPDATE_SUBSCRIPTIONS","NOTIFY_TOKEN_REFRESHED","hadSyncLine","loop","instructions","CloseSyncStream","hide_disconnect","stop","updated","state","delay","timeoutId","endDelay","clearTimeout","once","setTimeout","ConnectionClosedError","MATCHES","input","NAME","ConcurrentSqliteConnection","leaseMutex","needsNavigatorLocks","acquireMutex","returnLock","ConnectionLeaseToken","useMutex","closed","OPEN_DB_LOCK","isSharedWorker","WebRemote","platform","websockets","WebSocketSupport","ua","nav","browser","brands","userAgentData","tests","brand","version","regexps","re","getBrowserInfo","os","toLowerCase","getOsInfo","getUserAgentInfo","WebStreamingSyncImplementation","webOptions","lockOptions","identifier","BroadcastLogger","clients","currentLevel","sendBroadcasts","sanitized","sanitizeRecord","iterateClients","client","clientProvider","setLevel","structuredClone","DatabaseClient","config","shareConnectionAbortController","receiveTableUpdates","notifyRemoteClosed","remoteCanCloseUnexpectedly","traceQueries","debugMode","Comlink.transfer","notification","dbFilename","markRemoteClosed","useConnectionState","Comlink.releaseProxy","lock","ClientLockContext","refreshSchema","shareConnection","now","round","releaseLock","Comlink.createEndpoint","getConfiguration","maybeTrace","describeForTrace","performance","description","measure","executeOnWorker","workerPromise","fireActionOnAbort","handleAbort","completePromise","action","SharedSyncClientEvent","CONNECTOR_PLACEHOLDER","SharedSyncImplementation","ports","isInitialized","statusListener","fetchCredentialsController","uploadDataController","syncParams","lastConnectOptions","portMutex","connectionManager","database","generateReconnectableDatabase","initialized","generateStreamingImplementation","getLastWrappedPort","isClosing","getRandomWrappedPort","nonClosingPorts","withSyncImplementation","collectActiveSubscriptions","currentSubscriptions","serializedKey","setLogLevel","setParams","enableBroadcastLogs","self","onerror","addPort","portProvider","Comlink.wrap","closeListeners","removePort","findIndex","trackedPort","activePort","closeListener","lastPort","onabort","streamOptions","openInternalDB","handleClosed","removeCloseListener","withAbort","getDBWorkerPort","cleanupOnAbort","dbParams","clientLockName","clientView","connectToExisting","sharedSync","connectionState","handleClientClosed","impl","WorkerClient","resolvedPort","resolvedPortPromise","Comlink.expose","CLOSE_CLIENT","resolved","CLOSE_ACK","addLockBasedCloseSignal","server","activeDatabases","handleConnection","logLevel","Comlink.proxy","openConnectionLocally","count","maxAttempts","databaseOpenAttempt","withSafeConcurrency","closeAll","existingDatabases","exposedDatabaseFunctions","sharedSyncImplementation","onconnect","outerEvent","service"],"mappings":";;;;;AAKA,MAAMA,EAAcC,OAAO,iBACrBC,EAAiBD,OAAO,oBACxBE,EAAeF,OAAO,wBACtBG,EAAYH,OAAO,qBACnBI,EAAcJ,OAAO,kBACrBK,EAAYC,GAAwB,iBAARA,GAA4B,OAARA,GAAgC,mBAARA,EAgDxEC,EAAmB,IAAIC,IAAI,CAC7B,CAAC,QA7CwB,CACzBC,UAAYH,GAAQD,EAASC,IAAQA,EAAIP,GACzC,SAAAW,CAAUC,GACN,MAAMC,MAAEA,EAAKC,MAAEA,GAAU,IAAIC,eA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