@powersync/web 1.37.1 → 1.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/2075a31bb151adbb9767.wasm +0 -0
  2. package/dist/3322bc84de986b63c2cd.wasm +0 -0
  3. package/dist/8e97452e297be23b5e50.wasm +0 -0
  4. package/dist/fbc178b70d530e8ce02b.wasm +0 -0
  5. package/dist/index.umd.js +4289 -4786
  6. package/dist/index.umd.js.map +1 -1
  7. package/dist/worker/SharedSyncImplementation.umd.js +517 -1265
  8. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
  9. package/dist/worker/WASQLiteDB.umd.js +576 -1201
  10. package/dist/worker/WASQLiteDB.umd.js.map +1 -1
  11. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-9af0a7.umd.js +31 -0
  12. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-9af0a7.umd.js.map +1 -0
  13. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-bbf5a9.umd.js +31 -0
  14. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-bbf5a9.umd.js.map +1 -0
  15. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-c26e0f.umd.js +31 -0
  16. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-cc5fcc.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-c26e0f.umd.js.map} +1 -1
  17. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +31 -0
  18. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map} +1 -1
  19. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-2fb422.umd.js +3562 -0
  20. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-2fb422.umd.js.map +1 -0
  21. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-0df390.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-96fb23.umd.js} +16 -16
  22. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-0df390.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-96fb23.umd.js.map} +1 -1
  23. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-151024.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-c89911.umd.js} +12 -12
  24. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-151024.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-c89911.umd.js.map} +1 -1
  25. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-c01ef0.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-ec4eb1.umd.js} +14 -14
  26. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-c01ef0.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-ec4eb1.umd.js.map} +1 -1
  27. package/lib/package.json +5 -8
  28. package/lib/src/db/PowerSyncDatabase.d.ts +1 -1
  29. package/lib/src/db/PowerSyncDatabase.js +0 -8
  30. package/lib/src/db/adapters/AsyncWebAdapter.d.ts +13 -3
  31. package/lib/src/db/adapters/AsyncWebAdapter.js +115 -21
  32. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.js +1 -2
  33. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js +1 -1
  34. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +16 -2
  35. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +60 -38
  36. package/lib/src/db/adapters/wa-sqlite/vfs.d.ts +7 -18
  37. package/lib/src/db/adapters/wa-sqlite/vfs.js +34 -49
  38. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.d.ts +4 -0
  39. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.js +4 -0
  40. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.d.ts +0 -1
  41. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +0 -3
  42. package/lib/src/db/sync/WebRemote.d.ts +1 -3
  43. package/lib/src/db/sync/WebRemote.js +0 -12
  44. package/lib/src/worker/db/MultiDatabaseServer.js +4 -1
  45. package/lib/src/worker/db/open-worker-database.js +2 -2
  46. package/lib/src/worker/sync/SharedSyncImplementation.d.ts +0 -2
  47. package/lib/src/worker/sync/SharedSyncImplementation.js +4 -16
  48. package/lib/src/worker/sync/WorkerClient.d.ts +0 -1
  49. package/lib/src/worker/sync/WorkerClient.js +0 -3
  50. package/lib/tsconfig.tsbuildinfo +1 -1
  51. package/package.json +6 -9
  52. package/src/db/PowerSyncDatabase.ts +1 -9
  53. package/src/db/adapters/AsyncWebAdapter.ts +138 -22
  54. package/src/db/adapters/wa-sqlite/DatabaseServer.ts +4 -2
  55. package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +4 -1
  56. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +89 -44
  57. package/src/db/adapters/wa-sqlite/vfs.ts +33 -49
  58. package/src/db/sync/SSRWebStreamingSyncImplementation.ts +5 -0
  59. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +0 -4
  60. package/src/db/sync/WebRemote.ts +0 -16
  61. package/src/worker/db/MultiDatabaseServer.ts +4 -1
  62. package/src/worker/db/open-worker-database.ts +2 -2
  63. package/src/worker/sync/SharedSyncImplementation.ts +4 -18
  64. package/src/worker/sync/WorkerClient.ts +0 -4
  65. package/dist/26d61ca9f5694d064635.wasm +0 -0
  66. package/dist/b4c6283dc473b6b3fd24.wasm +0 -0
  67. package/dist/c78985091a0b22aaef03.wasm +0 -0
  68. package/dist/ca59e199e1138b553fad.wasm +0 -0
  69. package/dist/worker/node_modules_pnpm_bson_6_10_4_node_modules_bson_lib_bson_mjs.umd.js +0 -4646
  70. package/dist/worker/node_modules_pnpm_bson_6_10_4_node_modules_bson_lib_bson_mjs.umd.js.map +0 -1
  71. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-b9c070.umd.js +0 -31
  72. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-b9c070.umd.js.map +0 -1
  73. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-c99c07.umd.js +0 -31
  74. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-c99c07.umd.js.map +0 -1
  75. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-cc5fcc.umd.js +0 -31
  76. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +0 -31
@@ -384,9 +384,9 @@ function generateUUID() {
384
384
 
385
385
  /***/ },
386
386
 
387
- /***/ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js"
387
+ /***/ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js"
388
388
  /*!*******************************************************************************************************************!*\
389
- !*** ../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js ***!
389
+ !*** ../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js ***!
390
390
  \*******************************************************************************************************************/
391
391
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
392
392
 
@@ -627,7 +627,7 @@ __webpack_require__.r(__webpack_exports__);
627
627
  /* harmony export */ SQLITE_WARNING: () => (/* reexport safe */ _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__.SQLITE_WARNING),
628
628
  /* harmony export */ SQLiteError: () => (/* binding */ SQLiteError)
629
629
  /* harmony export */ });
630
- /* harmony import */ var _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sqlite-constants.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js");
630
+ /* harmony import */ var _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sqlite-constants.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js");
631
631
  // Copyright 2021 Roy T. Hashimoto. All Rights Reserved.
632
632
 
633
633
 
@@ -669,6 +669,7 @@ function Factory(Module) {
669
669
  /** @type {SQLiteAPI} */ const sqlite3 = {};
670
670
 
671
671
  Module.retryOps = [];
672
+ Module.pendingOps = [];
672
673
  const sqliteFreeAddress = Module._getSqliteFree();
673
674
 
674
675
  // Allocate some space for 32-bit returned values.
@@ -1524,7 +1525,7 @@ function Factory(Module) {
1524
1525
  // succeed.
1525
1526
  async function retry(f) {
1526
1527
  let rc;
1527
- do {
1528
+ for (let retryCount = 0; retryCount < 2; ++retryCount) {
1528
1529
  // Wait for all pending retry operations to complete. This is
1529
1530
  // normally empty on the first loop iteration.
1530
1531
  if (Module.retryOps.length) {
@@ -1536,9 +1537,20 @@ function Factory(Module) {
1536
1537
  }
1537
1538
 
1538
1539
  rc = await f();
1539
-
1540
- // Retry on failure with new pending retry operations.
1541
- } while (rc && Module.retryOps.length);
1540
+ if (rc === _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__.SQLITE_OK || Module.retryOps.length === 0) {
1541
+ if (Module.pendingOps.length) {
1542
+ try {
1543
+ await Promise.all(Module.pendingOps);
1544
+ } catch (e) {
1545
+ console.error('Error in pendingOps:', e);
1546
+ return e.code || _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__.SQLITE_ERROR;
1547
+ } finally {
1548
+ Module.pendingOps = [];
1549
+ }
1550
+ }
1551
+ return rc;
1552
+ }
1553
+ }
1542
1554
  return rc;
1543
1555
  }
1544
1556
 
@@ -1579,9 +1591,9 @@ function decl(s) {
1579
1591
 
1580
1592
  /***/ },
1581
1593
 
1582
- /***/ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js"
1594
+ /***/ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js"
1583
1595
  /*!*************************************************************************************************************************!*\
1584
- !*** ../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js ***!
1596
+ !*** ../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js ***!
1585
1597
  \*************************************************************************************************************************/
1586
1598
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
1587
1599
 
@@ -2332,8 +2344,7 @@ class DatabaseServer {
2332
2344
  },
2333
2345
  requestAccess: async (write, timeoutMs) => {
2334
2346
  requireOpen();
2335
- // TODO: Support timeouts, they don't seem to be supported by the async-mutex package.
2336
- const lease = await this.#inner.acquireConnection();
2347
+ const lease = await this.#inner.acquireConnection(timeoutMs != null ? AbortSignal.timeout(timeoutMs) : undefined);
2337
2348
  if (!isOpen) {
2338
2349
  // Race between requestAccess and close(), the connection was closed while we tried to acquire a lease.
2339
2350
  await lease.returnLease();
@@ -2405,7 +2416,7 @@ __webpack_require__.r(__webpack_exports__);
2405
2416
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2406
2417
  /* harmony export */ RawSqliteConnection: () => (/* binding */ RawSqliteConnection)
2407
2418
  /* harmony export */ });
2408
- /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
2419
+ /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
2409
2420
  /* harmony import */ var _vfs_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vfs.js */ "./lib/src/db/adapters/wa-sqlite/vfs.js");
2410
2421
 
2411
2422
 
@@ -2432,7 +2443,7 @@ class RawSqliteConnection {
2432
2443
  }
2433
2444
  async init() {
2434
2445
  const api = (this._sqliteAPI = await this.openSQLiteAPI());
2435
- this.db = await api.open_v2(this.options.dbFilename);
2446
+ this.db = await api.open_v2(this.options.dbFilename, this.options.isReadOnly ? 1 /* SQLITE_OPEN_READONLY */ : 6 /* SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE */);
2436
2447
  await this.executeRaw(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
2437
2448
  if (this.options.encryptionKey) {
2438
2449
  const escapedKey = this.options.encryptionKey.replace("'", "''");
@@ -2566,11 +2577,7 @@ class RawSqliteConnection {
2566
2577
 
2567
2578
  __webpack_require__.r(__webpack_exports__);
2568
2579
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2569
- /* harmony export */ AsyncWASQLiteModuleFactory: () => (/* binding */ AsyncWASQLiteModuleFactory),
2570
2580
  /* harmony export */ DEFAULT_MODULE_FACTORIES: () => (/* binding */ DEFAULT_MODULE_FACTORIES),
2571
- /* harmony export */ MultiCipherAsyncWASQLiteModuleFactory: () => (/* binding */ MultiCipherAsyncWASQLiteModuleFactory),
2572
- /* harmony export */ MultiCipherSyncWASQLiteModuleFactory: () => (/* binding */ MultiCipherSyncWASQLiteModuleFactory),
2573
- /* harmony export */ SyncWASQLiteModuleFactory: () => (/* binding */ SyncWASQLiteModuleFactory),
2574
2581
  /* harmony export */ WASQLiteVFS: () => (/* binding */ WASQLiteVFS),
2575
2582
  /* harmony export */ vfsRequiresDedicatedWorkers: () => (/* binding */ vfsRequiresDedicatedWorkers)
2576
2583
  /* harmony export */ });
@@ -2582,51 +2589,38 @@ var WASQLiteVFS;
2582
2589
  WASQLiteVFS["IDBBatchAtomicVFS"] = "IDBBatchAtomicVFS";
2583
2590
  WASQLiteVFS["OPFSCoopSyncVFS"] = "OPFSCoopSyncVFS";
2584
2591
  WASQLiteVFS["AccessHandlePoolVFS"] = "AccessHandlePoolVFS";
2592
+ WASQLiteVFS["OPFSWriteAheadVFS"] = "OPFSWriteAheadVFS";
2585
2593
  })(WASQLiteVFS || (WASQLiteVFS = {}));
2586
2594
  function vfsRequiresDedicatedWorkers(vfs) {
2587
2595
  return vfs != WASQLiteVFS.IDBBatchAtomicVFS;
2588
2596
  }
2589
- /**
2590
- * @internal
2591
- */
2592
- const AsyncWASQLiteModuleFactory = async () => {
2593
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-cc5fcc").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs"));
2594
- return factory();
2595
- };
2596
- /**
2597
- * @internal
2598
- */
2599
- const MultiCipherAsyncWASQLiteModuleFactory = async () => {
2600
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-c99c07").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs"));
2601
- return factory();
2602
- };
2603
- /**
2604
- * @internal
2605
- */
2606
- const SyncWASQLiteModuleFactory = async () => {
2607
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite.mjs"));
2608
- return factory();
2609
- };
2610
- /**
2611
- * @internal
2612
- */
2613
- const MultiCipherSyncWASQLiteModuleFactory = async () => {
2614
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-b9c070").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs"));
2615
- return factory();
2616
- };
2597
+ async function asyncModuleFactory(encryptionKey) {
2598
+ if (encryptionKey) {
2599
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-9af0a7").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs"));
2600
+ return factory();
2601
+ }
2602
+ else {
2603
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-c26e0f").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs"));
2604
+ return factory();
2605
+ }
2606
+ }
2607
+ async function syncModuleFactory(encryptionKey) {
2608
+ if (encryptionKey) {
2609
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-bbf5a9").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs"));
2610
+ return factory();
2611
+ }
2612
+ else {
2613
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite.mjs"));
2614
+ return factory();
2615
+ }
2616
+ }
2617
2617
  /**
2618
2618
  * @internal
2619
2619
  */
2620
2620
  const DEFAULT_MODULE_FACTORIES = {
2621
2621
  [WASQLiteVFS.IDBBatchAtomicVFS]: async (options) => {
2622
- let module;
2623
- if (options.encryptionKey) {
2624
- module = await MultiCipherAsyncWASQLiteModuleFactory();
2625
- }
2626
- else {
2627
- module = await AsyncWASQLiteModuleFactory();
2628
- }
2629
- const { IDBBatchAtomicVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-0df390").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js"));
2622
+ const module = await asyncModuleFactory(options.encryptionKey);
2623
+ const { IDBBatchAtomicVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-96fb23").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js"));
2630
2624
  return {
2631
2625
  module,
2632
2626
  // @ts-expect-error The types for this static method are missing upstream
@@ -2634,35 +2628,33 @@ const DEFAULT_MODULE_FACTORIES = {
2634
2628
  };
2635
2629
  },
2636
2630
  [WASQLiteVFS.AccessHandlePoolVFS]: async (options) => {
2637
- let module;
2638
- if (options.encryptionKey) {
2639
- module = await MultiCipherSyncWASQLiteModuleFactory();
2640
- }
2641
- else {
2642
- module = await SyncWASQLiteModuleFactory();
2643
- }
2631
+ const module = await syncModuleFactory(options.encryptionKey);
2644
2632
  // @ts-expect-error The types for this static method are missing upstream
2645
- const { AccessHandlePoolVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-151024").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js"));
2633
+ const { AccessHandlePoolVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-c89911").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js"));
2646
2634
  return {
2647
2635
  module,
2648
2636
  vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)
2649
2637
  };
2650
2638
  },
2651
2639
  [WASQLiteVFS.OPFSCoopSyncVFS]: async (options) => {
2652
- let module;
2653
- if (options.encryptionKey) {
2654
- module = await MultiCipherSyncWASQLiteModuleFactory();
2655
- }
2656
- else {
2657
- module = await SyncWASQLiteModuleFactory();
2658
- }
2640
+ const module = await syncModuleFactory(options.encryptionKey);
2659
2641
  // @ts-expect-error The types for this static method are missing upstream
2660
- const { OPFSCoopSyncVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-c01ef0").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js"));
2642
+ const { OPFSCoopSyncVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-ec4eb1").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js"));
2661
2643
  const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);
2662
2644
  return {
2663
2645
  module,
2664
2646
  vfs
2665
2647
  };
2648
+ },
2649
+ [WASQLiteVFS.OPFSWriteAheadVFS]: async (options) => {
2650
+ const module = await syncModuleFactory(options.encryptionKey);
2651
+ // @ts-expect-error The types for this static method are missing upstream
2652
+ const { OPFSWriteAheadVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-2fb422").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/OPFSWriteAheadVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSWriteAheadVFS.js"));
2653
+ const vfs = await OPFSWriteAheadVFS.create(options.dbFileName, module, {});
2654
+ return {
2655
+ module,
2656
+ vfs
2657
+ };
2666
2658
  }
2667
2659
  };
2668
2660
 
@@ -2756,7 +2748,10 @@ class MultiDatabaseServer {
2756
2748
  const { dbFilename } = options;
2757
2749
  let server = this.activeDatabases.get(dbFilename);
2758
2750
  if (server == null) {
2759
- const needsNavigatorLocks = !isSharedWorker;
2751
+ // We don't need navigator locks for shared workers because all queries run in this shared worker exclusively.
2752
+ // For read-only connections, we use a VFS that supports concurrent reads (so a single lock on the connection is
2753
+ // fine).
2754
+ const needsNavigatorLocks = !(isSharedWorker || options.isReadOnly);
2760
2755
  const connection = new _db_adapters_wa_sqlite_RawSqliteConnection_js__WEBPACK_IMPORTED_MODULE_3__.RawSqliteConnection(options);
2761
2756
  const withSafeConcurrency = new _db_adapters_wa_sqlite_ConcurrentConnection_js__WEBPACK_IMPORTED_MODULE_4__.ConcurrentSqliteConnection(connection, needsNavigatorLocks);
2762
2757
  // Initializing the RawSqliteConnection will run some pragmas that might write to the database file, so we want
@@ -2834,7 +2829,6 @@ __webpack_require__.r(__webpack_exports__);
2834
2829
  /* harmony export */ DEFAULT_LOCK_TIMEOUT_MS: () => (/* binding */ DEFAULT_LOCK_TIMEOUT_MS),
2835
2830
  /* harmony export */ DEFAULT_POWERSYNC_CLOSE_OPTIONS: () => (/* binding */ DEFAULT_POWERSYNC_CLOSE_OPTIONS),
2836
2831
  /* harmony export */ DEFAULT_POWERSYNC_DB_OPTIONS: () => (/* binding */ DEFAULT_POWERSYNC_DB_OPTIONS),
2837
- /* harmony export */ DEFAULT_PRESSURE_LIMITS: () => (/* binding */ DEFAULT_PRESSURE_LIMITS),
2838
2832
  /* harmony export */ DEFAULT_REMOTE_LOGGER: () => (/* binding */ DEFAULT_REMOTE_LOGGER),
2839
2833
  /* harmony export */ DEFAULT_REMOTE_OPTIONS: () => (/* binding */ DEFAULT_REMOTE_OPTIONS),
2840
2834
  /* harmony export */ DEFAULT_RETRY_DELAY_MS: () => (/* binding */ DEFAULT_RETRY_DELAY_MS),
@@ -2845,7 +2839,6 @@ __webpack_require__.r(__webpack_exports__);
2845
2839
  /* harmony export */ DEFAULT_TABLE_OPTIONS: () => (/* binding */ DEFAULT_TABLE_OPTIONS),
2846
2840
  /* harmony export */ DEFAULT_WATCH_QUERY_OPTIONS: () => (/* binding */ DEFAULT_WATCH_QUERY_OPTIONS),
2847
2841
  /* harmony export */ DEFAULT_WATCH_THROTTLE_MS: () => (/* binding */ DEFAULT_WATCH_THROTTLE_MS),
2848
- /* harmony export */ DataStream: () => (/* binding */ DataStream),
2849
2842
  /* harmony export */ DiffTriggerOperation: () => (/* binding */ DiffTriggerOperation),
2850
2843
  /* harmony export */ DifferentialQueryProcessor: () => (/* binding */ DifferentialQueryProcessor),
2851
2844
  /* harmony export */ EMPTY_DIFFERENTIAL: () => (/* binding */ EMPTY_DIFFERENTIAL),
@@ -2864,9 +2857,6 @@ __webpack_require__.r(__webpack_exports__);
2864
2857
  /* harmony export */ MEMORY_TRIGGER_CLAIM_MANAGER: () => (/* binding */ MEMORY_TRIGGER_CLAIM_MANAGER),
2865
2858
  /* harmony export */ Mutex: () => (/* binding */ Mutex),
2866
2859
  /* harmony export */ OnChangeQueryProcessor: () => (/* binding */ OnChangeQueryProcessor),
2867
- /* harmony export */ OpType: () => (/* binding */ OpType),
2868
- /* harmony export */ OpTypeEnum: () => (/* binding */ OpTypeEnum),
2869
- /* harmony export */ OplogEntry: () => (/* binding */ OplogEntry),
2870
2860
  /* harmony export */ PSInternalTable: () => (/* binding */ PSInternalTable),
2871
2861
  /* harmony export */ PowerSyncControlCommand: () => (/* binding */ PowerSyncControlCommand),
2872
2862
  /* harmony export */ RowUpdateType: () => (/* binding */ RowUpdateType),
@@ -2874,8 +2864,6 @@ __webpack_require__.r(__webpack_exports__);
2874
2864
  /* harmony export */ Semaphore: () => (/* binding */ Semaphore),
2875
2865
  /* harmony export */ SqliteBucketStorage: () => (/* binding */ SqliteBucketStorage),
2876
2866
  /* harmony export */ SyncClientImplementation: () => (/* binding */ SyncClientImplementation),
2877
- /* harmony export */ SyncDataBatch: () => (/* binding */ SyncDataBatch),
2878
- /* harmony export */ SyncDataBucket: () => (/* binding */ SyncDataBucket),
2879
2867
  /* harmony export */ SyncProgress: () => (/* binding */ SyncProgress),
2880
2868
  /* harmony export */ SyncStatus: () => (/* binding */ SyncStatus),
2881
2869
  /* harmony export */ SyncStreamConnectionMethod: () => (/* binding */ SyncStreamConnectionMethod),
@@ -2893,18 +2881,10 @@ __webpack_require__.r(__webpack_exports__);
2893
2881
  /* harmony export */ createLogger: () => (/* binding */ createLogger),
2894
2882
  /* harmony export */ extractTableUpdates: () => (/* binding */ extractTableUpdates),
2895
2883
  /* harmony export */ isBatchedUpdateNotification: () => (/* binding */ isBatchedUpdateNotification),
2896
- /* harmony export */ isContinueCheckpointRequest: () => (/* binding */ isContinueCheckpointRequest),
2897
2884
  /* harmony export */ isDBAdapter: () => (/* binding */ isDBAdapter),
2898
2885
  /* harmony export */ isPowerSyncDatabaseOptionsWithSettings: () => (/* binding */ isPowerSyncDatabaseOptionsWithSettings),
2899
2886
  /* harmony export */ isSQLOpenFactory: () => (/* binding */ isSQLOpenFactory),
2900
2887
  /* harmony export */ isSQLOpenOptions: () => (/* binding */ isSQLOpenOptions),
2901
- /* harmony export */ isStreamingKeepalive: () => (/* binding */ isStreamingKeepalive),
2902
- /* harmony export */ isStreamingSyncCheckpoint: () => (/* binding */ isStreamingSyncCheckpoint),
2903
- /* harmony export */ isStreamingSyncCheckpointComplete: () => (/* binding */ isStreamingSyncCheckpointComplete),
2904
- /* harmony export */ isStreamingSyncCheckpointDiff: () => (/* binding */ isStreamingSyncCheckpointDiff),
2905
- /* harmony export */ isStreamingSyncCheckpointPartiallyComplete: () => (/* binding */ isStreamingSyncCheckpointPartiallyComplete),
2906
- /* harmony export */ isStreamingSyncData: () => (/* binding */ isStreamingSyncData),
2907
- /* harmony export */ isSyncNewCheckpointRequest: () => (/* binding */ isSyncNewCheckpointRequest),
2908
2888
  /* harmony export */ parseQuery: () => (/* binding */ parseQuery),
2909
2889
  /* harmony export */ runOnSchemaChange: () => (/* binding */ runOnSchemaChange),
2910
2890
  /* harmony export */ sanitizeSQL: () => (/* binding */ sanitizeSQL),
@@ -4309,6 +4289,8 @@ var EncodingType;
4309
4289
  EncodingType["Base64"] = "base64";
4310
4290
  })(EncodingType || (EncodingType = {}));
4311
4291
 
4292
+ const symbolAsyncIterator = Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');
4293
+
4312
4294
  function getDefaultExportFromCjs (x) {
4313
4295
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
4314
4296
  }
@@ -4389,7 +4371,7 @@ function requireEventIterator () {
4389
4371
  this.removeCallback();
4390
4372
  });
4391
4373
  }
4392
- [Symbol.asyncIterator]() {
4374
+ [symbolAsyncIterator]() {
4393
4375
  return {
4394
4376
  next: (value) => {
4395
4377
  const result = this.pushQueue.shift();
@@ -4436,7 +4418,7 @@ function requireEventIterator () {
4436
4418
  queue.eventHandlers[event] = fn;
4437
4419
  },
4438
4420
  }) || (() => { });
4439
- this[Symbol.asyncIterator] = () => queue[Symbol.asyncIterator]();
4421
+ this[symbolAsyncIterator] = () => queue[symbolAsyncIterator]();
4440
4422
  Object.freeze(this);
4441
4423
  }
4442
4424
  }
@@ -4880,8 +4862,15 @@ class BaseTransaction {
4880
4862
  class TransactionImplementation extends DBGetUtilsDefaultMixin(BaseTransaction) {
4881
4863
  static async runWith(ctx, fn) {
4882
4864
  let tx = new TransactionImplementation(ctx);
4865
+ // For write transactions, use BEGIN IMMEDIATE to immediately obtain a write lock on the database (instead of doing
4866
+ // that on the first statement). If we have a genuine read-only connection, we also use BEGIN IMMEDIATE there: In
4867
+ // WAL mode, that ensures we pin the current state of the database (instead of the state at the first statement in
4868
+ // the transaction). But if we have a "fake" read-only connection implemented through `pragma query_only = true`, we
4869
+ // can't use this trick because it would attempt to lock the connection. So there, we use a regular `BEGIN`
4870
+ // statement.
4871
+ const useBeginImmediate = ctx.connectionType != 'queryOnly';
4883
4872
  try {
4884
- await ctx.execute('BEGIN IMMEDIATE');
4873
+ await ctx.execute(useBeginImmediate ? 'BEGIN IMMEDIATE' : 'BEGIN');
4885
4874
  const result = await fn(tx);
4886
4875
  await tx.commit();
4887
4876
  return result;
@@ -5040,16 +5029,12 @@ class SyncStatus {
5040
5029
  *
5041
5030
  * This returns null when the database is currently being opened and we don't have reliable information about all
5042
5031
  * included streams yet.
5043
- *
5044
- * @experimental Sync streams are currently in alpha.
5045
5032
  */
5046
5033
  get syncStreams() {
5047
5034
  return this.options.dataFlow?.internalStreamSubscriptions?.map((core) => new SyncStreamStatusView(this, core));
5048
5035
  }
5049
5036
  /**
5050
5037
  * If the `stream` appears in {@link syncStreams}, returns the current status for that stream.
5051
- *
5052
- * @experimental Sync streams are currently in alpha.
5053
5038
  */
5054
5039
  forStream(stream) {
5055
5040
  const asJson = JSON.stringify(stream.parameters);
@@ -5318,15 +5303,6 @@ class ControlledExecutor {
5318
5303
  }
5319
5304
  }
5320
5305
 
5321
- /**
5322
- * A ponyfill for `Symbol.asyncIterator` that is compatible with the
5323
- * [recommended polyfill](https://github.com/Azure/azure-sdk-for-js/blob/%40azure/core-asynciterator-polyfill_1.0.2/sdk/core/core-asynciterator-polyfill/src/index.ts#L4-L6)
5324
- * we recommend for React Native.
5325
- *
5326
- * As long as we use this symbol (instead of `for await` and `async *`) in this package, we can be compatible with async
5327
- * iterators without requiring them.
5328
- */
5329
- const symbolAsyncIterator = Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');
5330
5306
  /**
5331
5307
  * Throttle a function to be called at most once every "wait" milliseconds,
5332
5308
  * on the trailing edge.
@@ -5641,7 +5617,7 @@ class SyncStreamSubscriptionHandle {
5641
5617
  constructor(subscription) {
5642
5618
  this.subscription = subscription;
5643
5619
  subscription.refcount++;
5644
- _finalizer?.register(this, subscription);
5620
+ _finalizer?.register(this, subscription, this);
5645
5621
  }
5646
5622
  get name() {
5647
5623
  return this.subscription.name;
@@ -6230,6 +6206,10 @@ var PowerSyncControlCommand;
6230
6206
  PowerSyncControlCommand["NOTIFY_TOKEN_REFRESHED"] = "refreshed_token";
6231
6207
  PowerSyncControlCommand["NOTIFY_CRUD_UPLOAD_COMPLETED"] = "completed_upload";
6232
6208
  PowerSyncControlCommand["UPDATE_SUBSCRIPTIONS"] = "update_subscriptions";
6209
+ /**
6210
+ * An `established` or `end` event for response streams.
6211
+ */
6212
+ PowerSyncControlCommand["CONNECTION_STATE"] = "connection";
6233
6213
  })(PowerSyncControlCommand || (PowerSyncControlCommand = {}));
6234
6214
 
6235
6215
  /**
@@ -6411,103 +6391,6 @@ class AbortOperation extends Error {
6411
6391
  }
6412
6392
  }
6413
6393
 
6414
- var OpTypeEnum;
6415
- (function (OpTypeEnum) {
6416
- OpTypeEnum[OpTypeEnum["CLEAR"] = 1] = "CLEAR";
6417
- OpTypeEnum[OpTypeEnum["MOVE"] = 2] = "MOVE";
6418
- OpTypeEnum[OpTypeEnum["PUT"] = 3] = "PUT";
6419
- OpTypeEnum[OpTypeEnum["REMOVE"] = 4] = "REMOVE";
6420
- })(OpTypeEnum || (OpTypeEnum = {}));
6421
- /**
6422
- * Used internally for sync buckets.
6423
- */
6424
- class OpType {
6425
- value;
6426
- static fromJSON(jsonValue) {
6427
- return new OpType(OpTypeEnum[jsonValue]);
6428
- }
6429
- constructor(value) {
6430
- this.value = value;
6431
- }
6432
- toJSON() {
6433
- return Object.entries(OpTypeEnum).find(([, value]) => value === this.value)[0];
6434
- }
6435
- }
6436
-
6437
- class OplogEntry {
6438
- op_id;
6439
- op;
6440
- checksum;
6441
- subkey;
6442
- object_type;
6443
- object_id;
6444
- data;
6445
- static fromRow(row) {
6446
- return new OplogEntry(row.op_id, OpType.fromJSON(row.op), row.checksum, row.subkey, row.object_type, row.object_id, row.data);
6447
- }
6448
- constructor(op_id, op, checksum, subkey, object_type, object_id, data) {
6449
- this.op_id = op_id;
6450
- this.op = op;
6451
- this.checksum = checksum;
6452
- this.subkey = subkey;
6453
- this.object_type = object_type;
6454
- this.object_id = object_id;
6455
- this.data = data;
6456
- }
6457
- toJSON(fixedKeyEncoding = false) {
6458
- return {
6459
- op_id: this.op_id,
6460
- op: this.op.toJSON(),
6461
- object_type: this.object_type,
6462
- object_id: this.object_id,
6463
- checksum: this.checksum,
6464
- data: this.data,
6465
- // Older versions of the JS SDK used to always JSON.stringify here. That has always been wrong,
6466
- // but we need to migrate gradually to not break existing databases.
6467
- subkey: fixedKeyEncoding ? this.subkey : JSON.stringify(this.subkey)
6468
- };
6469
- }
6470
- }
6471
-
6472
- class SyncDataBucket {
6473
- bucket;
6474
- data;
6475
- has_more;
6476
- after;
6477
- next_after;
6478
- static fromRow(row) {
6479
- return new SyncDataBucket(row.bucket, row.data.map((entry) => OplogEntry.fromRow(entry)), row.has_more ?? false, row.after, row.next_after);
6480
- }
6481
- constructor(bucket, data,
6482
- /**
6483
- * True if the response does not contain all the data for this bucket, and another request must be made.
6484
- */
6485
- has_more,
6486
- /**
6487
- * The `after` specified in the request.
6488
- */
6489
- after,
6490
- /**
6491
- * Use this for the next request.
6492
- */
6493
- next_after) {
6494
- this.bucket = bucket;
6495
- this.data = data;
6496
- this.has_more = has_more;
6497
- this.after = after;
6498
- this.next_after = next_after;
6499
- }
6500
- toJSON(fixedKeyEncoding = false) {
6501
- return {
6502
- bucket: this.bucket,
6503
- has_more: this.has_more,
6504
- after: this.after,
6505
- next_after: this.next_after,
6506
- data: this.data.map((entry) => entry.toJSON(fixedKeyEncoding))
6507
- };
6508
- }
6509
- }
6510
-
6511
6394
  var buffer = {};
6512
6395
 
6513
6396
  var base64Js = {};
@@ -13663,177 +13546,10 @@ function requireDist () {
13663
13546
 
13664
13547
  var distExports = requireDist();
13665
13548
 
13666
- var version = "1.51.0";
13549
+ var version = "1.53.0";
13667
13550
  var PACKAGE = {
13668
13551
  version: version};
13669
13552
 
13670
- const DEFAULT_PRESSURE_LIMITS = {
13671
- highWater: 10,
13672
- lowWater: 0
13673
- };
13674
- /**
13675
- * A very basic implementation of a data stream with backpressure support which does not use
13676
- * native JS streams or async iterators.
13677
- * This is handy for environments such as React Native which need polyfills for the above.
13678
- */
13679
- class DataStream extends BaseObserver {
13680
- options;
13681
- dataQueue;
13682
- isClosed;
13683
- processingPromise;
13684
- notifyDataAdded;
13685
- logger;
13686
- mapLine;
13687
- constructor(options) {
13688
- super();
13689
- this.options = options;
13690
- this.processingPromise = null;
13691
- this.isClosed = false;
13692
- this.dataQueue = [];
13693
- this.mapLine = options?.mapLine ?? ((line) => line);
13694
- this.logger = options?.logger ?? Logger.get('DataStream');
13695
- if (options?.closeOnError) {
13696
- const l = this.registerListener({
13697
- error: (ex) => {
13698
- l?.();
13699
- this.close();
13700
- }
13701
- });
13702
- }
13703
- }
13704
- get highWatermark() {
13705
- return this.options?.pressure?.highWaterMark ?? DEFAULT_PRESSURE_LIMITS.highWater;
13706
- }
13707
- get lowWatermark() {
13708
- return this.options?.pressure?.lowWaterMark ?? DEFAULT_PRESSURE_LIMITS.lowWater;
13709
- }
13710
- get closed() {
13711
- return this.isClosed;
13712
- }
13713
- async close() {
13714
- this.isClosed = true;
13715
- await this.processingPromise;
13716
- this.iterateListeners((l) => l.closed?.());
13717
- // Discard any data in the queue
13718
- this.dataQueue = [];
13719
- this.listeners.clear();
13720
- }
13721
- /**
13722
- * Enqueues data for the consumers to read
13723
- */
13724
- enqueueData(data) {
13725
- if (this.isClosed) {
13726
- throw new Error('Cannot enqueue data into closed stream.');
13727
- }
13728
- this.dataQueue.push(data);
13729
- this.notifyDataAdded?.();
13730
- this.processQueue();
13731
- }
13732
- /**
13733
- * Reads data once from the data stream
13734
- * @returns a Data payload or Null if the stream closed.
13735
- */
13736
- async read() {
13737
- if (this.closed) {
13738
- return null;
13739
- }
13740
- // Wait for any pending processing to complete first.
13741
- // This ensures we register our listener before calling processQueue(),
13742
- // avoiding a race where processQueue() sees no reader and returns early.
13743
- if (this.processingPromise) {
13744
- await this.processingPromise;
13745
- }
13746
- // Re-check after await - stream may have closed while we were waiting
13747
- if (this.closed) {
13748
- return null;
13749
- }
13750
- return new Promise((resolve, reject) => {
13751
- const l = this.registerListener({
13752
- data: async (data) => {
13753
- resolve(data);
13754
- // Remove the listener
13755
- l?.();
13756
- },
13757
- closed: () => {
13758
- resolve(null);
13759
- l?.();
13760
- },
13761
- error: (ex) => {
13762
- reject(ex);
13763
- l?.();
13764
- }
13765
- });
13766
- this.processQueue();
13767
- });
13768
- }
13769
- /**
13770
- * Executes a callback for each data item in the stream
13771
- */
13772
- forEach(callback) {
13773
- if (this.dataQueue.length <= this.lowWatermark) {
13774
- this.iterateAsyncErrored(async (l) => l.lowWater?.());
13775
- }
13776
- return this.registerListener({
13777
- data: callback
13778
- });
13779
- }
13780
- processQueue() {
13781
- if (this.processingPromise) {
13782
- return;
13783
- }
13784
- const promise = (this.processingPromise = this._processQueue());
13785
- promise.finally(() => {
13786
- this.processingPromise = null;
13787
- });
13788
- return promise;
13789
- }
13790
- hasDataReader() {
13791
- return Array.from(this.listeners.values()).some((l) => !!l.data);
13792
- }
13793
- async _processQueue() {
13794
- /**
13795
- * Allow listeners to mutate the queue before processing.
13796
- * This allows for operations such as dropping or compressing data
13797
- * on high water or requesting more data on low water.
13798
- */
13799
- if (this.dataQueue.length >= this.highWatermark) {
13800
- await this.iterateAsyncErrored(async (l) => l.highWater?.());
13801
- }
13802
- if (this.isClosed || !this.hasDataReader()) {
13803
- return;
13804
- }
13805
- if (this.dataQueue.length) {
13806
- const data = this.dataQueue.shift();
13807
- const mapped = this.mapLine(data);
13808
- await this.iterateAsyncErrored(async (l) => l.data?.(mapped));
13809
- }
13810
- if (this.dataQueue.length <= this.lowWatermark) {
13811
- const dataAdded = new Promise((resolve) => {
13812
- this.notifyDataAdded = resolve;
13813
- });
13814
- await Promise.race([this.iterateAsyncErrored(async (l) => l.lowWater?.()), dataAdded]);
13815
- this.notifyDataAdded = null;
13816
- }
13817
- if (this.dataQueue.length > 0) {
13818
- setTimeout(() => this.processQueue());
13819
- }
13820
- }
13821
- async iterateAsyncErrored(cb) {
13822
- // Important: We need to copy the listeners, as calling a listener could result in adding another
13823
- // listener, resulting in infinite loops.
13824
- const listeners = Array.from(this.listeners.values());
13825
- for (let i of listeners) {
13826
- try {
13827
- await cb(i);
13828
- }
13829
- catch (ex) {
13830
- this.logger.error(ex);
13831
- this.iterateListeners((l) => l.error?.(ex));
13832
- }
13833
- }
13834
- }
13835
- }
13836
-
13837
13553
  var WebsocketDuplexConnection = {};
13838
13554
 
13839
13555
  var hasRequiredWebsocketDuplexConnection;
@@ -13996,8 +13712,199 @@ class WebsocketClientTransport {
13996
13712
  }
13997
13713
  }
13998
13714
 
13715
+ const doneResult = { done: true, value: undefined };
13716
+ function valueResult(value) {
13717
+ return { done: false, value };
13718
+ }
13719
+ /**
13720
+ * Expands a source async iterator by allowing to inject events asynchronously.
13721
+ *
13722
+ * The resulting iterator will emit all events from its source. Additionally though, events can be injected. These
13723
+ * events are dropped once the main iterator completes, but are otherwise forwarded.
13724
+ *
13725
+ * The iterator completes when its source completes, and it supports backpressure by only calling `next()` on the source
13726
+ * in response to a `next()` call from downstream if no pending injected events can be dispatched.
13727
+ */
13728
+ function injectable(source) {
13729
+ let sourceIsDone = false;
13730
+ let waiter = undefined; // An active, waiting next() call.
13731
+ // A pending upstream event that couldn't be dispatched because inject() has been called before it was resolved.
13732
+ let pendingSourceEvent = null;
13733
+ let pendingInjectedEvents = [];
13734
+ const consumeWaiter = () => {
13735
+ const pending = waiter;
13736
+ waiter = undefined;
13737
+ return pending;
13738
+ };
13739
+ const fetchFromSource = () => {
13740
+ const resolveWaiter = (propagate) => {
13741
+ const active = consumeWaiter();
13742
+ if (active) {
13743
+ propagate(active);
13744
+ }
13745
+ else {
13746
+ pendingSourceEvent = propagate;
13747
+ }
13748
+ };
13749
+ const nextFromSource = source.next();
13750
+ nextFromSource.then((value) => {
13751
+ sourceIsDone = value.done == true;
13752
+ resolveWaiter((w) => w.resolve(value));
13753
+ }, (error) => {
13754
+ resolveWaiter((w) => w.reject(error));
13755
+ });
13756
+ };
13757
+ return {
13758
+ next: () => {
13759
+ return new Promise((resolve, reject) => {
13760
+ // First priority: Dispatch ready upstream events.
13761
+ if (sourceIsDone) {
13762
+ return resolve(doneResult);
13763
+ }
13764
+ if (pendingSourceEvent) {
13765
+ pendingSourceEvent({ resolve, reject });
13766
+ pendingSourceEvent = null;
13767
+ return;
13768
+ }
13769
+ // Second priority: Dispatch injected events
13770
+ if (pendingInjectedEvents.length) {
13771
+ return resolve(valueResult(pendingInjectedEvents.shift()));
13772
+ }
13773
+ // Nothing pending? Fetch from source
13774
+ waiter = { resolve, reject };
13775
+ return fetchFromSource();
13776
+ });
13777
+ },
13778
+ inject: (event) => {
13779
+ const pending = consumeWaiter();
13780
+ if (pending != null) {
13781
+ pending.resolve(valueResult(event));
13782
+ }
13783
+ else {
13784
+ pendingInjectedEvents.push(event);
13785
+ }
13786
+ }
13787
+ };
13788
+ }
13789
+ /**
13790
+ * Splits a byte stream at line endings, emitting each line as a string.
13791
+ */
13792
+ function extractJsonLines(source, decoder) {
13793
+ let buffer = '';
13794
+ const pendingLines = [];
13795
+ let isFinalEvent = false;
13796
+ return {
13797
+ next: async () => {
13798
+ while (true) {
13799
+ if (isFinalEvent) {
13800
+ return doneResult;
13801
+ }
13802
+ {
13803
+ const first = pendingLines.shift();
13804
+ if (first) {
13805
+ return { done: false, value: first };
13806
+ }
13807
+ }
13808
+ const { done, value } = await source.next();
13809
+ if (done) {
13810
+ const remaining = buffer.trim();
13811
+ if (remaining.length != 0) {
13812
+ isFinalEvent = true;
13813
+ return { done: false, value: remaining };
13814
+ }
13815
+ return doneResult;
13816
+ }
13817
+ const data = decoder.decode(value, { stream: true });
13818
+ buffer += data;
13819
+ const lines = buffer.split('\n');
13820
+ for (let i = 0; i < lines.length - 1; i++) {
13821
+ const l = lines[i].trim();
13822
+ if (l.length > 0) {
13823
+ pendingLines.push(l);
13824
+ }
13825
+ }
13826
+ buffer = lines[lines.length - 1];
13827
+ }
13828
+ }
13829
+ };
13830
+ }
13831
+ /**
13832
+ * Splits a concatenated stream of BSON objects by emitting individual objects.
13833
+ */
13834
+ function extractBsonObjects(source) {
13835
+ // Fully read but not emitted yet.
13836
+ const completedObjects = [];
13837
+ // Whether source has returned { done: true }. We do the same once completed objects have been emitted.
13838
+ let isDone = false;
13839
+ const lengthBuffer = new DataView(new ArrayBuffer(4));
13840
+ let objectBody = null;
13841
+ // If we're parsing the length field, a number between 1 and 4 (inclusive) describing remaining bytes in the header.
13842
+ // If we're consuming a document, the bytes remaining.
13843
+ let remainingLength = 4;
13844
+ return {
13845
+ async next() {
13846
+ while (true) {
13847
+ // Before fetching new data from upstream, return completed objects.
13848
+ if (completedObjects.length) {
13849
+ return valueResult(completedObjects.shift());
13850
+ }
13851
+ if (isDone) {
13852
+ return doneResult;
13853
+ }
13854
+ const upstreamEvent = await source.next();
13855
+ if (upstreamEvent.done) {
13856
+ isDone = true;
13857
+ if (objectBody || remainingLength != 4) {
13858
+ throw new Error('illegal end of stream in BSON object');
13859
+ }
13860
+ return doneResult;
13861
+ }
13862
+ const chunk = upstreamEvent.value;
13863
+ for (let i = 0; i < chunk.length;) {
13864
+ const availableInData = chunk.length - i;
13865
+ if (objectBody) {
13866
+ // We're in the middle of reading a BSON document.
13867
+ const bytesToRead = Math.min(availableInData, remainingLength);
13868
+ const copySource = new Uint8Array(chunk.buffer, chunk.byteOffset + i, bytesToRead);
13869
+ objectBody.set(copySource, objectBody.length - remainingLength);
13870
+ i += bytesToRead;
13871
+ remainingLength -= bytesToRead;
13872
+ if (remainingLength == 0) {
13873
+ completedObjects.push(objectBody);
13874
+ // Prepare to read another document, starting with its length
13875
+ objectBody = null;
13876
+ remainingLength = 4;
13877
+ }
13878
+ }
13879
+ else {
13880
+ // Copy up to 4 bytes into lengthBuffer, depending on how many we still need.
13881
+ const bytesToRead = Math.min(availableInData, remainingLength);
13882
+ for (let j = 0; j < bytesToRead; j++) {
13883
+ lengthBuffer.setUint8(4 - remainingLength + j, chunk[i + j]);
13884
+ }
13885
+ i += bytesToRead;
13886
+ remainingLength -= bytesToRead;
13887
+ if (remainingLength == 0) {
13888
+ // Transition from reading length header to reading document. Subtracting 4 because the length of the
13889
+ // header is included in length.
13890
+ const length = lengthBuffer.getInt32(0, true /* little endian */);
13891
+ remainingLength = length - 4;
13892
+ if (remainingLength < 1) {
13893
+ throw new Error(`invalid length for bson: ${length}`);
13894
+ }
13895
+ objectBody = new Uint8Array(length);
13896
+ new DataView(objectBody.buffer).setInt32(0, length, true);
13897
+ }
13898
+ }
13899
+ }
13900
+ }
13901
+ }
13902
+ };
13903
+ }
13904
+
13999
13905
  const POWERSYNC_TRAILING_SLASH_MATCH = /\/+$/;
14000
13906
  const POWERSYNC_JS_VERSION = PACKAGE.version;
13907
+ const SYNC_QUEUE_REQUEST_HIGH_WATER = 10;
14001
13908
  const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
14002
13909
  // Keep alive message is sent every period
14003
13910
  const KEEP_ALIVE_MS = 20_000;
@@ -14177,73 +14084,67 @@ class AbstractRemote {
14177
14084
  return new WebSocket(url);
14178
14085
  }
14179
14086
  /**
14180
- * Returns a data stream of sync line data.
14087
+ * Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.
14181
14088
  *
14182
- * @param map Maps received payload frames to the typed event value.
14183
- * @param bson A BSON encoder and decoder. When set, the data stream will be requested with a BSON payload
14184
- * (required for compatibility with older sync services).
14089
+ * The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.
14185
14090
  */
14186
- async socketStreamRaw(options, map, bson) {
14091
+ async socketStreamRaw(options) {
14187
14092
  const { path, fetchStrategy = FetchStrategy.Buffered } = options;
14188
- const mimeType = bson == null ? 'application/json' : 'application/bson';
14093
+ const mimeType = 'application/json';
14189
14094
  function toBuffer(js) {
14190
- let contents;
14191
- if (bson != null) {
14192
- contents = bson.serialize(js);
14193
- }
14194
- else {
14195
- contents = JSON.stringify(js);
14196
- }
14197
- return bufferExports.Buffer.from(contents);
14095
+ return bufferExports.Buffer.from(JSON.stringify(js));
14198
14096
  }
14199
14097
  const syncQueueRequestSize = fetchStrategy == FetchStrategy.Buffered ? 10 : 1;
14200
14098
  const request = await this.buildRequest(path);
14099
+ const url = this.options.socketUrlTransformer(request.url);
14201
14100
  // Add the user agent in the setup payload - we can't set custom
14202
14101
  // headers with websockets on web. The browser userAgent is however added
14203
14102
  // automatically as a header.
14204
14103
  const userAgent = this.getUserAgent();
14205
- const stream = new DataStream({
14206
- logger: this.logger,
14207
- pressure: {
14208
- lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER
14209
- },
14210
- mapLine: map
14211
- });
14104
+ // While we're connecting (a process that can't be aborted in RSocket), the WebSocket instance to close if we wanted
14105
+ // to abort the connection.
14106
+ let pendingSocket = null;
14107
+ let keepAliveTimeout;
14108
+ let rsocket = null;
14109
+ let queue = null;
14110
+ let didClose = false;
14111
+ const abortRequest = () => {
14112
+ if (didClose) {
14113
+ return;
14114
+ }
14115
+ didClose = true;
14116
+ clearTimeout(keepAliveTimeout);
14117
+ if (pendingSocket) {
14118
+ pendingSocket.close();
14119
+ }
14120
+ if (rsocket) {
14121
+ rsocket.close();
14122
+ }
14123
+ if (queue) {
14124
+ queue.stop();
14125
+ }
14126
+ };
14212
14127
  // Handle upstream abort
14213
- if (options.abortSignal?.aborted) {
14128
+ if (options.abortSignal.aborted) {
14214
14129
  throw new AbortOperation('Connection request aborted');
14215
14130
  }
14216
14131
  else {
14217
- options.abortSignal?.addEventListener('abort', () => {
14218
- stream.close();
14219
- }, { once: true });
14132
+ options.abortSignal.addEventListener('abort', abortRequest);
14220
14133
  }
14221
- let keepAliveTimeout;
14222
14134
  const resetTimeout = () => {
14223
14135
  clearTimeout(keepAliveTimeout);
14224
14136
  keepAliveTimeout = setTimeout(() => {
14225
14137
  this.logger.error(`No data received on WebSocket in ${SOCKET_TIMEOUT_MS}ms, closing connection.`);
14226
- stream.close();
14138
+ abortRequest();
14227
14139
  }, SOCKET_TIMEOUT_MS);
14228
14140
  };
14229
14141
  resetTimeout();
14230
- // Typescript complains about this being `never` if it's not assigned here.
14231
- // This is assigned in `wsCreator`.
14232
- let disposeSocketConnectionTimeout = () => { };
14233
- const url = this.options.socketUrlTransformer(request.url);
14234
14142
  const connector = new distExports.RSocketConnector({
14235
14143
  transport: new WebsocketClientTransport({
14236
14144
  url,
14237
14145
  wsCreator: (url) => {
14238
- const socket = this.createSocket(url);
14239
- disposeSocketConnectionTimeout = stream.registerListener({
14240
- closed: () => {
14241
- // Allow closing the underlying WebSocket if the stream was closed before the
14242
- // RSocket connect completed. This should effectively abort the request.
14243
- socket.close();
14244
- }
14245
- });
14246
- socket.addEventListener('message', (event) => {
14146
+ const socket = (pendingSocket = this.createSocket(url));
14147
+ socket.addEventListener('message', () => {
14247
14148
  resetTimeout();
14248
14149
  });
14249
14150
  return socket;
@@ -14263,43 +14164,40 @@ class AbstractRemote {
14263
14164
  }
14264
14165
  }
14265
14166
  });
14266
- let rsocket;
14267
14167
  try {
14268
14168
  rsocket = await connector.connect();
14269
14169
  // The connection is established, we no longer need to monitor the initial timeout
14270
- disposeSocketConnectionTimeout();
14170
+ pendingSocket = null;
14271
14171
  }
14272
14172
  catch (ex) {
14273
14173
  this.logger.error(`Failed to connect WebSocket`, ex);
14274
- clearTimeout(keepAliveTimeout);
14275
- if (!stream.closed) {
14276
- await stream.close();
14277
- }
14174
+ abortRequest();
14278
14175
  throw ex;
14279
14176
  }
14280
14177
  resetTimeout();
14281
- let socketIsClosed = false;
14282
- const closeSocket = () => {
14283
- clearTimeout(keepAliveTimeout);
14284
- if (socketIsClosed) {
14285
- return;
14286
- }
14287
- socketIsClosed = true;
14288
- rsocket.close();
14289
- };
14290
14178
  // Helps to prevent double close scenarios
14291
- rsocket.onClose(() => (socketIsClosed = true));
14292
- // We initially request this amount and expect these to arrive eventually
14293
- let pendingEventsCount = syncQueueRequestSize;
14294
- const disposeClosedListener = stream.registerListener({
14295
- closed: () => {
14296
- closeSocket();
14297
- disposeClosedListener();
14298
- }
14299
- });
14300
- const socket = await new Promise((resolve, reject) => {
14179
+ rsocket.onClose(() => (rsocket = null));
14180
+ return await new Promise((resolve, reject) => {
14301
14181
  let connectionEstablished = false;
14302
- const res = rsocket.requestStream({
14182
+ let pendingEventsCount = syncQueueRequestSize;
14183
+ let paused = false;
14184
+ let res = null;
14185
+ function requestMore() {
14186
+ const delta = syncQueueRequestSize - pendingEventsCount;
14187
+ if (!paused && delta > 0) {
14188
+ res?.request(delta);
14189
+ pendingEventsCount = syncQueueRequestSize;
14190
+ }
14191
+ }
14192
+ const events = new domExports.EventIterator((q) => {
14193
+ queue = q;
14194
+ q.on('highWater', () => (paused = true));
14195
+ q.on('lowWater', () => {
14196
+ paused = false;
14197
+ requestMore();
14198
+ });
14199
+ }, { highWaterMark: SYNC_QUEUE_REQUEST_HIGH_WATER, lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER })[symbolAsyncIterator]();
14200
+ res = rsocket.requestStream({
14303
14201
  data: toBuffer(options.data),
14304
14202
  metadata: toBuffer({
14305
14203
  path
@@ -14324,7 +14222,7 @@ class AbstractRemote {
14324
14222
  }
14325
14223
  // RSocket will close the RSocket stream automatically
14326
14224
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
14327
- stream.close();
14225
+ abortRequest();
14328
14226
  // Handles cases where the connection failed e.g. auth error or connection error
14329
14227
  if (!connectionEstablished) {
14330
14228
  reject(e);
@@ -14334,41 +14232,40 @@ class AbstractRemote {
14334
14232
  // The connection is active
14335
14233
  if (!connectionEstablished) {
14336
14234
  connectionEstablished = true;
14337
- resolve(res);
14235
+ resolve(events);
14338
14236
  }
14339
14237
  const { data } = payload;
14238
+ if (data) {
14239
+ queue.push(data);
14240
+ }
14340
14241
  // Less events are now pending
14341
14242
  pendingEventsCount--;
14342
- if (!data) {
14343
- return;
14344
- }
14345
- stream.enqueueData(data);
14243
+ // Request another event (unless the downstream consumer is paused).
14244
+ requestMore();
14346
14245
  },
14347
14246
  onComplete: () => {
14348
- stream.close();
14247
+ abortRequest(); // this will also emit a done event
14349
14248
  },
14350
14249
  onExtension: () => { }
14351
14250
  });
14352
14251
  });
14353
- const l = stream.registerListener({
14354
- lowWater: async () => {
14355
- // Request to fill up the queue
14356
- const required = syncQueueRequestSize - pendingEventsCount;
14357
- if (required > 0) {
14358
- socket.request(syncQueueRequestSize - pendingEventsCount);
14359
- pendingEventsCount = syncQueueRequestSize;
14360
- }
14361
- },
14362
- closed: () => {
14363
- l();
14364
- }
14365
- });
14366
- return stream;
14367
14252
  }
14368
14253
  /**
14369
- * Connects to the sync/stream http endpoint, mapping and emitting each received string line.
14254
+ * @returns Whether the HTTP implementation on this platform can receive streamed binary responses. This is true on
14255
+ * all platforms except React Native (who would have guessed...), where we must not request BSON responses.
14256
+ *
14257
+ * @see https://github.com/react-native-community/fetch?tab=readme-ov-file#motivation
14258
+ */
14259
+ get supportsStreamingBinaryResponses() {
14260
+ return true;
14261
+ }
14262
+ /**
14263
+ * Posts a `/sync/stream` request, asserts that it completes successfully and returns the streaming response as an
14264
+ * async iterator of byte blobs.
14265
+ *
14266
+ * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
14370
14267
  */
14371
- async postStreamRaw(options, mapLine) {
14268
+ async fetchStreamRaw(options) {
14372
14269
  const { data, path, headers, abortSignal } = options;
14373
14270
  const request = await this.buildRequest(path);
14374
14271
  /**
@@ -14380,119 +14277,94 @@ class AbstractRemote {
14380
14277
  * Aborting the active fetch request while it is being consumed seems to throw
14381
14278
  * an unhandled exception on the window level.
14382
14279
  */
14383
- if (abortSignal?.aborted) {
14384
- throw new AbortOperation('Abort request received before making postStreamRaw request');
14280
+ if (abortSignal.aborted) {
14281
+ throw new AbortOperation('Abort request received before making fetchStreamRaw request');
14385
14282
  }
14386
14283
  const controller = new AbortController();
14387
- let requestResolved = false;
14388
- abortSignal?.addEventListener('abort', () => {
14389
- if (!requestResolved) {
14284
+ let reader = null;
14285
+ abortSignal.addEventListener('abort', () => {
14286
+ const reason = abortSignal.reason ??
14287
+ new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.');
14288
+ if (reader == null) {
14390
14289
  // Only abort via the abort controller if the request has not resolved yet
14391
- controller.abort(abortSignal.reason ??
14392
- new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.'));
14290
+ controller.abort(reason);
14291
+ }
14292
+ else {
14293
+ reader.cancel(reason).catch(() => {
14294
+ // Cancelling the reader might rethrow an exception we would have handled by throwing in next(). So we can
14295
+ // ignore it here.
14296
+ });
14393
14297
  }
14394
14298
  });
14395
- const res = await this.fetch(request.url, {
14396
- method: 'POST',
14397
- headers: { ...headers, ...request.headers },
14398
- body: JSON.stringify(data),
14399
- signal: controller.signal,
14400
- cache: 'no-store',
14401
- ...(this.options.fetchOptions ?? {}),
14402
- ...options.fetchOptions
14403
- }).catch((ex) => {
14299
+ let res;
14300
+ let responseIsBson = false;
14301
+ try {
14302
+ const ndJson = 'application/x-ndjson';
14303
+ const bson = 'application/vnd.powersync.bson-stream';
14304
+ res = await this.fetch(request.url, {
14305
+ method: 'POST',
14306
+ headers: {
14307
+ ...headers,
14308
+ ...request.headers,
14309
+ accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
14310
+ },
14311
+ body: JSON.stringify(data),
14312
+ signal: controller.signal,
14313
+ cache: 'no-store',
14314
+ ...(this.options.fetchOptions ?? {}),
14315
+ ...options.fetchOptions
14316
+ });
14317
+ if (!res.ok || !res.body) {
14318
+ const text = await res.text();
14319
+ this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
14320
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
14321
+ error.status = res.status;
14322
+ throw error;
14323
+ }
14324
+ const contentType = res.headers.get('content-type');
14325
+ responseIsBson = contentType == bson;
14326
+ }
14327
+ catch (ex) {
14404
14328
  if (ex.name == 'AbortError') {
14405
14329
  throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
14406
14330
  }
14407
14331
  throw ex;
14408
- });
14409
- if (!res) {
14410
- throw new Error('Fetch request was aborted');
14411
- }
14412
- requestResolved = true;
14413
- if (!res.ok || !res.body) {
14414
- const text = await res.text();
14415
- this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
14416
- const error = new Error(`HTTP ${res.statusText}: ${text}`);
14417
- error.status = res.status;
14418
- throw error;
14419
14332
  }
14420
- // Create a new stream splitting the response at line endings while also handling cancellations
14421
- // by closing the reader.
14422
- const reader = res.body.getReader();
14423
- let readerReleased = false;
14424
- // This will close the network request and read stream
14425
- const closeReader = async () => {
14426
- try {
14427
- readerReleased = true;
14428
- await reader.cancel();
14429
- }
14430
- catch (ex) {
14431
- // an error will throw if the reader hasn't been used yet
14432
- }
14433
- reader.releaseLock();
14434
- };
14435
- const stream = new DataStream({
14436
- logger: this.logger,
14437
- mapLine: mapLine,
14438
- pressure: {
14439
- highWaterMark: 20,
14440
- lowWaterMark: 10
14441
- }
14442
- });
14443
- abortSignal?.addEventListener('abort', () => {
14444
- closeReader();
14445
- stream.close();
14446
- });
14447
- const decoder = this.createTextDecoder();
14448
- let buffer = '';
14449
- const consumeStream = async () => {
14450
- while (!stream.closed && !abortSignal?.aborted && !readerReleased) {
14451
- const { done, value } = await reader.read();
14452
- if (done) {
14453
- const remaining = buffer.trim();
14454
- if (remaining.length != 0) {
14455
- stream.enqueueData(remaining);
14456
- }
14457
- stream.close();
14458
- await closeReader();
14459
- return;
14333
+ reader = res.body.getReader();
14334
+ const stream = {
14335
+ next: async () => {
14336
+ if (controller.signal.aborted) {
14337
+ return doneResult;
14460
14338
  }
14461
- const data = decoder.decode(value, { stream: true });
14462
- buffer += data;
14463
- const lines = buffer.split('\n');
14464
- for (var i = 0; i < lines.length - 1; i++) {
14465
- var l = lines[i].trim();
14466
- if (l.length > 0) {
14467
- stream.enqueueData(l);
14468
- }
14339
+ try {
14340
+ return await reader.read();
14469
14341
  }
14470
- buffer = lines[lines.length - 1];
14471
- // Implement backpressure by waiting for the low water mark to be reached
14472
- if (stream.dataQueue.length > stream.highWatermark) {
14473
- await new Promise((resolve) => {
14474
- const dispose = stream.registerListener({
14475
- lowWater: async () => {
14476
- resolve();
14477
- dispose();
14478
- },
14479
- closed: () => {
14480
- resolve();
14481
- dispose();
14482
- }
14483
- });
14484
- });
14342
+ catch (ex) {
14343
+ if (controller.signal.aborted) {
14344
+ // .read() completes with an error if we cancel the reader, which we do to disconnect. So this is just
14345
+ // things working as intended, we can return a done event and consider the exception handled.
14346
+ return doneResult;
14347
+ }
14348
+ throw ex;
14485
14349
  }
14486
14350
  }
14487
14351
  };
14488
- consumeStream().catch(ex => this.logger.error('Error consuming stream', ex));
14489
- const l = stream.registerListener({
14490
- closed: () => {
14491
- closeReader();
14492
- l?.();
14493
- }
14494
- });
14495
- return stream;
14352
+ return { isBson: responseIsBson, stream };
14353
+ }
14354
+ /**
14355
+ * Posts a `/sync/stream` request.
14356
+ *
14357
+ * Depending on the `Content-Type` of the response, this returns strings for sync lines or encoded BSON documents as
14358
+ * {@link Uint8Array}s.
14359
+ */
14360
+ async fetchStream(options) {
14361
+ const { isBson, stream } = await this.fetchStreamRaw(options);
14362
+ if (isBson) {
14363
+ return extractBsonObjects(stream);
14364
+ }
14365
+ else {
14366
+ return extractJsonLines(stream, this.createTextDecoder());
14367
+ }
14496
14368
  }
14497
14369
  }
14498
14370
 
@@ -14521,31 +14393,8 @@ function coreStatusToJs(status) {
14521
14393
  priorityStatusEntries: status.priority_status.map(priorityToJs)
14522
14394
  };
14523
14395
  }
14524
-
14525
- function isStreamingSyncData(line) {
14526
- return line.data != null;
14527
- }
14528
- function isStreamingKeepalive(line) {
14529
- return line.token_expires_in != null;
14530
- }
14531
- function isStreamingSyncCheckpoint(line) {
14532
- return line.checkpoint != null;
14533
- }
14534
- function isStreamingSyncCheckpointComplete(line) {
14535
- return line.checkpoint_complete != null;
14536
- }
14537
- function isStreamingSyncCheckpointPartiallyComplete(line) {
14538
- return line.partial_checkpoint_complete != null;
14539
- }
14540
- function isStreamingSyncCheckpointDiff(line) {
14541
- return line.checkpoint_diff != null;
14542
- }
14543
- function isContinueCheckpointRequest(request) {
14544
- return (Array.isArray(request.buckets) &&
14545
- typeof request.checkpoint_token == 'string');
14546
- }
14547
- function isSyncNewCheckpointRequest(request) {
14548
- return typeof request.request_checkpoint == 'object';
14396
+ function isInterruptingInstruction(instruction) {
14397
+ return 'EstablishSyncStream' in instruction || 'CloseSyncStream' in instruction;
14549
14398
  }
14550
14399
 
14551
14400
  var LockType;
@@ -14560,35 +14409,21 @@ var SyncStreamConnectionMethod;
14560
14409
  })(SyncStreamConnectionMethod || (SyncStreamConnectionMethod = {}));
14561
14410
  var SyncClientImplementation;
14562
14411
  (function (SyncClientImplementation) {
14563
- /**
14564
- * Decodes and handles sync lines received from the sync service in JavaScript.
14565
- *
14566
- * This is the default option.
14567
- *
14568
- * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with
14569
- * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future
14570
- * version of the PowerSync SDK.
14571
- */
14572
- SyncClientImplementation["JAVASCRIPT"] = "js";
14573
14412
  /**
14574
14413
  * This implementation offloads the sync line decoding and handling into the PowerSync
14575
14414
  * core extension.
14576
14415
  *
14577
- * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the
14578
- * recommended client implementation for all apps.
14416
+ * This is the only option, as an older JavaScript client implementation has been removed from the SDK.
14579
14417
  *
14580
14418
  * ## Compatibility warning
14581
14419
  *
14582
14420
  * The Rust sync client stores sync data in a format that is slightly different than the one used
14583
- * by the old {@link JAVASCRIPT} implementation. When adopting the {@link RUST} client on existing
14584
- * databases, the PowerSync SDK will migrate the format automatically.
14585
- * Further, the {@link JAVASCRIPT} client in recent versions of the PowerSync JS SDK (starting from
14586
- * the version introducing {@link RUST} as an option) also supports the new format, so you can switch
14587
- * back to {@link JAVASCRIPT} later.
14421
+ * by the old JavaScript client. When adopting the {@link RUST} client on existing databases, the PowerSync SDK will
14422
+ * migrate the format automatically.
14588
14423
  *
14589
- * __However__: Upgrading the SDK version, then adopting {@link RUST} as a sync client and later
14590
- * downgrading the SDK to an older version (necessarily using the JavaScript-based implementation then)
14591
- * can lead to sync issues.
14424
+ * SDK versions supporting both the JavaScript and the Rust client support both formats with the JavaScript client
14425
+ * implementaiton. However, downgrading to an SDK version that only supports the JavaScript client would not be
14426
+ * possible anymore. Problematic SDK versions have been released before 2025-06-09.
14592
14427
  */
14593
14428
  SyncClientImplementation["RUST"] = "rust";
14594
14429
  })(SyncClientImplementation || (SyncClientImplementation = {}));
@@ -14611,13 +14446,7 @@ const DEFAULT_STREAM_CONNECTION_OPTIONS = {
14611
14446
  serializedSchema: undefined,
14612
14447
  includeDefaultStreams: true
14613
14448
  };
14614
- // The priority we assume when we receive checkpoint lines where no priority is set.
14615
- // This is the default priority used by the sync service, but can be set to an arbitrary
14616
- // value since sync services without priorities also won't send partial sync completion
14617
- // messages.
14618
- const FALLBACK_PRIORITY = 3;
14619
14449
  class AbstractStreamingSyncImplementation extends BaseObserver {
14620
- _lastSyncedAt;
14621
14450
  options;
14622
14451
  abortController;
14623
14452
  // In rare cases, mostly for tests, uploads can be triggered without being properly connected.
@@ -14627,6 +14456,7 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
14627
14456
  streamingSyncPromise;
14628
14457
  logger;
14629
14458
  activeStreams;
14459
+ connectionMayHaveChanged = false;
14630
14460
  isUploadingCrud = false;
14631
14461
  notifyCompletedUploads;
14632
14462
  handleActiveStreamsChange;
@@ -14706,9 +14536,6 @@ class AbstractStreamingSyncImplementation extends BaseObserver {
14706
14536
  this.crudUpdateListener = undefined;
14707
14537
  this.uploadAbortController?.abort();
14708
14538
  }
14709
- async hasCompletedSync() {
14710
- return this.options.adapter.hasCompletedSync();
14711
- }
14712
14539
  async getWriteCheckpoint() {
14713
14540
  const clientId = await this.options.adapter.getClientId();
14714
14541
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
@@ -14790,7 +14617,7 @@ The next upload iteration will be delayed.`);
14790
14617
  });
14791
14618
  }
14792
14619
  }
14793
- this.uploadAbortController = null;
14620
+ this.uploadAbortController = undefined;
14794
14621
  }
14795
14622
  });
14796
14623
  }
@@ -14906,6 +14733,11 @@ The next upload iteration will be delayed.`);
14906
14733
  shouldDelayRetry = false;
14907
14734
  // A disconnect was requested, we should not delay since there is no explicit retry
14908
14735
  }
14736
+ else if (this.connectionMayHaveChanged && ex.message?.indexOf('No iteration is active') >= 0) {
14737
+ this.connectionMayHaveChanged = false;
14738
+ this.logger.info('Sync error after changed connection, retrying immediately');
14739
+ shouldDelayRetry = false;
14740
+ }
14909
14741
  else {
14910
14742
  this.logger.error(ex);
14911
14743
  }
@@ -14936,17 +14768,14 @@ The next upload iteration will be delayed.`);
14936
14768
  // Mark as disconnected if here
14937
14769
  this.updateSyncStatus({ connected: false, connecting: false });
14938
14770
  }
14939
- async collectLocalBucketState() {
14940
- const bucketEntries = await this.options.adapter.getBucketStates();
14941
- const req = bucketEntries.map((entry) => ({
14942
- name: entry.bucket,
14943
- after: entry.op_id
14944
- }));
14945
- const localDescriptions = new Map();
14946
- for (const entry of bucketEntries) {
14947
- localDescriptions.set(entry.bucket, null);
14948
- }
14949
- return [req, localDescriptions];
14771
+ markConnectionMayHaveChanged() {
14772
+ // By setting this field, we'll immediately retry if the next sync event causes an error triggered by us not having
14773
+ // an active sync iteration on the connection in use.
14774
+ this.connectionMayHaveChanged = true;
14775
+ // This triggers a `powersync_control` invocation if a sync iteration is currently active. This is a cheap call to
14776
+ // make when no subscriptions have actually changed, we're mainly interested in this immediately throwing if no
14777
+ // iteration is active. That allows us to reconnect ASAP, instead of having to wait for the next sync line.
14778
+ this.handleActiveStreamsChange?.();
14950
14779
  }
14951
14780
  /**
14952
14781
  * Older versions of the JS SDK used to encode subkeys as JSON in {@link OplogEntry.toJSON}.
@@ -14987,344 +14816,98 @@ The next upload iteration will be delayed.`);
14987
14816
  if (invalidMetadata.length > 0) {
14988
14817
  throw new Error(`Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`);
14989
14818
  }
14990
- const clientImplementation = resolvedOptions.clientImplementation;
14991
- this.updateSyncStatus({ clientImplementation });
14992
- if (clientImplementation == SyncClientImplementation.JAVASCRIPT) {
14993
- await this.legacyStreamingSyncIteration(signal, resolvedOptions);
14994
- return null;
14995
- }
14996
- else {
14997
- await this.requireKeyFormat(true);
14998
- return await this.rustSyncIteration(signal, resolvedOptions);
14999
- }
14819
+ await this.requireKeyFormat(true);
14820
+ return await this.rustSyncIteration(signal, resolvedOptions);
15000
14821
  }
15001
14822
  });
15002
14823
  }
15003
- async legacyStreamingSyncIteration(signal, resolvedOptions) {
15004
- const rawTables = resolvedOptions.serializedSchema?.raw_tables;
15005
- if (rawTables != null && rawTables.length) {
15006
- this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');
15007
- }
15008
- if (this.activeStreams.length) {
15009
- this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');
15010
- }
15011
- this.logger.debug('Streaming sync iteration started');
15012
- this.options.adapter.startSession();
15013
- let [req, bucketMap] = await this.collectLocalBucketState();
15014
- let targetCheckpoint = null;
15015
- // A checkpoint that has been validated but not applied (e.g. due to pending local writes)
15016
- let pendingValidatedCheckpoint = null;
15017
- const clientId = await this.options.adapter.getClientId();
15018
- const usingFixedKeyFormat = await this.requireKeyFormat(false);
15019
- this.logger.debug('Requesting stream from server');
15020
- const syncOptions = {
15021
- path: '/sync/stream',
15022
- abortSignal: signal,
15023
- data: {
15024
- buckets: req,
15025
- include_checksum: true,
15026
- raw_data: true,
15027
- parameters: resolvedOptions.params,
15028
- app_metadata: resolvedOptions.appMetadata,
15029
- client_id: clientId
14824
+ receiveSyncLines(data) {
14825
+ const { options, connection } = data;
14826
+ const remote = this.options.remote;
14827
+ const openInner = async () => {
14828
+ if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
14829
+ return await remote.fetchStream(options);
15030
14830
  }
15031
- };
15032
- let stream;
15033
- if (resolvedOptions?.connectionMethod == SyncStreamConnectionMethod.HTTP) {
15034
- stream = await this.options.remote.postStreamRaw(syncOptions, (line) => {
15035
- if (typeof line == 'string') {
15036
- return JSON.parse(line);
15037
- }
15038
- else {
15039
- // Directly enqueued by us
15040
- return line;
15041
- }
15042
- });
15043
- }
15044
- else {
15045
- const bson = await this.options.remote.getBSON();
15046
- stream = await this.options.remote.socketStreamRaw({
15047
- ...syncOptions,
15048
- ...{ fetchStrategy: resolvedOptions.fetchStrategy }
15049
- }, (payload) => {
15050
- if (payload instanceof Uint8Array) {
15051
- return bson.deserialize(payload);
15052
- }
15053
- else {
15054
- // Directly enqueued by us
15055
- return payload;
15056
- }
15057
- }, bson);
15058
- }
15059
- this.logger.debug('Stream established. Processing events');
15060
- this.notifyCompletedUploads = () => {
15061
- if (!stream.closed) {
15062
- stream.enqueueData({ crud_upload_completed: null });
14831
+ else {
14832
+ return await this.options.remote.socketStreamRaw({
14833
+ ...options,
14834
+ ...{ fetchStrategy: connection.fetchStrategy }
14835
+ });
15063
14836
  }
15064
14837
  };
15065
- while (!stream.closed) {
15066
- const line = await stream.read();
15067
- if (!line) {
15068
- // The stream has closed while waiting
15069
- return;
15070
- }
15071
- if ('crud_upload_completed' in line) {
15072
- if (pendingValidatedCheckpoint != null) {
15073
- const { applied, endIteration } = await this.applyCheckpoint(pendingValidatedCheckpoint);
15074
- if (applied) {
15075
- pendingValidatedCheckpoint = null;
15076
- }
15077
- else if (endIteration) {
15078
- break;
15079
- }
14838
+ let inner;
14839
+ let done = false;
14840
+ return {
14841
+ async next() {
14842
+ if (done) {
14843
+ return doneResult;
15080
14844
  }
15081
- continue;
15082
- }
15083
- // A connection is active and messages are being received
15084
- if (!this.syncStatus.connected) {
15085
- // There is a connection now
15086
- Promise.resolve().then(() => this.triggerCrudUpload());
15087
- this.updateSyncStatus({
15088
- connected: true
15089
- });
15090
- }
15091
- if (isStreamingSyncCheckpoint(line)) {
15092
- targetCheckpoint = line.checkpoint;
15093
- // New checkpoint - existing validated checkpoint is no longer valid
15094
- pendingValidatedCheckpoint = null;
15095
- const bucketsToDelete = new Set(bucketMap.keys());
15096
- const newBuckets = new Map();
15097
- for (const checksum of line.checkpoint.buckets) {
15098
- newBuckets.set(checksum.bucket, {
15099
- name: checksum.bucket,
15100
- priority: checksum.priority ?? FALLBACK_PRIORITY
14845
+ else if (inner == null) {
14846
+ inner = await openInner();
14847
+ // We're connected here, so we can tell the core extension about it.
14848
+ return valueResult({
14849
+ command: PowerSyncControlCommand.CONNECTION_STATE,
14850
+ payload: 'established'
15101
14851
  });
15102
- bucketsToDelete.delete(checksum.bucket);
15103
- }
15104
- if (bucketsToDelete.size > 0) {
15105
- this.logger.debug('Removing buckets', [...bucketsToDelete]);
15106
- }
15107
- bucketMap = newBuckets;
15108
- await this.options.adapter.removeBuckets([...bucketsToDelete]);
15109
- await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
15110
- await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
15111
- }
15112
- else if (isStreamingSyncCheckpointComplete(line)) {
15113
- const result = await this.applyCheckpoint(targetCheckpoint);
15114
- if (result.endIteration) {
15115
- return;
15116
- }
15117
- else if (!result.applied) {
15118
- // "Could not apply checkpoint due to local data". We need to retry after
15119
- // finishing uploads.
15120
- pendingValidatedCheckpoint = targetCheckpoint;
15121
- }
15122
- else {
15123
- // Nothing to retry later. This would likely already be null from the last
15124
- // checksum or checksum_diff operation, but we make sure.
15125
- pendingValidatedCheckpoint = null;
15126
14852
  }
15127
- }
15128
- else if (isStreamingSyncCheckpointPartiallyComplete(line)) {
15129
- const priority = line.partial_checkpoint_complete.priority;
15130
- this.logger.debug('Partial checkpoint complete', priority);
15131
- const result = await this.options.adapter.syncLocalDatabase(targetCheckpoint, priority);
15132
- if (!result.checkpointValid) {
15133
- // This means checksums failed. Start again with a new checkpoint.
15134
- // TODO: better back-off
15135
- await new Promise((resolve) => setTimeout(resolve, 50));
15136
- return;
15137
- }
15138
- else if (!result.ready) ;
15139
14853
  else {
15140
- // We'll keep on downloading, but can report that this priority is synced now.
15141
- this.logger.debug('partial checkpoint validation succeeded');
15142
- // All states with a higher priority can be deleted since this partial sync includes them.
15143
- const priorityStates = this.syncStatus.priorityStatusEntries.filter((s) => s.priority <= priority);
15144
- priorityStates.push({
15145
- priority,
15146
- lastSyncedAt: new Date(),
15147
- hasSynced: true
15148
- });
15149
- this.updateSyncStatus({
15150
- connected: true,
15151
- priorityStatusEntries: priorityStates
15152
- });
15153
- }
15154
- }
15155
- else if (isStreamingSyncCheckpointDiff(line)) {
15156
- // TODO: It may be faster to just keep track of the diff, instead of the entire checkpoint
15157
- if (targetCheckpoint == null) {
15158
- throw new Error('Checkpoint diff without previous checkpoint');
15159
- }
15160
- // New checkpoint - existing validated checkpoint is no longer valid
15161
- pendingValidatedCheckpoint = null;
15162
- const diff = line.checkpoint_diff;
15163
- const newBuckets = new Map();
15164
- for (const checksum of targetCheckpoint.buckets) {
15165
- newBuckets.set(checksum.bucket, checksum);
15166
- }
15167
- for (const checksum of diff.updated_buckets) {
15168
- newBuckets.set(checksum.bucket, checksum);
15169
- }
15170
- for (const bucket of diff.removed_buckets) {
15171
- newBuckets.delete(bucket);
15172
- }
15173
- const newCheckpoint = {
15174
- last_op_id: diff.last_op_id,
15175
- buckets: [...newBuckets.values()],
15176
- write_checkpoint: diff.write_checkpoint
15177
- };
15178
- targetCheckpoint = newCheckpoint;
15179
- await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
15180
- bucketMap = new Map();
15181
- newBuckets.forEach((checksum, name) => bucketMap.set(name, {
15182
- name: checksum.bucket,
15183
- priority: checksum.priority ?? FALLBACK_PRIORITY
15184
- }));
15185
- const bucketsToDelete = diff.removed_buckets;
15186
- if (bucketsToDelete.length > 0) {
15187
- this.logger.debug('Remove buckets', bucketsToDelete);
15188
- }
15189
- await this.options.adapter.removeBuckets(bucketsToDelete);
15190
- await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
15191
- }
15192
- else if (isStreamingSyncData(line)) {
15193
- const { data } = line;
15194
- const previousProgress = this.syncStatus.dataFlowStatus.downloadProgress;
15195
- let updatedProgress = null;
15196
- if (previousProgress) {
15197
- updatedProgress = { ...previousProgress };
15198
- const progressForBucket = updatedProgress[data.bucket];
15199
- if (progressForBucket) {
15200
- updatedProgress[data.bucket] = {
15201
- ...progressForBucket,
15202
- since_last: progressForBucket.since_last + data.data.length
15203
- };
14854
+ const event = await inner.next();
14855
+ if (event.done) {
14856
+ done = true;
14857
+ return valueResult({ command: PowerSyncControlCommand.CONNECTION_STATE, payload: 'end' });
15204
14858
  }
15205
- }
15206
- this.updateSyncStatus({
15207
- dataFlow: {
15208
- downloading: true,
15209
- downloadProgress: updatedProgress
14859
+ else {
14860
+ return valueResult({
14861
+ command: typeof event.value == 'string'
14862
+ ? PowerSyncControlCommand.PROCESS_TEXT_LINE
14863
+ : PowerSyncControlCommand.PROCESS_BSON_LINE,
14864
+ payload: event.value
14865
+ });
15210
14866
  }
15211
- });
15212
- await this.options.adapter.saveSyncData({ buckets: [SyncDataBucket.fromRow(data)] }, usingFixedKeyFormat);
15213
- }
15214
- else if (isStreamingKeepalive(line)) {
15215
- const remaining_seconds = line.token_expires_in;
15216
- if (remaining_seconds == 0) {
15217
- // Connection would be closed automatically right after this
15218
- this.logger.debug('Token expiring; reconnect');
15219
- /**
15220
- * For a rare case where the backend connector does not update the token
15221
- * (uses the same one), this should have some delay.
15222
- */
15223
- await this.delayRetry();
15224
- return;
15225
- }
15226
- else if (remaining_seconds < 30) {
15227
- this.logger.debug('Token will expire soon; reconnect');
15228
- // Pre-emptively refresh the token
15229
- this.options.remote.invalidateCredentials();
15230
- return;
15231
14867
  }
15232
- this.triggerCrudUpload();
15233
- }
15234
- else {
15235
- this.logger.debug('Received unknown sync line', line);
15236
14868
  }
15237
- }
15238
- this.logger.debug('Stream input empty');
15239
- // Connection closed. Likely due to auth issue.
15240
- return;
14869
+ };
15241
14870
  }
15242
14871
  async rustSyncIteration(signal, resolvedOptions) {
15243
14872
  const syncImplementation = this;
15244
14873
  const adapter = this.options.adapter;
15245
14874
  const remote = this.options.remote;
15246
- let receivingLines = null;
15247
- let hadSyncLine = false;
15248
14875
  let hideDisconnectOnRestart = false;
14876
+ let notifyTokenRefreshed;
15249
14877
  if (signal.aborted) {
15250
14878
  throw new AbortOperation('Connection request has been aborted');
15251
14879
  }
15252
- const abortController = new AbortController();
15253
- signal.addEventListener('abort', () => abortController.abort());
15254
- // Pending sync lines received from the service, as well as local events that trigger a powersync_control
15255
- // invocation (local events include refreshed tokens and completed uploads).
15256
- // This is a single data stream so that we can handle all control calls from a single place.
15257
- let controlInvocations = null;
15258
- async function connect(instr) {
15259
- const syncOptions = {
15260
- path: '/sync/stream',
15261
- abortSignal: abortController.signal,
15262
- data: instr.request
14880
+ function startCommand() {
14881
+ const options = {
14882
+ parameters: resolvedOptions.params,
14883
+ app_metadata: resolvedOptions.appMetadata,
14884
+ active_streams: syncImplementation.activeStreams,
14885
+ include_defaults: resolvedOptions.includeDefaultStreams
15263
14886
  };
15264
- if (resolvedOptions.connectionMethod == SyncStreamConnectionMethod.HTTP) {
15265
- controlInvocations = await remote.postStreamRaw(syncOptions, (line) => {
15266
- if (typeof line == 'string') {
15267
- return {
15268
- command: PowerSyncControlCommand.PROCESS_TEXT_LINE,
15269
- payload: line
15270
- };
15271
- }
15272
- else {
15273
- // Directly enqueued by us
15274
- return line;
15275
- }
15276
- });
15277
- }
15278
- else {
15279
- controlInvocations = await remote.socketStreamRaw({
15280
- ...syncOptions,
15281
- fetchStrategy: resolvedOptions.fetchStrategy
15282
- }, (payload) => {
15283
- if (payload instanceof Uint8Array) {
15284
- return {
15285
- command: PowerSyncControlCommand.PROCESS_BSON_LINE,
15286
- payload: payload
15287
- };
15288
- }
15289
- else {
15290
- // Directly enqueued by us
15291
- return payload;
15292
- }
15293
- });
15294
- }
15295
- // The rust client will set connected: true after the first sync line because that's when it gets invoked, but
15296
- // we're already connected here and can report that.
15297
- syncImplementation.updateSyncStatus({ connected: true });
15298
- try {
15299
- while (!controlInvocations.closed) {
15300
- const line = await controlInvocations.read();
15301
- if (line == null) {
15302
- return;
15303
- }
15304
- await control(line.command, line.payload);
15305
- if (!hadSyncLine) {
15306
- syncImplementation.triggerCrudUpload();
15307
- hadSyncLine = true;
15308
- }
15309
- }
15310
- }
15311
- finally {
15312
- const activeInstructions = controlInvocations;
15313
- // We concurrently add events to the active data stream when e.g. a CRUD upload is completed or a token is
15314
- // refreshed. That would throw after closing (and we can't handle those events either way), so set this back
15315
- // to null.
15316
- controlInvocations = null;
15317
- await activeInstructions.close();
14887
+ if (resolvedOptions.serializedSchema) {
14888
+ options.schema = resolvedOptions.serializedSchema;
15318
14889
  }
14890
+ return invokePowerSyncControl(PowerSyncControlCommand.START, JSON.stringify(options));
15319
14891
  }
15320
14892
  async function stop() {
15321
- await control(PowerSyncControlCommand.STOP);
14893
+ const instructions = await invokePowerSyncControl(PowerSyncControlCommand.STOP);
14894
+ for (const instruction of instructions) {
14895
+ // We don't need to handle interrupting instructions since we're unconditionally ending the sync iteration at
14896
+ // this point.
14897
+ if (isInterruptingInstruction(instruction))
14898
+ continue;
14899
+ await handleInstruction(instruction);
14900
+ }
15322
14901
  }
15323
- async function control(op, payload) {
14902
+ async function invokePowerSyncControl(op, payload) {
15324
14903
  const rawResponse = await adapter.control(op, payload ?? null);
15325
14904
  const logger = syncImplementation.logger;
15326
14905
  logger.trace('powersync_control', op, payload == null || typeof payload == 'string' ? payload : '<bytes>', rawResponse);
15327
- await handleInstructions(JSON.parse(rawResponse));
14906
+ if (op != PowerSyncControlCommand.STOP) {
14907
+ // Evidently we have a working connection here, otherwise powersync_control would have failed.
14908
+ syncImplementation.connectionMayHaveChanged = false;
14909
+ }
14910
+ return JSON.parse(rawResponse);
15328
14911
  }
15329
14912
  async function handleInstruction(instruction) {
15330
14913
  if ('LogLine' in instruction) {
@@ -15343,13 +14926,6 @@ The next upload iteration will be delayed.`);
15343
14926
  else if ('UpdateSyncStatus' in instruction) {
15344
14927
  syncImplementation.updateSyncStatus(coreStatusToJs(instruction.UpdateSyncStatus.status));
15345
14928
  }
15346
- else if ('EstablishSyncStream' in instruction) {
15347
- if (receivingLines != null) {
15348
- // Already connected, this shouldn't happen during a single iteration.
15349
- throw 'Unexpected request to establish sync stream, already connected';
15350
- }
15351
- receivingLines = connect(instruction.EstablishSyncStream);
15352
- }
15353
14929
  else if ('FetchCredentials' in instruction) {
15354
14930
  if (instruction.FetchCredentials.did_expire) {
15355
14931
  remote.invalidateCredentials();
@@ -15358,16 +14934,12 @@ The next upload iteration will be delayed.`);
15358
14934
  remote.invalidateCredentials();
15359
14935
  // Restart iteration after the credentials have been refreshed.
15360
14936
  remote.fetchCredentials().then((_) => {
15361
- controlInvocations?.enqueueData({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
14937
+ notifyTokenRefreshed?.();
15362
14938
  }, (err) => {
15363
14939
  syncImplementation.logger.warn('Could not prefetch credentials', err);
15364
14940
  });
15365
14941
  }
15366
14942
  }
15367
- else if ('CloseSyncStream' in instruction) {
15368
- abortController.abort();
15369
- hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
15370
- }
15371
14943
  else if ('FlushFileSystem' in instruction) ;
15372
14944
  else if ('DidCompleteSync' in instruction) {
15373
14945
  syncImplementation.updateSyncStatus({
@@ -15377,105 +14949,83 @@ The next upload iteration will be delayed.`);
15377
14949
  });
15378
14950
  }
15379
14951
  }
15380
- async function handleInstructions(instructions) {
15381
- for (const instr of instructions) {
15382
- await handleInstruction(instr);
15383
- }
15384
- }
15385
14952
  try {
15386
- const options = {
15387
- parameters: resolvedOptions.params,
15388
- app_metadata: resolvedOptions.appMetadata,
15389
- active_streams: this.activeStreams,
15390
- include_defaults: resolvedOptions.includeDefaultStreams
15391
- };
15392
- if (resolvedOptions.serializedSchema) {
15393
- options.schema = resolvedOptions.serializedSchema;
14953
+ const defaultResult = { immediateRestart: false };
14954
+ // Pending sync lines received from the service, as well as local events that trigger a powersync_control
14955
+ // invocation (local events include refreshed tokens and completed uploads).
14956
+ // This is a single data stream so that we can handle all control calls from a single place.
14957
+ let controlInvocations = null;
14958
+ for (const startInstruction of await startCommand()) {
14959
+ if ('EstablishSyncStream' in startInstruction) {
14960
+ const syncOptions = {
14961
+ path: '/sync/stream',
14962
+ abortSignal: signal,
14963
+ data: startInstruction.EstablishSyncStream.request
14964
+ };
14965
+ controlInvocations = injectable(syncImplementation.receiveSyncLines({
14966
+ options: syncOptions,
14967
+ connection: resolvedOptions
14968
+ }));
14969
+ }
14970
+ else if ('CloseSyncStream' in startInstruction) {
14971
+ return defaultResult;
14972
+ }
14973
+ else {
14974
+ await handleInstruction(startInstruction);
14975
+ }
15394
14976
  }
15395
- await control(PowerSyncControlCommand.START, JSON.stringify(options));
14977
+ if (controlInvocations == null)
14978
+ return defaultResult;
15396
14979
  this.notifyCompletedUploads = () => {
15397
- if (controlInvocations && !controlInvocations?.closed) {
15398
- controlInvocations.enqueueData({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
15399
- }
14980
+ controlInvocations.inject({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
15400
14981
  };
15401
14982
  this.handleActiveStreamsChange = () => {
15402
- if (controlInvocations && !controlInvocations?.closed) {
15403
- controlInvocations.enqueueData({
15404
- command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
15405
- payload: JSON.stringify(this.activeStreams)
15406
- });
15407
- }
14983
+ controlInvocations.inject({
14984
+ command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
14985
+ payload: JSON.stringify(this.activeStreams)
14986
+ });
14987
+ };
14988
+ notifyTokenRefreshed = () => {
14989
+ controlInvocations.inject({
14990
+ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED
14991
+ });
15408
14992
  };
15409
- await receivingLines;
14993
+ let hadSyncLine = false;
14994
+ loop: while (true) {
14995
+ const { done, value } = await controlInvocations.next();
14996
+ if (done)
14997
+ break;
14998
+ if (!hadSyncLine) {
14999
+ // Trigger a local CRUD upload when the first sync line has been received, this allows uploading local changes
15000
+ // that have been made while offline or disconnected.
15001
+ if (value.command == PowerSyncControlCommand.PROCESS_TEXT_LINE ||
15002
+ value.command == PowerSyncControlCommand.PROCESS_BSON_LINE) {
15003
+ hadSyncLine = true;
15004
+ this.triggerCrudUpload?.();
15005
+ }
15006
+ }
15007
+ const instructions = await invokePowerSyncControl(value.command, value.payload);
15008
+ for (const instruction of instructions) {
15009
+ if ('EstablishSyncStream' in instruction) {
15010
+ throw new Error('Received EstablishSyncStream while already connected.');
15011
+ }
15012
+ else if ('CloseSyncStream' in instruction) {
15013
+ hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
15014
+ break loop;
15015
+ }
15016
+ else {
15017
+ await handleInstruction(instruction);
15018
+ }
15019
+ }
15020
+ }
15410
15021
  }
15411
15022
  finally {
15412
15023
  this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
15024
+ notifyTokenRefreshed = undefined;
15413
15025
  await stop();
15414
15026
  }
15415
15027
  return { immediateRestart: hideDisconnectOnRestart };
15416
15028
  }
15417
- async updateSyncStatusForStartingCheckpoint(checkpoint) {
15418
- const localProgress = await this.options.adapter.getBucketOperationProgress();
15419
- const progress = {};
15420
- let invalidated = false;
15421
- for (const bucket of checkpoint.buckets) {
15422
- const savedProgress = localProgress[bucket.bucket];
15423
- const atLast = savedProgress?.atLast ?? 0;
15424
- const sinceLast = savedProgress?.sinceLast ?? 0;
15425
- progress[bucket.bucket] = {
15426
- // The fallback priority doesn't matter here, but 3 is the one newer versions of the sync service
15427
- // will use by default.
15428
- priority: bucket.priority ?? 3,
15429
- at_last: atLast,
15430
- since_last: sinceLast,
15431
- target_count: bucket.count ?? 0
15432
- };
15433
- if (bucket.count != null && bucket.count < atLast + sinceLast) {
15434
- // Either due to a defrag / sync rule deploy or a compaction operation, the size
15435
- // of the bucket shrank so much that the local ops exceed the ops in the updated
15436
- // bucket. We can't prossibly report progress in this case (it would overshoot 100%).
15437
- invalidated = true;
15438
- }
15439
- }
15440
- if (invalidated) {
15441
- for (const bucket in progress) {
15442
- const bucketProgress = progress[bucket];
15443
- bucketProgress.at_last = 0;
15444
- bucketProgress.since_last = 0;
15445
- }
15446
- }
15447
- this.updateSyncStatus({
15448
- dataFlow: {
15449
- downloading: true,
15450
- downloadProgress: progress
15451
- }
15452
- });
15453
- }
15454
- async applyCheckpoint(checkpoint) {
15455
- let result = await this.options.adapter.syncLocalDatabase(checkpoint);
15456
- if (!result.checkpointValid) {
15457
- this.logger.debug(`Checksum mismatch in checkpoint ${checkpoint.last_op_id}, will reconnect`);
15458
- // This means checksums failed. Start again with a new checkpoint.
15459
- // TODO: better back-off
15460
- await new Promise((resolve) => setTimeout(resolve, 50));
15461
- return { applied: false, endIteration: true };
15462
- }
15463
- else if (!result.ready) {
15464
- this.logger.debug(`Could not apply checkpoint ${checkpoint.last_op_id} due to local data. We will retry applying the checkpoint after that upload is completed.`);
15465
- return { applied: false, endIteration: false };
15466
- }
15467
- this.logger.debug(`Applied checkpoint ${checkpoint.last_op_id}`, checkpoint);
15468
- this.updateSyncStatus({
15469
- connected: true,
15470
- lastSyncedAt: new Date(),
15471
- dataFlow: {
15472
- downloading: false,
15473
- downloadProgress: null,
15474
- downloadError: undefined
15475
- }
15476
- });
15477
- return { applied: true, endIteration: false };
15478
- }
15479
15029
  updateSyncStatus(options) {
15480
15030
  const updatedStatus = new SyncStatus({
15481
15031
  connected: options.connected ?? this.syncStatus.connected,
@@ -17014,14 +16564,12 @@ class SqliteBucketStorage extends BaseObserver {
17014
16564
  db;
17015
16565
  logger;
17016
16566
  tableNames;
17017
- _hasCompletedSync;
17018
16567
  updateListener;
17019
16568
  _clientId;
17020
16569
  constructor(db, logger = Logger.get('SqliteBucketStorage')) {
17021
16570
  super();
17022
16571
  this.db = db;
17023
16572
  this.logger = logger;
17024
- this._hasCompletedSync = false;
17025
16573
  this.tableNames = new Set();
17026
16574
  this.updateListener = db.registerListener({
17027
16575
  tablesUpdated: (update) => {
@@ -17033,7 +16581,6 @@ class SqliteBucketStorage extends BaseObserver {
17033
16581
  });
17034
16582
  }
17035
16583
  async init() {
17036
- this._hasCompletedSync = false;
17037
16584
  const existingTableRows = await this.db.getAll(`SELECT name FROM sqlite_master WHERE type='table' AND name GLOB 'ps_data_*'`);
17038
16585
  for (const row of existingTableRows ?? []) {
17039
16586
  this.tableNames.add(row.name);
@@ -17055,156 +16602,6 @@ class SqliteBucketStorage extends BaseObserver {
17055
16602
  getMaxOpId() {
17056
16603
  return MAX_OP_ID;
17057
16604
  }
17058
- /**
17059
- * Reset any caches.
17060
- */
17061
- startSession() { }
17062
- async getBucketStates() {
17063
- const result = await this.db.getAll("SELECT name as bucket, cast(last_op as TEXT) as op_id FROM ps_buckets WHERE pending_delete = 0 AND name != '$local'");
17064
- return result;
17065
- }
17066
- async getBucketOperationProgress() {
17067
- const rows = await this.db.getAll('SELECT name, count_at_last, count_since_last FROM ps_buckets');
17068
- return Object.fromEntries(rows.map((r) => [r.name, { atLast: r.count_at_last, sinceLast: r.count_since_last }]));
17069
- }
17070
- async saveSyncData(batch, fixedKeyFormat = false) {
17071
- await this.writeTransaction(async (tx) => {
17072
- for (const b of batch.buckets) {
17073
- await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', [
17074
- 'save',
17075
- JSON.stringify({ buckets: [b.toJSON(fixedKeyFormat)] })
17076
- ]);
17077
- this.logger.debug(`Saved batch of data for bucket: ${b.bucket}, operations: ${b.data.length}`);
17078
- }
17079
- });
17080
- }
17081
- async removeBuckets(buckets) {
17082
- for (const bucket of buckets) {
17083
- await this.deleteBucket(bucket);
17084
- }
17085
- }
17086
- /**
17087
- * Mark a bucket for deletion.
17088
- */
17089
- async deleteBucket(bucket) {
17090
- await this.writeTransaction(async (tx) => {
17091
- await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', ['delete_bucket', bucket]);
17092
- });
17093
- this.logger.debug(`Done deleting bucket ${bucket}`);
17094
- }
17095
- async hasCompletedSync() {
17096
- if (this._hasCompletedSync) {
17097
- return true;
17098
- }
17099
- const r = await this.db.get(`SELECT powersync_last_synced_at() as synced_at`);
17100
- const completed = r.synced_at != null;
17101
- if (completed) {
17102
- this._hasCompletedSync = true;
17103
- }
17104
- return completed;
17105
- }
17106
- async syncLocalDatabase(checkpoint, priority) {
17107
- const r = await this.validateChecksums(checkpoint, priority);
17108
- if (!r.checkpointValid) {
17109
- this.logger.error('Checksums failed for', r.checkpointFailures);
17110
- for (const b of r.checkpointFailures ?? []) {
17111
- await this.deleteBucket(b);
17112
- }
17113
- return { ready: false, checkpointValid: false, checkpointFailures: r.checkpointFailures };
17114
- }
17115
- if (priority == null) {
17116
- this.logger.debug(`Validated checksums checkpoint ${checkpoint.last_op_id}`);
17117
- }
17118
- else {
17119
- this.logger.debug(`Validated checksums for partial checkpoint ${checkpoint.last_op_id}, priority ${priority}`);
17120
- }
17121
- let buckets = checkpoint.buckets;
17122
- if (priority !== undefined) {
17123
- buckets = buckets.filter((b) => hasMatchingPriority(priority, b));
17124
- }
17125
- const bucketNames = buckets.map((b) => b.bucket);
17126
- await this.writeTransaction(async (tx) => {
17127
- await tx.execute(`UPDATE ps_buckets SET last_op = ? WHERE name IN (SELECT json_each.value FROM json_each(?))`, [
17128
- checkpoint.last_op_id,
17129
- JSON.stringify(bucketNames)
17130
- ]);
17131
- if (priority == null && checkpoint.write_checkpoint) {
17132
- await tx.execute("UPDATE ps_buckets SET last_op = ? WHERE name = '$local'", [checkpoint.write_checkpoint]);
17133
- }
17134
- });
17135
- const valid = await this.updateObjectsFromBuckets(checkpoint, priority);
17136
- if (!valid) {
17137
- return { ready: false, checkpointValid: true };
17138
- }
17139
- return {
17140
- ready: true,
17141
- checkpointValid: true
17142
- };
17143
- }
17144
- /**
17145
- * Atomically update the local state to the current checkpoint.
17146
- *
17147
- * This includes creating new tables, dropping old tables, and copying data over from the oplog.
17148
- */
17149
- async updateObjectsFromBuckets(checkpoint, priority) {
17150
- let arg = '';
17151
- if (priority !== undefined) {
17152
- const affectedBuckets = [];
17153
- for (const desc of checkpoint.buckets) {
17154
- if (hasMatchingPriority(priority, desc)) {
17155
- affectedBuckets.push(desc.bucket);
17156
- }
17157
- }
17158
- arg = JSON.stringify({ priority, buckets: affectedBuckets });
17159
- }
17160
- return this.writeTransaction(async (tx) => {
17161
- const { insertId: result } = await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', [
17162
- 'sync_local',
17163
- arg
17164
- ]);
17165
- if (result == 1) {
17166
- if (priority == null) {
17167
- const bucketToCount = Object.fromEntries(checkpoint.buckets.map((b) => [b.bucket, b.count]));
17168
- // The two parameters could be replaced with one, but: https://github.com/powersync-ja/better-sqlite3/pull/6
17169
- const jsonBucketCount = JSON.stringify(bucketToCount);
17170
- await tx.execute("UPDATE ps_buckets SET count_since_last = 0, count_at_last = ?->name WHERE name != '$local' AND ?->name IS NOT NULL", [jsonBucketCount, jsonBucketCount]);
17171
- }
17172
- return true;
17173
- }
17174
- else {
17175
- return false;
17176
- }
17177
- });
17178
- }
17179
- async validateChecksums(checkpoint, priority) {
17180
- if (priority !== undefined) {
17181
- // Only validate the buckets within the priority we care about
17182
- const newBuckets = checkpoint.buckets.filter((cs) => hasMatchingPriority(priority, cs));
17183
- checkpoint = { ...checkpoint, buckets: newBuckets };
17184
- }
17185
- const rs = await this.db.execute('SELECT powersync_validate_checkpoint(?) as result', [
17186
- JSON.stringify({ ...checkpoint })
17187
- ]);
17188
- const resultItem = rs.rows?.item(0);
17189
- if (!resultItem) {
17190
- return {
17191
- checkpointValid: false,
17192
- ready: false,
17193
- checkpointFailures: []
17194
- };
17195
- }
17196
- const result = JSON.parse(resultItem['result']);
17197
- if (result['valid']) {
17198
- return { ready: true, checkpointValid: true };
17199
- }
17200
- else {
17201
- return {
17202
- checkpointValid: false,
17203
- ready: false,
17204
- checkpointFailures: result['failed_buckets']
17205
- };
17206
- }
17207
- }
17208
16605
  async updateLocalTarget(cb) {
17209
16606
  const rs1 = await this.db.getAll("SELECT target_op FROM ps_buckets WHERE name = '$local' AND target_op = CAST(? as INTEGER)", [MAX_OP_ID]);
17210
16607
  if (!rs1.length) {
@@ -17295,12 +16692,6 @@ class SqliteBucketStorage extends BaseObserver {
17295
16692
  async writeTransaction(callback, options) {
17296
16693
  return this.db.writeTransaction(callback, options);
17297
16694
  }
17298
- /**
17299
- * Set a target checkpoint.
17300
- */
17301
- async setTargetCheckpoint(checkpoint) {
17302
- // No-op for now
17303
- }
17304
16695
  async control(op, payload) {
17305
16696
  return await this.writeTransaction(async (tx) => {
17306
16697
  const [[raw]] = await tx.executeRaw('SELECT powersync_control(?, ?)', [op, payload]);
@@ -17324,20 +16715,6 @@ class SqliteBucketStorage extends BaseObserver {
17324
16715
  }
17325
16716
  static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';
17326
16717
  }
17327
- function hasMatchingPriority(priority, bucket) {
17328
- return bucket.priority != null && bucket.priority <= priority;
17329
- }
17330
-
17331
- // TODO JSON
17332
- class SyncDataBatch {
17333
- buckets;
17334
- static fromJSON(json) {
17335
- return new SyncDataBatch(json.buckets.map((bucket) => SyncDataBucket.fromRow(bucket)));
17336
- }
17337
- constructor(buckets) {
17338
- this.buckets = buckets;
17339
- }
17340
- }
17341
16718
 
17342
16719
  /**
17343
16720
  * Thrown when an underlying database connection is closed.
@@ -17397,10 +16774,8 @@ class Schema {
17397
16774
  * developer instead of automatically by PowerSync.
17398
16775
  * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
17399
16776
  * using client-side table and column constraints.
17400
- * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
17401
16777
  *
17402
16778
  * @param tables An object of (table name, raw table definition) entries.
17403
- * @experimental Note that the raw tables API is still experimental and may change in the future.
17404
16779
  */
17405
16780
  withRawTables(tables) {
17406
16781
  for (const [name, rawTableDefinition] of Object.entries(tables)) {
@@ -17773,7 +17148,7 @@ var __webpack_exports__ = {};
17773
17148
  !*** ./lib/src/worker/db/WASQLiteDB.worker.js ***!
17774
17149
  \************************************************/
17775
17150
  __webpack_require__.r(__webpack_exports__);
17776
- /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
17151
+ /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.7.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
17777
17152
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
17778
17153
  /* harmony import */ var comlink__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! comlink */ "../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs");
17779
17154
  /* harmony import */ var _MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./MultiDatabaseServer.js */ "./lib/src/worker/db/MultiDatabaseServer.js");