@powersync/web 1.30.0 → 1.32.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 (112) hide show
  1. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js +1867 -0
  2. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js.map +1 -0
  3. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-2530150.index.umd.js +555 -0
  4. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-2530150.index.umd.js.map +1 -0
  5. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-2530151.index.umd.js +555 -0
  6. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-2530151.index.umd.js.map +1 -0
  7. package/dist/index.umd.js +5022 -38504
  8. package/dist/index.umd.js.map +1 -1
  9. package/dist/worker/SharedSyncImplementation.umd.js +819 -2220
  10. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
  11. package/dist/worker/WASQLiteDB.umd.js +524 -2121
  12. package/dist/worker/WASQLiteDB.umd.js.map +1 -1
  13. package/dist/worker/{node_modules_bson_lib_bson_mjs.umd.js → node_modules_pnpm_bson_6_10_4_node_modules_bson_lib_bson_mjs.umd.js} +8 -8
  14. package/dist/worker/node_modules_pnpm_bson_6_10_4_node_modules_bson_lib_bson_mjs.umd.js.map +1 -0
  15. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-3a94cf.umd.js +44 -0
  16. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-3a94cf.umd.js.map +1 -0
  17. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-868779.umd.js +44 -0
  18. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-868779.umd.js.map +1 -0
  19. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-f60d0d.umd.js +44 -0
  20. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-f60d0d.umd.js.map +1 -0
  21. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +44 -0
  22. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map +1 -0
  23. package/dist/worker/{node_modules_journeyapps_wa-sqlite_src_examples_IDBBatchAtomicVFS_js.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-0d2437.umd.js} +32 -32
  24. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-0d2437.umd.js.map +1 -0
  25. package/dist/worker/{node_modules_journeyapps_wa-sqlite_src_examples_OPFSCoopSyncVFS_js.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-1d4e74.umd.js} +24 -24
  26. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-1d4e74.umd.js.map +1 -0
  27. package/dist/worker/{node_modules_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-3622cf.umd.js} +24 -24
  28. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-3622cf.umd.js.map +1 -0
  29. package/lib/package.json +27 -23
  30. package/lib/src/db/NavigatorTriggerClaimManager.d.ts +6 -0
  31. package/lib/src/db/NavigatorTriggerClaimManager.js +20 -0
  32. package/lib/src/db/PowerSyncDatabase.d.ts +5 -2
  33. package/lib/src/db/PowerSyncDatabase.js +49 -11
  34. package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.d.ts +1 -1
  35. package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.js +1 -1
  36. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.d.ts +2 -2
  37. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.js +2 -2
  38. package/lib/src/db/adapters/AsyncDatabaseConnection.d.ts +1 -1
  39. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.d.ts +21 -4
  40. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.js +116 -22
  41. package/lib/src/db/adapters/WebDBAdapter.d.ts +5 -2
  42. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.d.ts +7 -3
  43. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js +14 -7
  44. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.d.ts +12 -0
  45. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.js +19 -0
  46. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.d.ts +2 -2
  47. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js +11 -2
  48. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.d.ts +4 -4
  49. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.js +6 -6
  50. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +5 -5
  51. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +7 -7
  52. package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.d.ts +1 -1
  53. package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.js +3 -3
  54. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.d.ts +6 -9
  55. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +54 -38
  56. package/lib/src/db/sync/WebRemote.js +1 -1
  57. package/lib/src/db/sync/WebStreamingSyncImplementation.d.ts +1 -1
  58. package/lib/src/db/sync/WebStreamingSyncImplementation.js +1 -1
  59. package/lib/src/index.d.ts +12 -12
  60. package/lib/src/index.js +12 -12
  61. package/lib/src/worker/db/SharedWASQLiteConnection.d.ts +2 -2
  62. package/lib/src/worker/db/WASQLiteDB.worker.js +3 -3
  63. package/lib/src/worker/db/WorkerWASQLiteConnection.d.ts +2 -2
  64. package/lib/src/worker/db/WorkerWASQLiteConnection.js +1 -1
  65. package/lib/src/worker/db/open-worker-database.d.ts +2 -2
  66. package/lib/src/worker/db/open-worker-database.js +1 -1
  67. package/lib/src/worker/sync/BroadcastLogger.d.ts +1 -1
  68. package/lib/src/worker/sync/SharedSyncImplementation.d.ts +21 -11
  69. package/lib/src/worker/sync/SharedSyncImplementation.js +209 -113
  70. package/lib/src/worker/sync/SharedSyncImplementation.worker.js +3 -3
  71. package/lib/src/worker/sync/WorkerClient.d.ts +4 -5
  72. package/lib/src/worker/sync/WorkerClient.js +8 -10
  73. package/lib/tsconfig.tsbuildinfo +1 -1
  74. package/package.json +23 -19
  75. package/src/db/NavigatorTriggerClaimManager.ts +23 -0
  76. package/src/db/PowerSyncDatabase.ts +64 -22
  77. package/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.ts +1 -1
  78. package/src/db/adapters/AbstractWebSQLOpenFactory.ts +3 -3
  79. package/src/db/adapters/AsyncDatabaseConnection.ts +1 -1
  80. package/src/db/adapters/LockedAsyncDatabaseAdapter.ts +138 -33
  81. package/src/db/adapters/WebDBAdapter.ts +6 -2
  82. package/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.ts +20 -8
  83. package/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.ts +23 -0
  84. package/src/db/adapters/wa-sqlite/WASQLiteConnection.ts +13 -5
  85. package/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.ts +8 -8
  86. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +9 -9
  87. package/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.ts +3 -3
  88. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +69 -51
  89. package/src/db/sync/WebRemote.ts +1 -1
  90. package/src/db/sync/WebStreamingSyncImplementation.ts +2 -2
  91. package/src/index.ts +12 -12
  92. package/src/worker/db/SharedWASQLiteConnection.ts +2 -2
  93. package/src/worker/db/WASQLiteDB.worker.ts +5 -6
  94. package/src/worker/db/WorkerWASQLiteConnection.ts +2 -2
  95. package/src/worker/db/open-worker-database.ts +2 -2
  96. package/src/worker/sync/BroadcastLogger.ts +1 -1
  97. package/src/worker/sync/SharedSyncImplementation.ts +241 -126
  98. package/src/worker/sync/SharedSyncImplementation.worker.ts +3 -3
  99. package/src/worker/sync/WorkerClient.ts +10 -14
  100. package/dist/worker/node_modules_bson_lib_bson_mjs.umd.js.map +0 -1
  101. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite-async_mjs.umd.js +0 -44
  102. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite-async_mjs.umd.js.map +0 -1
  103. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite_mjs.umd.js +0 -44
  104. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite_mjs.umd.js.map +0 -1
  105. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_wa-sqlite-async_mjs.umd.js +0 -44
  106. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_wa-sqlite-async_mjs.umd.js.map +0 -1
  107. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +0 -44
  108. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map +0 -1
  109. package/dist/worker/node_modules_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js.umd.js.map +0 -1
  110. package/dist/worker/node_modules_journeyapps_wa-sqlite_src_examples_IDBBatchAtomicVFS_js.umd.js.map +0 -1
  111. package/dist/worker/node_modules_journeyapps_wa-sqlite_src_examples_OPFSCoopSyncVFS_js.umd.js.map +0 -1
  112. /package/bin/{powersync.js → powersync.cjs} +0 -0
@@ -3,11 +3,11 @@ var sdk_web;
3
3
  /******/ "use strict";
4
4
  /******/ var __webpack_modules__ = ({
5
5
 
6
- /***/ "../../node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js":
7
- /*!*******************************************************************!*\
8
- !*** ../../node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js ***!
9
- \*******************************************************************/
10
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6
+ /***/ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js"
7
+ /*!*******************************************************************************************************************!*\
8
+ !*** ../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js ***!
9
+ \*******************************************************************************************************************/
10
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
11
11
 
12
12
  __webpack_require__.r(__webpack_exports__);
13
13
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -246,7 +246,7 @@ __webpack_require__.r(__webpack_exports__);
246
246
  /* harmony export */ SQLITE_WARNING: () => (/* reexport safe */ _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__.SQLITE_WARNING),
247
247
  /* harmony export */ SQLiteError: () => (/* binding */ SQLiteError)
248
248
  /* harmony export */ });
249
- /* harmony import */ var _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sqlite-constants.js */ "../../node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js");
249
+ /* harmony import */ var _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sqlite-constants.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js");
250
250
  // Copyright 2021 Roy T. Hashimoto. All Rights Reserved.
251
251
 
252
252
 
@@ -1147,8 +1147,11 @@ function Factory(Module) {
1147
1147
  // Wait for all pending retry operations to complete. This is
1148
1148
  // normally empty on the first loop iteration.
1149
1149
  if (Module.retryOps.length) {
1150
- await Promise.all(Module.retryOps);
1151
- Module.retryOps = [];
1150
+ try {
1151
+ await Promise.all(Module.retryOps);
1152
+ } finally {
1153
+ Module.retryOps = [];
1154
+ }
1152
1155
  }
1153
1156
 
1154
1157
  rc = await f();
@@ -1193,13 +1196,13 @@ function decl(s) {
1193
1196
  }
1194
1197
 
1195
1198
 
1196
- /***/ }),
1199
+ /***/ },
1197
1200
 
1198
- /***/ "../../node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js":
1199
- /*!*************************************************************************!*\
1200
- !*** ../../node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js ***!
1201
- \*************************************************************************/
1202
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1201
+ /***/ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js"
1202
+ /*!*************************************************************************************************************************!*\
1203
+ !*** ../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js ***!
1204
+ \*************************************************************************************************************************/
1205
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
1203
1206
 
1204
1207
  __webpack_require__.r(__webpack_exports__);
1205
1208
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -1712,13 +1715,13 @@ const SQLITE_PREPARE_PERSISTENT = 0x01;
1712
1715
  const SQLITE_PREPARE_NORMALIZED = 0x02;
1713
1716
  const SQLITE_PREPARE_NO_VTAB = 0x04;
1714
1717
 
1715
- /***/ }),
1718
+ /***/ },
1716
1719
 
1717
- /***/ "../../node_modules/async-mutex/index.mjs":
1718
- /*!************************************************!*\
1719
- !*** ../../node_modules/async-mutex/index.mjs ***!
1720
- \************************************************/
1721
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1720
+ /***/ "../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs"
1721
+ /*!*************************************************************************************!*\
1722
+ !*** ../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs ***!
1723
+ \*************************************************************************************/
1724
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
1722
1725
 
1723
1726
  __webpack_require__.r(__webpack_exports__);
1724
1727
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -2023,13 +2026,13 @@ function tryAcquire(sync, alreadyAcquiredError = E_ALREADY_LOCKED) {
2023
2026
 
2024
2027
 
2025
2028
 
2026
- /***/ }),
2029
+ /***/ },
2027
2030
 
2028
- /***/ "../../node_modules/comlink/dist/esm/comlink.mjs":
2029
- /*!*******************************************************!*\
2030
- !*** ../../node_modules/comlink/dist/esm/comlink.mjs ***!
2031
- \*******************************************************/
2032
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2031
+ /***/ "../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs"
2032
+ /*!****************************************************************************************!*\
2033
+ !*** ../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs ***!
2034
+ \****************************************************************************************/
2035
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2033
2036
 
2034
2037
  __webpack_require__.r(__webpack_exports__);
2035
2038
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -2404,13 +2407,13 @@ function generateUUID() {
2404
2407
  //# sourceMappingURL=comlink.mjs.map
2405
2408
 
2406
2409
 
2407
- /***/ }),
2410
+ /***/ },
2408
2411
 
2409
- /***/ "../common/dist/bundle.mjs":
2412
+ /***/ "../common/dist/bundle.mjs"
2410
2413
  /*!*********************************!*\
2411
2414
  !*** ../common/dist/bundle.mjs ***!
2412
2415
  \*********************************/
2413
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2416
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2414
2417
 
2415
2418
  __webpack_require__.r(__webpack_exports__);
2416
2419
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -2424,6 +2427,7 @@ __webpack_require__.r(__webpack_exports__);
2424
2427
  /* harmony export */ BaseObserver: () => (/* binding */ BaseObserver),
2425
2428
  /* harmony export */ Column: () => (/* binding */ Column),
2426
2429
  /* harmony export */ ColumnType: () => (/* binding */ ColumnType),
2430
+ /* harmony export */ ConnectionClosedError: () => (/* binding */ ConnectionClosedError),
2427
2431
  /* harmony export */ ConnectionManager: () => (/* binding */ ConnectionManager),
2428
2432
  /* harmony export */ ControlledExecutor: () => (/* binding */ ControlledExecutor),
2429
2433
  /* harmony export */ CrudBatch: () => (/* binding */ CrudBatch),
@@ -2462,12 +2466,14 @@ __webpack_require__.r(__webpack_exports__);
2462
2466
  /* harmony export */ LogLevel: () => (/* binding */ LogLevel),
2463
2467
  /* harmony export */ MAX_AMOUNT_OF_COLUMNS: () => (/* binding */ MAX_AMOUNT_OF_COLUMNS),
2464
2468
  /* harmony export */ MAX_OP_ID: () => (/* binding */ MAX_OP_ID),
2469
+ /* harmony export */ MEMORY_TRIGGER_CLAIM_MANAGER: () => (/* binding */ MEMORY_TRIGGER_CLAIM_MANAGER),
2465
2470
  /* harmony export */ OnChangeQueryProcessor: () => (/* binding */ OnChangeQueryProcessor),
2466
2471
  /* harmony export */ OpType: () => (/* binding */ OpType),
2467
2472
  /* harmony export */ OpTypeEnum: () => (/* binding */ OpTypeEnum),
2468
2473
  /* harmony export */ OplogEntry: () => (/* binding */ OplogEntry),
2469
2474
  /* harmony export */ PSInternalTable: () => (/* binding */ PSInternalTable),
2470
2475
  /* harmony export */ PowerSyncControlCommand: () => (/* binding */ PowerSyncControlCommand),
2476
+ /* harmony export */ RawTable: () => (/* binding */ RawTable),
2471
2477
  /* harmony export */ RowUpdateType: () => (/* binding */ RowUpdateType),
2472
2478
  /* harmony export */ Schema: () => (/* binding */ Schema),
2473
2479
  /* harmony export */ SqliteBucketStorage: () => (/* binding */ SqliteBucketStorage),
@@ -2479,6 +2485,7 @@ __webpack_require__.r(__webpack_exports__);
2479
2485
  /* harmony export */ SyncStreamConnectionMethod: () => (/* binding */ SyncStreamConnectionMethod),
2480
2486
  /* harmony export */ Table: () => (/* binding */ Table),
2481
2487
  /* harmony export */ TableV2: () => (/* binding */ TableV2),
2488
+ /* harmony export */ TriggerManagerImpl: () => (/* binding */ TriggerManagerImpl),
2482
2489
  /* harmony export */ UpdateType: () => (/* binding */ UpdateType),
2483
2490
  /* harmony export */ UploadQueueStats: () => (/* binding */ UploadQueueStats),
2484
2491
  /* harmony export */ WatchedQueryListenerEvent: () => (/* binding */ WatchedQueryListenerEvent),
@@ -2505,7 +2512,7 @@ __webpack_require__.r(__webpack_exports__);
2505
2512
  /* harmony export */ sanitizeSQL: () => (/* binding */ sanitizeSQL),
2506
2513
  /* harmony export */ sanitizeUUID: () => (/* binding */ sanitizeUUID)
2507
2514
  /* harmony export */ });
2508
- /* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! async-mutex */ "../../node_modules/async-mutex/index.mjs");
2515
+ /* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! async-mutex */ "../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs");
2509
2516
 
2510
2517
 
2511
2518
  function getDefaultExportFromCjs (x) {
@@ -3228,12 +3235,30 @@ class SyncStatus {
3228
3235
  return {
3229
3236
  connected: this.connected,
3230
3237
  connecting: this.connecting,
3231
- dataFlow: this.dataFlowStatus,
3238
+ dataFlow: {
3239
+ ...this.dataFlowStatus,
3240
+ uploadError: this.serializeError(this.dataFlowStatus.uploadError),
3241
+ downloadError: this.serializeError(this.dataFlowStatus.downloadError)
3242
+ },
3232
3243
  lastSyncedAt: this.lastSyncedAt,
3233
3244
  hasSynced: this.hasSynced,
3234
3245
  priorityStatusEntries: this.priorityStatusEntries
3235
3246
  };
3236
3247
  }
3248
+ /**
3249
+ * Not all errors are serializable over a MessagePort. E.g. some `DomExceptions` fail to be passed across workers.
3250
+ * This explicitly serializes errors in the SyncStatus.
3251
+ */
3252
+ serializeError(error) {
3253
+ if (typeof error == 'undefined') {
3254
+ return undefined;
3255
+ }
3256
+ return {
3257
+ name: error.name,
3258
+ message: error.message,
3259
+ stack: error.stack
3260
+ };
3261
+ }
3237
3262
  static comparePriorities(a, b) {
3238
3263
  return b.priority - a.priority; // Reverse because higher priorities have lower numbers
3239
3264
  }
@@ -4577,7 +4602,7 @@ class SyncDataBucket {
4577
4602
  }
4578
4603
  }
4579
4604
 
4580
- var buffer$1 = {};
4605
+ var buffer = {};
4581
4606
 
4582
4607
  var base64Js = {};
4583
4608
 
@@ -4841,12 +4866,12 @@ function requireIeee754 () {
4841
4866
  * @license MIT
4842
4867
  */
4843
4868
 
4844
- var hasRequiredBuffer$1;
4869
+ var hasRequiredBuffer;
4845
4870
 
4846
- function requireBuffer$1 () {
4847
- if (hasRequiredBuffer$1) return buffer$1;
4848
- hasRequiredBuffer$1 = 1;
4849
- (function (exports) {
4871
+ function requireBuffer () {
4872
+ if (hasRequiredBuffer) return buffer;
4873
+ hasRequiredBuffer = 1;
4874
+ (function (exports$1) {
4850
4875
 
4851
4876
  const base64 = requireBase64Js();
4852
4877
  const ieee754 = requireIeee754();
@@ -4855,12 +4880,12 @@ function requireBuffer$1 () {
4855
4880
  ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
4856
4881
  : null;
4857
4882
 
4858
- exports.Buffer = Buffer;
4859
- exports.SlowBuffer = SlowBuffer;
4860
- exports.INSPECT_MAX_BYTES = 50;
4883
+ exports$1.Buffer = Buffer;
4884
+ exports$1.SlowBuffer = SlowBuffer;
4885
+ exports$1.INSPECT_MAX_BYTES = 50;
4861
4886
 
4862
4887
  const K_MAX_LENGTH = 0x7fffffff;
4863
- exports.kMaxLength = K_MAX_LENGTH;
4888
+ exports$1.kMaxLength = K_MAX_LENGTH;
4864
4889
 
4865
4890
  /**
4866
4891
  * If `Buffer.TYPED_ARRAY_SUPPORT`:
@@ -5456,7 +5481,7 @@ function requireBuffer$1 () {
5456
5481
 
5457
5482
  Buffer.prototype.inspect = function inspect () {
5458
5483
  let str = '';
5459
- const max = exports.INSPECT_MAX_BYTES;
5484
+ const max = exports$1.INSPECT_MAX_BYTES;
5460
5485
  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
5461
5486
  if (this.length > max) str += ' ... ';
5462
5487
  return '<Buffer ' + str + '>'
@@ -6940,1845 +6965,16 @@ function requireBuffer$1 () {
6940
6965
  }
6941
6966
 
6942
6967
  function BufferBigIntNotDefined () {
6943
- throw new Error('BigInt not supported')
6944
- }
6945
- } (buffer$1));
6946
- return buffer$1;
6947
- }
6948
-
6949
- var bufferExports$1 = requireBuffer$1();
6950
-
6951
- var dist = {};
6952
-
6953
- var buffer = {};
6954
-
6955
- /*!
6956
- * The buffer module from node.js, for the browser.
6957
- *
6958
- * @author Feross Aboukhadijeh <https://feross.org>
6959
- * @license MIT
6960
- */
6961
-
6962
- var hasRequiredBuffer;
6963
-
6964
- function requireBuffer () {
6965
- if (hasRequiredBuffer) return buffer;
6966
- hasRequiredBuffer = 1;
6967
- (function (exports) {
6968
-
6969
- var base64 = requireBase64Js();
6970
- var ieee754 = requireIeee754();
6971
- var customInspectSymbol =
6972
- (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
6973
- ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
6974
- : null;
6975
-
6976
- exports.Buffer = Buffer;
6977
- exports.SlowBuffer = SlowBuffer;
6978
- exports.INSPECT_MAX_BYTES = 50;
6979
-
6980
- var K_MAX_LENGTH = 0x7fffffff;
6981
- exports.kMaxLength = K_MAX_LENGTH;
6982
-
6983
- /**
6984
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
6985
- * === true Use Uint8Array implementation (fastest)
6986
- * === false Print warning and recommend using `buffer` v4.x which has an Object
6987
- * implementation (most compatible, even IE6)
6988
- *
6989
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
6990
- * Opera 11.6+, iOS 4.2+.
6991
- *
6992
- * We report that the browser does not support typed arrays if the are not subclassable
6993
- * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
6994
- * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
6995
- * for __proto__ and has a buggy typed array implementation.
6996
- */
6997
- Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
6998
-
6999
- if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
7000
- typeof console.error === 'function') {
7001
- console.error(
7002
- 'This browser lacks typed array (Uint8Array) support which is required by ' +
7003
- '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
7004
- );
7005
- }
7006
-
7007
- function typedArraySupport () {
7008
- // Can typed array instances can be augmented?
7009
- try {
7010
- var arr = new Uint8Array(1);
7011
- var proto = { foo: function () { return 42 } };
7012
- Object.setPrototypeOf(proto, Uint8Array.prototype);
7013
- Object.setPrototypeOf(arr, proto);
7014
- return arr.foo() === 42
7015
- } catch (e) {
7016
- return false
7017
- }
7018
- }
7019
-
7020
- Object.defineProperty(Buffer.prototype, 'parent', {
7021
- enumerable: true,
7022
- get: function () {
7023
- if (!Buffer.isBuffer(this)) return undefined
7024
- return this.buffer
7025
- }
7026
- });
7027
-
7028
- Object.defineProperty(Buffer.prototype, 'offset', {
7029
- enumerable: true,
7030
- get: function () {
7031
- if (!Buffer.isBuffer(this)) return undefined
7032
- return this.byteOffset
7033
- }
7034
- });
7035
-
7036
- function createBuffer (length) {
7037
- if (length > K_MAX_LENGTH) {
7038
- throw new RangeError('The value "' + length + '" is invalid for option "size"')
7039
- }
7040
- // Return an augmented `Uint8Array` instance
7041
- var buf = new Uint8Array(length);
7042
- Object.setPrototypeOf(buf, Buffer.prototype);
7043
- return buf
7044
- }
7045
-
7046
- /**
7047
- * The Buffer constructor returns instances of `Uint8Array` that have their
7048
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
7049
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
7050
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
7051
- * returns a single octet.
7052
- *
7053
- * The `Uint8Array` prototype remains unmodified.
7054
- */
7055
-
7056
- function Buffer (arg, encodingOrOffset, length) {
7057
- // Common case.
7058
- if (typeof arg === 'number') {
7059
- if (typeof encodingOrOffset === 'string') {
7060
- throw new TypeError(
7061
- 'The "string" argument must be of type string. Received type number'
7062
- )
7063
- }
7064
- return allocUnsafe(arg)
7065
- }
7066
- return from(arg, encodingOrOffset, length)
7067
- }
7068
-
7069
- Buffer.poolSize = 8192; // not used by this implementation
7070
-
7071
- function from (value, encodingOrOffset, length) {
7072
- if (typeof value === 'string') {
7073
- return fromString(value, encodingOrOffset)
7074
- }
7075
-
7076
- if (ArrayBuffer.isView(value)) {
7077
- return fromArrayView(value)
7078
- }
7079
-
7080
- if (value == null) {
7081
- throw new TypeError(
7082
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
7083
- 'or Array-like Object. Received type ' + (typeof value)
7084
- )
7085
- }
7086
-
7087
- if (isInstance(value, ArrayBuffer) ||
7088
- (value && isInstance(value.buffer, ArrayBuffer))) {
7089
- return fromArrayBuffer(value, encodingOrOffset, length)
7090
- }
7091
-
7092
- if (typeof SharedArrayBuffer !== 'undefined' &&
7093
- (isInstance(value, SharedArrayBuffer) ||
7094
- (value && isInstance(value.buffer, SharedArrayBuffer)))) {
7095
- return fromArrayBuffer(value, encodingOrOffset, length)
7096
- }
7097
-
7098
- if (typeof value === 'number') {
7099
- throw new TypeError(
7100
- 'The "value" argument must not be of type number. Received type number'
7101
- )
7102
- }
7103
-
7104
- var valueOf = value.valueOf && value.valueOf();
7105
- if (valueOf != null && valueOf !== value) {
7106
- return Buffer.from(valueOf, encodingOrOffset, length)
7107
- }
7108
-
7109
- var b = fromObject(value);
7110
- if (b) return b
7111
-
7112
- if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
7113
- typeof value[Symbol.toPrimitive] === 'function') {
7114
- return Buffer.from(
7115
- value[Symbol.toPrimitive]('string'), encodingOrOffset, length
7116
- )
7117
- }
7118
-
7119
- throw new TypeError(
7120
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
7121
- 'or Array-like Object. Received type ' + (typeof value)
7122
- )
7123
- }
7124
-
7125
- /**
7126
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
7127
- * if value is a number.
7128
- * Buffer.from(str[, encoding])
7129
- * Buffer.from(array)
7130
- * Buffer.from(buffer)
7131
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
7132
- **/
7133
- Buffer.from = function (value, encodingOrOffset, length) {
7134
- return from(value, encodingOrOffset, length)
7135
- };
7136
-
7137
- // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
7138
- // https://github.com/feross/buffer/pull/148
7139
- Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
7140
- Object.setPrototypeOf(Buffer, Uint8Array);
7141
-
7142
- function assertSize (size) {
7143
- if (typeof size !== 'number') {
7144
- throw new TypeError('"size" argument must be of type number')
7145
- } else if (size < 0) {
7146
- throw new RangeError('The value "' + size + '" is invalid for option "size"')
7147
- }
7148
- }
7149
-
7150
- function alloc (size, fill, encoding) {
7151
- assertSize(size);
7152
- if (size <= 0) {
7153
- return createBuffer(size)
7154
- }
7155
- if (fill !== undefined) {
7156
- // Only pay attention to encoding if it's a string. This
7157
- // prevents accidentally sending in a number that would
7158
- // be interpreted as a start offset.
7159
- return typeof encoding === 'string'
7160
- ? createBuffer(size).fill(fill, encoding)
7161
- : createBuffer(size).fill(fill)
7162
- }
7163
- return createBuffer(size)
7164
- }
7165
-
7166
- /**
7167
- * Creates a new filled Buffer instance.
7168
- * alloc(size[, fill[, encoding]])
7169
- **/
7170
- Buffer.alloc = function (size, fill, encoding) {
7171
- return alloc(size, fill, encoding)
7172
- };
7173
-
7174
- function allocUnsafe (size) {
7175
- assertSize(size);
7176
- return createBuffer(size < 0 ? 0 : checked(size) | 0)
7177
- }
7178
-
7179
- /**
7180
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
7181
- * */
7182
- Buffer.allocUnsafe = function (size) {
7183
- return allocUnsafe(size)
7184
- };
7185
- /**
7186
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
7187
- */
7188
- Buffer.allocUnsafeSlow = function (size) {
7189
- return allocUnsafe(size)
7190
- };
7191
-
7192
- function fromString (string, encoding) {
7193
- if (typeof encoding !== 'string' || encoding === '') {
7194
- encoding = 'utf8';
7195
- }
7196
-
7197
- if (!Buffer.isEncoding(encoding)) {
7198
- throw new TypeError('Unknown encoding: ' + encoding)
7199
- }
7200
-
7201
- var length = byteLength(string, encoding) | 0;
7202
- var buf = createBuffer(length);
7203
-
7204
- var actual = buf.write(string, encoding);
7205
-
7206
- if (actual !== length) {
7207
- // Writing a hex string, for example, that contains invalid characters will
7208
- // cause everything after the first invalid character to be ignored. (e.g.
7209
- // 'abxxcd' will be treated as 'ab')
7210
- buf = buf.slice(0, actual);
7211
- }
7212
-
7213
- return buf
7214
- }
7215
-
7216
- function fromArrayLike (array) {
7217
- var length = array.length < 0 ? 0 : checked(array.length) | 0;
7218
- var buf = createBuffer(length);
7219
- for (var i = 0; i < length; i += 1) {
7220
- buf[i] = array[i] & 255;
7221
- }
7222
- return buf
7223
- }
7224
-
7225
- function fromArrayView (arrayView) {
7226
- if (isInstance(arrayView, Uint8Array)) {
7227
- var copy = new Uint8Array(arrayView);
7228
- return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
7229
- }
7230
- return fromArrayLike(arrayView)
7231
- }
7232
-
7233
- function fromArrayBuffer (array, byteOffset, length) {
7234
- if (byteOffset < 0 || array.byteLength < byteOffset) {
7235
- throw new RangeError('"offset" is outside of buffer bounds')
7236
- }
7237
-
7238
- if (array.byteLength < byteOffset + (length || 0)) {
7239
- throw new RangeError('"length" is outside of buffer bounds')
7240
- }
7241
-
7242
- var buf;
7243
- if (byteOffset === undefined && length === undefined) {
7244
- buf = new Uint8Array(array);
7245
- } else if (length === undefined) {
7246
- buf = new Uint8Array(array, byteOffset);
7247
- } else {
7248
- buf = new Uint8Array(array, byteOffset, length);
7249
- }
7250
-
7251
- // Return an augmented `Uint8Array` instance
7252
- Object.setPrototypeOf(buf, Buffer.prototype);
7253
-
7254
- return buf
7255
- }
7256
-
7257
- function fromObject (obj) {
7258
- if (Buffer.isBuffer(obj)) {
7259
- var len = checked(obj.length) | 0;
7260
- var buf = createBuffer(len);
7261
-
7262
- if (buf.length === 0) {
7263
- return buf
7264
- }
7265
-
7266
- obj.copy(buf, 0, 0, len);
7267
- return buf
7268
- }
7269
-
7270
- if (obj.length !== undefined) {
7271
- if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
7272
- return createBuffer(0)
7273
- }
7274
- return fromArrayLike(obj)
7275
- }
7276
-
7277
- if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
7278
- return fromArrayLike(obj.data)
7279
- }
7280
- }
7281
-
7282
- function checked (length) {
7283
- // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
7284
- // length is NaN (which is otherwise coerced to zero.)
7285
- if (length >= K_MAX_LENGTH) {
7286
- throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
7287
- 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
7288
- }
7289
- return length | 0
7290
- }
7291
-
7292
- function SlowBuffer (length) {
7293
- if (+length != length) { // eslint-disable-line eqeqeq
7294
- length = 0;
7295
- }
7296
- return Buffer.alloc(+length)
7297
- }
7298
-
7299
- Buffer.isBuffer = function isBuffer (b) {
7300
- return b != null && b._isBuffer === true &&
7301
- b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
7302
- };
7303
-
7304
- Buffer.compare = function compare (a, b) {
7305
- if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
7306
- if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
7307
- if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
7308
- throw new TypeError(
7309
- 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
7310
- )
7311
- }
7312
-
7313
- if (a === b) return 0
7314
-
7315
- var x = a.length;
7316
- var y = b.length;
7317
-
7318
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
7319
- if (a[i] !== b[i]) {
7320
- x = a[i];
7321
- y = b[i];
7322
- break
7323
- }
7324
- }
7325
-
7326
- if (x < y) return -1
7327
- if (y < x) return 1
7328
- return 0
7329
- };
7330
-
7331
- Buffer.isEncoding = function isEncoding (encoding) {
7332
- switch (String(encoding).toLowerCase()) {
7333
- case 'hex':
7334
- case 'utf8':
7335
- case 'utf-8':
7336
- case 'ascii':
7337
- case 'latin1':
7338
- case 'binary':
7339
- case 'base64':
7340
- case 'ucs2':
7341
- case 'ucs-2':
7342
- case 'utf16le':
7343
- case 'utf-16le':
7344
- return true
7345
- default:
7346
- return false
7347
- }
7348
- };
7349
-
7350
- Buffer.concat = function concat (list, length) {
7351
- if (!Array.isArray(list)) {
7352
- throw new TypeError('"list" argument must be an Array of Buffers')
7353
- }
7354
-
7355
- if (list.length === 0) {
7356
- return Buffer.alloc(0)
7357
- }
7358
-
7359
- var i;
7360
- if (length === undefined) {
7361
- length = 0;
7362
- for (i = 0; i < list.length; ++i) {
7363
- length += list[i].length;
7364
- }
7365
- }
7366
-
7367
- var buffer = Buffer.allocUnsafe(length);
7368
- var pos = 0;
7369
- for (i = 0; i < list.length; ++i) {
7370
- var buf = list[i];
7371
- if (isInstance(buf, Uint8Array)) {
7372
- if (pos + buf.length > buffer.length) {
7373
- Buffer.from(buf).copy(buffer, pos);
7374
- } else {
7375
- Uint8Array.prototype.set.call(
7376
- buffer,
7377
- buf,
7378
- pos
7379
- );
7380
- }
7381
- } else if (!Buffer.isBuffer(buf)) {
7382
- throw new TypeError('"list" argument must be an Array of Buffers')
7383
- } else {
7384
- buf.copy(buffer, pos);
7385
- }
7386
- pos += buf.length;
7387
- }
7388
- return buffer
7389
- };
7390
-
7391
- function byteLength (string, encoding) {
7392
- if (Buffer.isBuffer(string)) {
7393
- return string.length
7394
- }
7395
- if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
7396
- return string.byteLength
7397
- }
7398
- if (typeof string !== 'string') {
7399
- throw new TypeError(
7400
- 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
7401
- 'Received type ' + typeof string
7402
- )
7403
- }
7404
-
7405
- var len = string.length;
7406
- var mustMatch = (arguments.length > 2 && arguments[2] === true);
7407
- if (!mustMatch && len === 0) return 0
7408
-
7409
- // Use a for loop to avoid recursion
7410
- var loweredCase = false;
7411
- for (;;) {
7412
- switch (encoding) {
7413
- case 'ascii':
7414
- case 'latin1':
7415
- case 'binary':
7416
- return len
7417
- case 'utf8':
7418
- case 'utf-8':
7419
- return utf8ToBytes(string).length
7420
- case 'ucs2':
7421
- case 'ucs-2':
7422
- case 'utf16le':
7423
- case 'utf-16le':
7424
- return len * 2
7425
- case 'hex':
7426
- return len >>> 1
7427
- case 'base64':
7428
- return base64ToBytes(string).length
7429
- default:
7430
- if (loweredCase) {
7431
- return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
7432
- }
7433
- encoding = ('' + encoding).toLowerCase();
7434
- loweredCase = true;
7435
- }
7436
- }
7437
- }
7438
- Buffer.byteLength = byteLength;
7439
-
7440
- function slowToString (encoding, start, end) {
7441
- var loweredCase = false;
7442
-
7443
- // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
7444
- // property of a typed array.
7445
-
7446
- // This behaves neither like String nor Uint8Array in that we set start/end
7447
- // to their upper/lower bounds if the value passed is out of range.
7448
- // undefined is handled specially as per ECMA-262 6th Edition,
7449
- // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
7450
- if (start === undefined || start < 0) {
7451
- start = 0;
7452
- }
7453
- // Return early if start > this.length. Done here to prevent potential uint32
7454
- // coercion fail below.
7455
- if (start > this.length) {
7456
- return ''
7457
- }
7458
-
7459
- if (end === undefined || end > this.length) {
7460
- end = this.length;
7461
- }
7462
-
7463
- if (end <= 0) {
7464
- return ''
7465
- }
7466
-
7467
- // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
7468
- end >>>= 0;
7469
- start >>>= 0;
7470
-
7471
- if (end <= start) {
7472
- return ''
7473
- }
7474
-
7475
- if (!encoding) encoding = 'utf8';
7476
-
7477
- while (true) {
7478
- switch (encoding) {
7479
- case 'hex':
7480
- return hexSlice(this, start, end)
7481
-
7482
- case 'utf8':
7483
- case 'utf-8':
7484
- return utf8Slice(this, start, end)
7485
-
7486
- case 'ascii':
7487
- return asciiSlice(this, start, end)
7488
-
7489
- case 'latin1':
7490
- case 'binary':
7491
- return latin1Slice(this, start, end)
7492
-
7493
- case 'base64':
7494
- return base64Slice(this, start, end)
7495
-
7496
- case 'ucs2':
7497
- case 'ucs-2':
7498
- case 'utf16le':
7499
- case 'utf-16le':
7500
- return utf16leSlice(this, start, end)
7501
-
7502
- default:
7503
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7504
- encoding = (encoding + '').toLowerCase();
7505
- loweredCase = true;
7506
- }
7507
- }
7508
- }
7509
-
7510
- // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
7511
- // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
7512
- // reliably in a browserify context because there could be multiple different
7513
- // copies of the 'buffer' package in use. This method works even for Buffer
7514
- // instances that were created from another copy of the `buffer` package.
7515
- // See: https://github.com/feross/buffer/issues/154
7516
- Buffer.prototype._isBuffer = true;
7517
-
7518
- function swap (b, n, m) {
7519
- var i = b[n];
7520
- b[n] = b[m];
7521
- b[m] = i;
7522
- }
7523
-
7524
- Buffer.prototype.swap16 = function swap16 () {
7525
- var len = this.length;
7526
- if (len % 2 !== 0) {
7527
- throw new RangeError('Buffer size must be a multiple of 16-bits')
7528
- }
7529
- for (var i = 0; i < len; i += 2) {
7530
- swap(this, i, i + 1);
7531
- }
7532
- return this
7533
- };
7534
-
7535
- Buffer.prototype.swap32 = function swap32 () {
7536
- var len = this.length;
7537
- if (len % 4 !== 0) {
7538
- throw new RangeError('Buffer size must be a multiple of 32-bits')
7539
- }
7540
- for (var i = 0; i < len; i += 4) {
7541
- swap(this, i, i + 3);
7542
- swap(this, i + 1, i + 2);
7543
- }
7544
- return this
7545
- };
7546
-
7547
- Buffer.prototype.swap64 = function swap64 () {
7548
- var len = this.length;
7549
- if (len % 8 !== 0) {
7550
- throw new RangeError('Buffer size must be a multiple of 64-bits')
7551
- }
7552
- for (var i = 0; i < len; i += 8) {
7553
- swap(this, i, i + 7);
7554
- swap(this, i + 1, i + 6);
7555
- swap(this, i + 2, i + 5);
7556
- swap(this, i + 3, i + 4);
7557
- }
7558
- return this
7559
- };
7560
-
7561
- Buffer.prototype.toString = function toString () {
7562
- var length = this.length;
7563
- if (length === 0) return ''
7564
- if (arguments.length === 0) return utf8Slice(this, 0, length)
7565
- return slowToString.apply(this, arguments)
7566
- };
7567
-
7568
- Buffer.prototype.toLocaleString = Buffer.prototype.toString;
7569
-
7570
- Buffer.prototype.equals = function equals (b) {
7571
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
7572
- if (this === b) return true
7573
- return Buffer.compare(this, b) === 0
7574
- };
7575
-
7576
- Buffer.prototype.inspect = function inspect () {
7577
- var str = '';
7578
- var max = exports.INSPECT_MAX_BYTES;
7579
- str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
7580
- if (this.length > max) str += ' ... ';
7581
- return '<Buffer ' + str + '>'
7582
- };
7583
- if (customInspectSymbol) {
7584
- Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
7585
- }
7586
-
7587
- Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
7588
- if (isInstance(target, Uint8Array)) {
7589
- target = Buffer.from(target, target.offset, target.byteLength);
7590
- }
7591
- if (!Buffer.isBuffer(target)) {
7592
- throw new TypeError(
7593
- 'The "target" argument must be one of type Buffer or Uint8Array. ' +
7594
- 'Received type ' + (typeof target)
7595
- )
7596
- }
7597
-
7598
- if (start === undefined) {
7599
- start = 0;
7600
- }
7601
- if (end === undefined) {
7602
- end = target ? target.length : 0;
7603
- }
7604
- if (thisStart === undefined) {
7605
- thisStart = 0;
7606
- }
7607
- if (thisEnd === undefined) {
7608
- thisEnd = this.length;
7609
- }
7610
-
7611
- if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
7612
- throw new RangeError('out of range index')
7613
- }
7614
-
7615
- if (thisStart >= thisEnd && start >= end) {
7616
- return 0
7617
- }
7618
- if (thisStart >= thisEnd) {
7619
- return -1
7620
- }
7621
- if (start >= end) {
7622
- return 1
7623
- }
7624
-
7625
- start >>>= 0;
7626
- end >>>= 0;
7627
- thisStart >>>= 0;
7628
- thisEnd >>>= 0;
7629
-
7630
- if (this === target) return 0
7631
-
7632
- var x = thisEnd - thisStart;
7633
- var y = end - start;
7634
- var len = Math.min(x, y);
7635
-
7636
- var thisCopy = this.slice(thisStart, thisEnd);
7637
- var targetCopy = target.slice(start, end);
7638
-
7639
- for (var i = 0; i < len; ++i) {
7640
- if (thisCopy[i] !== targetCopy[i]) {
7641
- x = thisCopy[i];
7642
- y = targetCopy[i];
7643
- break
7644
- }
7645
- }
7646
-
7647
- if (x < y) return -1
7648
- if (y < x) return 1
7649
- return 0
7650
- };
7651
-
7652
- // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
7653
- // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
7654
- //
7655
- // Arguments:
7656
- // - buffer - a Buffer to search
7657
- // - val - a string, Buffer, or number
7658
- // - byteOffset - an index into `buffer`; will be clamped to an int32
7659
- // - encoding - an optional encoding, relevant is val is a string
7660
- // - dir - true for indexOf, false for lastIndexOf
7661
- function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
7662
- // Empty buffer means no match
7663
- if (buffer.length === 0) return -1
7664
-
7665
- // Normalize byteOffset
7666
- if (typeof byteOffset === 'string') {
7667
- encoding = byteOffset;
7668
- byteOffset = 0;
7669
- } else if (byteOffset > 0x7fffffff) {
7670
- byteOffset = 0x7fffffff;
7671
- } else if (byteOffset < -2147483648) {
7672
- byteOffset = -2147483648;
7673
- }
7674
- byteOffset = +byteOffset; // Coerce to Number.
7675
- if (numberIsNaN(byteOffset)) {
7676
- // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
7677
- byteOffset = dir ? 0 : (buffer.length - 1);
7678
- }
7679
-
7680
- // Normalize byteOffset: negative offsets start from the end of the buffer
7681
- if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
7682
- if (byteOffset >= buffer.length) {
7683
- if (dir) return -1
7684
- else byteOffset = buffer.length - 1;
7685
- } else if (byteOffset < 0) {
7686
- if (dir) byteOffset = 0;
7687
- else return -1
7688
- }
7689
-
7690
- // Normalize val
7691
- if (typeof val === 'string') {
7692
- val = Buffer.from(val, encoding);
7693
- }
7694
-
7695
- // Finally, search either indexOf (if dir is true) or lastIndexOf
7696
- if (Buffer.isBuffer(val)) {
7697
- // Special case: looking for empty string/buffer always fails
7698
- if (val.length === 0) {
7699
- return -1
7700
- }
7701
- return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
7702
- } else if (typeof val === 'number') {
7703
- val = val & 0xFF; // Search for a byte value [0-255]
7704
- if (typeof Uint8Array.prototype.indexOf === 'function') {
7705
- if (dir) {
7706
- return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
7707
- } else {
7708
- return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
7709
- }
7710
- }
7711
- return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
7712
- }
7713
-
7714
- throw new TypeError('val must be string, number or Buffer')
7715
- }
7716
-
7717
- function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
7718
- var indexSize = 1;
7719
- var arrLength = arr.length;
7720
- var valLength = val.length;
7721
-
7722
- if (encoding !== undefined) {
7723
- encoding = String(encoding).toLowerCase();
7724
- if (encoding === 'ucs2' || encoding === 'ucs-2' ||
7725
- encoding === 'utf16le' || encoding === 'utf-16le') {
7726
- if (arr.length < 2 || val.length < 2) {
7727
- return -1
7728
- }
7729
- indexSize = 2;
7730
- arrLength /= 2;
7731
- valLength /= 2;
7732
- byteOffset /= 2;
7733
- }
7734
- }
7735
-
7736
- function read (buf, i) {
7737
- if (indexSize === 1) {
7738
- return buf[i]
7739
- } else {
7740
- return buf.readUInt16BE(i * indexSize)
7741
- }
7742
- }
7743
-
7744
- var i;
7745
- if (dir) {
7746
- var foundIndex = -1;
7747
- for (i = byteOffset; i < arrLength; i++) {
7748
- if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
7749
- if (foundIndex === -1) foundIndex = i;
7750
- if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
7751
- } else {
7752
- if (foundIndex !== -1) i -= i - foundIndex;
7753
- foundIndex = -1;
7754
- }
7755
- }
7756
- } else {
7757
- if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
7758
- for (i = byteOffset; i >= 0; i--) {
7759
- var found = true;
7760
- for (var j = 0; j < valLength; j++) {
7761
- if (read(arr, i + j) !== read(val, j)) {
7762
- found = false;
7763
- break
7764
- }
7765
- }
7766
- if (found) return i
7767
- }
7768
- }
7769
-
7770
- return -1
7771
- }
7772
-
7773
- Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
7774
- return this.indexOf(val, byteOffset, encoding) !== -1
7775
- };
7776
-
7777
- Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
7778
- return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
7779
- };
7780
-
7781
- Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
7782
- return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
7783
- };
7784
-
7785
- function hexWrite (buf, string, offset, length) {
7786
- offset = Number(offset) || 0;
7787
- var remaining = buf.length - offset;
7788
- if (!length) {
7789
- length = remaining;
7790
- } else {
7791
- length = Number(length);
7792
- if (length > remaining) {
7793
- length = remaining;
7794
- }
7795
- }
7796
-
7797
- var strLen = string.length;
7798
-
7799
- if (length > strLen / 2) {
7800
- length = strLen / 2;
7801
- }
7802
- for (var i = 0; i < length; ++i) {
7803
- var parsed = parseInt(string.substr(i * 2, 2), 16);
7804
- if (numberIsNaN(parsed)) return i
7805
- buf[offset + i] = parsed;
7806
- }
7807
- return i
7808
- }
7809
-
7810
- function utf8Write (buf, string, offset, length) {
7811
- return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
7812
- }
7813
-
7814
- function asciiWrite (buf, string, offset, length) {
7815
- return blitBuffer(asciiToBytes(string), buf, offset, length)
7816
- }
7817
-
7818
- function base64Write (buf, string, offset, length) {
7819
- return blitBuffer(base64ToBytes(string), buf, offset, length)
7820
- }
7821
-
7822
- function ucs2Write (buf, string, offset, length) {
7823
- return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
7824
- }
7825
-
7826
- Buffer.prototype.write = function write (string, offset, length, encoding) {
7827
- // Buffer#write(string)
7828
- if (offset === undefined) {
7829
- encoding = 'utf8';
7830
- length = this.length;
7831
- offset = 0;
7832
- // Buffer#write(string, encoding)
7833
- } else if (length === undefined && typeof offset === 'string') {
7834
- encoding = offset;
7835
- length = this.length;
7836
- offset = 0;
7837
- // Buffer#write(string, offset[, length][, encoding])
7838
- } else if (isFinite(offset)) {
7839
- offset = offset >>> 0;
7840
- if (isFinite(length)) {
7841
- length = length >>> 0;
7842
- if (encoding === undefined) encoding = 'utf8';
7843
- } else {
7844
- encoding = length;
7845
- length = undefined;
7846
- }
7847
- } else {
7848
- throw new Error(
7849
- 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
7850
- )
7851
- }
7852
-
7853
- var remaining = this.length - offset;
7854
- if (length === undefined || length > remaining) length = remaining;
7855
-
7856
- if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
7857
- throw new RangeError('Attempt to write outside buffer bounds')
7858
- }
7859
-
7860
- if (!encoding) encoding = 'utf8';
7861
-
7862
- var loweredCase = false;
7863
- for (;;) {
7864
- switch (encoding) {
7865
- case 'hex':
7866
- return hexWrite(this, string, offset, length)
7867
-
7868
- case 'utf8':
7869
- case 'utf-8':
7870
- return utf8Write(this, string, offset, length)
7871
-
7872
- case 'ascii':
7873
- case 'latin1':
7874
- case 'binary':
7875
- return asciiWrite(this, string, offset, length)
7876
-
7877
- case 'base64':
7878
- // Warning: maxLength not taken into account in base64Write
7879
- return base64Write(this, string, offset, length)
7880
-
7881
- case 'ucs2':
7882
- case 'ucs-2':
7883
- case 'utf16le':
7884
- case 'utf-16le':
7885
- return ucs2Write(this, string, offset, length)
7886
-
7887
- default:
7888
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7889
- encoding = ('' + encoding).toLowerCase();
7890
- loweredCase = true;
7891
- }
7892
- }
7893
- };
7894
-
7895
- Buffer.prototype.toJSON = function toJSON () {
7896
- return {
7897
- type: 'Buffer',
7898
- data: Array.prototype.slice.call(this._arr || this, 0)
7899
- }
7900
- };
7901
-
7902
- function base64Slice (buf, start, end) {
7903
- if (start === 0 && end === buf.length) {
7904
- return base64.fromByteArray(buf)
7905
- } else {
7906
- return base64.fromByteArray(buf.slice(start, end))
7907
- }
7908
- }
7909
-
7910
- function utf8Slice (buf, start, end) {
7911
- end = Math.min(buf.length, end);
7912
- var res = [];
7913
-
7914
- var i = start;
7915
- while (i < end) {
7916
- var firstByte = buf[i];
7917
- var codePoint = null;
7918
- var bytesPerSequence = (firstByte > 0xEF)
7919
- ? 4
7920
- : (firstByte > 0xDF)
7921
- ? 3
7922
- : (firstByte > 0xBF)
7923
- ? 2
7924
- : 1;
7925
-
7926
- if (i + bytesPerSequence <= end) {
7927
- var secondByte, thirdByte, fourthByte, tempCodePoint;
7928
-
7929
- switch (bytesPerSequence) {
7930
- case 1:
7931
- if (firstByte < 0x80) {
7932
- codePoint = firstByte;
7933
- }
7934
- break
7935
- case 2:
7936
- secondByte = buf[i + 1];
7937
- if ((secondByte & 0xC0) === 0x80) {
7938
- tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
7939
- if (tempCodePoint > 0x7F) {
7940
- codePoint = tempCodePoint;
7941
- }
7942
- }
7943
- break
7944
- case 3:
7945
- secondByte = buf[i + 1];
7946
- thirdByte = buf[i + 2];
7947
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
7948
- tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
7949
- if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
7950
- codePoint = tempCodePoint;
7951
- }
7952
- }
7953
- break
7954
- case 4:
7955
- secondByte = buf[i + 1];
7956
- thirdByte = buf[i + 2];
7957
- fourthByte = buf[i + 3];
7958
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
7959
- tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
7960
- if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
7961
- codePoint = tempCodePoint;
7962
- }
7963
- }
7964
- }
7965
- }
7966
-
7967
- if (codePoint === null) {
7968
- // we did not generate a valid codePoint so insert a
7969
- // replacement char (U+FFFD) and advance only 1 byte
7970
- codePoint = 0xFFFD;
7971
- bytesPerSequence = 1;
7972
- } else if (codePoint > 0xFFFF) {
7973
- // encode to utf16 (surrogate pair dance)
7974
- codePoint -= 0x10000;
7975
- res.push(codePoint >>> 10 & 0x3FF | 0xD800);
7976
- codePoint = 0xDC00 | codePoint & 0x3FF;
7977
- }
7978
-
7979
- res.push(codePoint);
7980
- i += bytesPerSequence;
7981
- }
7982
-
7983
- return decodeCodePointsArray(res)
7984
- }
7985
-
7986
- // Based on http://stackoverflow.com/a/22747272/680742, the browser with
7987
- // the lowest limit is Chrome, with 0x10000 args.
7988
- // We go 1 magnitude less, for safety
7989
- var MAX_ARGUMENTS_LENGTH = 0x1000;
7990
-
7991
- function decodeCodePointsArray (codePoints) {
7992
- var len = codePoints.length;
7993
- if (len <= MAX_ARGUMENTS_LENGTH) {
7994
- return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
7995
- }
7996
-
7997
- // Decode in chunks to avoid "call stack size exceeded".
7998
- var res = '';
7999
- var i = 0;
8000
- while (i < len) {
8001
- res += String.fromCharCode.apply(
8002
- String,
8003
- codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
8004
- );
8005
- }
8006
- return res
8007
- }
8008
-
8009
- function asciiSlice (buf, start, end) {
8010
- var ret = '';
8011
- end = Math.min(buf.length, end);
8012
-
8013
- for (var i = start; i < end; ++i) {
8014
- ret += String.fromCharCode(buf[i] & 0x7F);
8015
- }
8016
- return ret
8017
- }
8018
-
8019
- function latin1Slice (buf, start, end) {
8020
- var ret = '';
8021
- end = Math.min(buf.length, end);
8022
-
8023
- for (var i = start; i < end; ++i) {
8024
- ret += String.fromCharCode(buf[i]);
8025
- }
8026
- return ret
8027
- }
8028
-
8029
- function hexSlice (buf, start, end) {
8030
- var len = buf.length;
8031
-
8032
- if (!start || start < 0) start = 0;
8033
- if (!end || end < 0 || end > len) end = len;
8034
-
8035
- var out = '';
8036
- for (var i = start; i < end; ++i) {
8037
- out += hexSliceLookupTable[buf[i]];
8038
- }
8039
- return out
8040
- }
8041
-
8042
- function utf16leSlice (buf, start, end) {
8043
- var bytes = buf.slice(start, end);
8044
- var res = '';
8045
- // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
8046
- for (var i = 0; i < bytes.length - 1; i += 2) {
8047
- res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256));
8048
- }
8049
- return res
8050
- }
8051
-
8052
- Buffer.prototype.slice = function slice (start, end) {
8053
- var len = this.length;
8054
- start = ~~start;
8055
- end = end === undefined ? len : ~~end;
8056
-
8057
- if (start < 0) {
8058
- start += len;
8059
- if (start < 0) start = 0;
8060
- } else if (start > len) {
8061
- start = len;
8062
- }
8063
-
8064
- if (end < 0) {
8065
- end += len;
8066
- if (end < 0) end = 0;
8067
- } else if (end > len) {
8068
- end = len;
8069
- }
8070
-
8071
- if (end < start) end = start;
8072
-
8073
- var newBuf = this.subarray(start, end);
8074
- // Return an augmented `Uint8Array` instance
8075
- Object.setPrototypeOf(newBuf, Buffer.prototype);
8076
-
8077
- return newBuf
8078
- };
8079
-
8080
- /*
8081
- * Need to make sure that buffer isn't trying to write out of bounds.
8082
- */
8083
- function checkOffset (offset, ext, length) {
8084
- if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
8085
- if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
8086
- }
8087
-
8088
- Buffer.prototype.readUintLE =
8089
- Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
8090
- offset = offset >>> 0;
8091
- byteLength = byteLength >>> 0;
8092
- if (!noAssert) checkOffset(offset, byteLength, this.length);
8093
-
8094
- var val = this[offset];
8095
- var mul = 1;
8096
- var i = 0;
8097
- while (++i < byteLength && (mul *= 0x100)) {
8098
- val += this[offset + i] * mul;
8099
- }
8100
-
8101
- return val
8102
- };
8103
-
8104
- Buffer.prototype.readUintBE =
8105
- Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
8106
- offset = offset >>> 0;
8107
- byteLength = byteLength >>> 0;
8108
- if (!noAssert) {
8109
- checkOffset(offset, byteLength, this.length);
8110
- }
8111
-
8112
- var val = this[offset + --byteLength];
8113
- var mul = 1;
8114
- while (byteLength > 0 && (mul *= 0x100)) {
8115
- val += this[offset + --byteLength] * mul;
8116
- }
8117
-
8118
- return val
8119
- };
8120
-
8121
- Buffer.prototype.readUint8 =
8122
- Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
8123
- offset = offset >>> 0;
8124
- if (!noAssert) checkOffset(offset, 1, this.length);
8125
- return this[offset]
8126
- };
8127
-
8128
- Buffer.prototype.readUint16LE =
8129
- Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
8130
- offset = offset >>> 0;
8131
- if (!noAssert) checkOffset(offset, 2, this.length);
8132
- return this[offset] | (this[offset + 1] << 8)
8133
- };
8134
-
8135
- Buffer.prototype.readUint16BE =
8136
- Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
8137
- offset = offset >>> 0;
8138
- if (!noAssert) checkOffset(offset, 2, this.length);
8139
- return (this[offset] << 8) | this[offset + 1]
8140
- };
8141
-
8142
- Buffer.prototype.readUint32LE =
8143
- Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
8144
- offset = offset >>> 0;
8145
- if (!noAssert) checkOffset(offset, 4, this.length);
8146
-
8147
- return ((this[offset]) |
8148
- (this[offset + 1] << 8) |
8149
- (this[offset + 2] << 16)) +
8150
- (this[offset + 3] * 0x1000000)
8151
- };
8152
-
8153
- Buffer.prototype.readUint32BE =
8154
- Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
8155
- offset = offset >>> 0;
8156
- if (!noAssert) checkOffset(offset, 4, this.length);
8157
-
8158
- return (this[offset] * 0x1000000) +
8159
- ((this[offset + 1] << 16) |
8160
- (this[offset + 2] << 8) |
8161
- this[offset + 3])
8162
- };
8163
-
8164
- Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
8165
- offset = offset >>> 0;
8166
- byteLength = byteLength >>> 0;
8167
- if (!noAssert) checkOffset(offset, byteLength, this.length);
8168
-
8169
- var val = this[offset];
8170
- var mul = 1;
8171
- var i = 0;
8172
- while (++i < byteLength && (mul *= 0x100)) {
8173
- val += this[offset + i] * mul;
8174
- }
8175
- mul *= 0x80;
8176
-
8177
- if (val >= mul) val -= Math.pow(2, 8 * byteLength);
8178
-
8179
- return val
8180
- };
8181
-
8182
- Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
8183
- offset = offset >>> 0;
8184
- byteLength = byteLength >>> 0;
8185
- if (!noAssert) checkOffset(offset, byteLength, this.length);
8186
-
8187
- var i = byteLength;
8188
- var mul = 1;
8189
- var val = this[offset + --i];
8190
- while (i > 0 && (mul *= 0x100)) {
8191
- val += this[offset + --i] * mul;
8192
- }
8193
- mul *= 0x80;
8194
-
8195
- if (val >= mul) val -= Math.pow(2, 8 * byteLength);
8196
-
8197
- return val
8198
- };
8199
-
8200
- Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
8201
- offset = offset >>> 0;
8202
- if (!noAssert) checkOffset(offset, 1, this.length);
8203
- if (!(this[offset] & 0x80)) return (this[offset])
8204
- return ((0xff - this[offset] + 1) * -1)
8205
- };
8206
-
8207
- Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
8208
- offset = offset >>> 0;
8209
- if (!noAssert) checkOffset(offset, 2, this.length);
8210
- var val = this[offset] | (this[offset + 1] << 8);
8211
- return (val & 0x8000) ? val | 0xFFFF0000 : val
8212
- };
8213
-
8214
- Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
8215
- offset = offset >>> 0;
8216
- if (!noAssert) checkOffset(offset, 2, this.length);
8217
- var val = this[offset + 1] | (this[offset] << 8);
8218
- return (val & 0x8000) ? val | 0xFFFF0000 : val
8219
- };
8220
-
8221
- Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
8222
- offset = offset >>> 0;
8223
- if (!noAssert) checkOffset(offset, 4, this.length);
8224
-
8225
- return (this[offset]) |
8226
- (this[offset + 1] << 8) |
8227
- (this[offset + 2] << 16) |
8228
- (this[offset + 3] << 24)
8229
- };
8230
-
8231
- Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
8232
- offset = offset >>> 0;
8233
- if (!noAssert) checkOffset(offset, 4, this.length);
8234
-
8235
- return (this[offset] << 24) |
8236
- (this[offset + 1] << 16) |
8237
- (this[offset + 2] << 8) |
8238
- (this[offset + 3])
8239
- };
8240
-
8241
- Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
8242
- offset = offset >>> 0;
8243
- if (!noAssert) checkOffset(offset, 4, this.length);
8244
- return ieee754.read(this, offset, true, 23, 4)
8245
- };
8246
-
8247
- Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
8248
- offset = offset >>> 0;
8249
- if (!noAssert) checkOffset(offset, 4, this.length);
8250
- return ieee754.read(this, offset, false, 23, 4)
8251
- };
8252
-
8253
- Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
8254
- offset = offset >>> 0;
8255
- if (!noAssert) checkOffset(offset, 8, this.length);
8256
- return ieee754.read(this, offset, true, 52, 8)
8257
- };
8258
-
8259
- Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
8260
- offset = offset >>> 0;
8261
- if (!noAssert) checkOffset(offset, 8, this.length);
8262
- return ieee754.read(this, offset, false, 52, 8)
8263
- };
8264
-
8265
- function checkInt (buf, value, offset, ext, max, min) {
8266
- if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
8267
- if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
8268
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
8269
- }
8270
-
8271
- Buffer.prototype.writeUintLE =
8272
- Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
8273
- value = +value;
8274
- offset = offset >>> 0;
8275
- byteLength = byteLength >>> 0;
8276
- if (!noAssert) {
8277
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
8278
- checkInt(this, value, offset, byteLength, maxBytes, 0);
8279
- }
8280
-
8281
- var mul = 1;
8282
- var i = 0;
8283
- this[offset] = value & 0xFF;
8284
- while (++i < byteLength && (mul *= 0x100)) {
8285
- this[offset + i] = (value / mul) & 0xFF;
8286
- }
8287
-
8288
- return offset + byteLength
8289
- };
8290
-
8291
- Buffer.prototype.writeUintBE =
8292
- Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
8293
- value = +value;
8294
- offset = offset >>> 0;
8295
- byteLength = byteLength >>> 0;
8296
- if (!noAssert) {
8297
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
8298
- checkInt(this, value, offset, byteLength, maxBytes, 0);
8299
- }
8300
-
8301
- var i = byteLength - 1;
8302
- var mul = 1;
8303
- this[offset + i] = value & 0xFF;
8304
- while (--i >= 0 && (mul *= 0x100)) {
8305
- this[offset + i] = (value / mul) & 0xFF;
8306
- }
8307
-
8308
- return offset + byteLength
8309
- };
8310
-
8311
- Buffer.prototype.writeUint8 =
8312
- Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
8313
- value = +value;
8314
- offset = offset >>> 0;
8315
- if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
8316
- this[offset] = (value & 0xff);
8317
- return offset + 1
8318
- };
8319
-
8320
- Buffer.prototype.writeUint16LE =
8321
- Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
8322
- value = +value;
8323
- offset = offset >>> 0;
8324
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
8325
- this[offset] = (value & 0xff);
8326
- this[offset + 1] = (value >>> 8);
8327
- return offset + 2
8328
- };
8329
-
8330
- Buffer.prototype.writeUint16BE =
8331
- Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
8332
- value = +value;
8333
- offset = offset >>> 0;
8334
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
8335
- this[offset] = (value >>> 8);
8336
- this[offset + 1] = (value & 0xff);
8337
- return offset + 2
8338
- };
8339
-
8340
- Buffer.prototype.writeUint32LE =
8341
- Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
8342
- value = +value;
8343
- offset = offset >>> 0;
8344
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
8345
- this[offset + 3] = (value >>> 24);
8346
- this[offset + 2] = (value >>> 16);
8347
- this[offset + 1] = (value >>> 8);
8348
- this[offset] = (value & 0xff);
8349
- return offset + 4
8350
- };
8351
-
8352
- Buffer.prototype.writeUint32BE =
8353
- Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
8354
- value = +value;
8355
- offset = offset >>> 0;
8356
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
8357
- this[offset] = (value >>> 24);
8358
- this[offset + 1] = (value >>> 16);
8359
- this[offset + 2] = (value >>> 8);
8360
- this[offset + 3] = (value & 0xff);
8361
- return offset + 4
8362
- };
8363
-
8364
- Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
8365
- value = +value;
8366
- offset = offset >>> 0;
8367
- if (!noAssert) {
8368
- var limit = Math.pow(2, (8 * byteLength) - 1);
8369
-
8370
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
8371
- }
8372
-
8373
- var i = 0;
8374
- var mul = 1;
8375
- var sub = 0;
8376
- this[offset] = value & 0xFF;
8377
- while (++i < byteLength && (mul *= 0x100)) {
8378
- if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
8379
- sub = 1;
8380
- }
8381
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
8382
- }
8383
-
8384
- return offset + byteLength
8385
- };
8386
-
8387
- Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
8388
- value = +value;
8389
- offset = offset >>> 0;
8390
- if (!noAssert) {
8391
- var limit = Math.pow(2, (8 * byteLength) - 1);
8392
-
8393
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
8394
- }
8395
-
8396
- var i = byteLength - 1;
8397
- var mul = 1;
8398
- var sub = 0;
8399
- this[offset + i] = value & 0xFF;
8400
- while (--i >= 0 && (mul *= 0x100)) {
8401
- if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
8402
- sub = 1;
8403
- }
8404
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
8405
- }
8406
-
8407
- return offset + byteLength
8408
- };
8409
-
8410
- Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
8411
- value = +value;
8412
- offset = offset >>> 0;
8413
- if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -128);
8414
- if (value < 0) value = 0xff + value + 1;
8415
- this[offset] = (value & 0xff);
8416
- return offset + 1
8417
- };
8418
-
8419
- Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
8420
- value = +value;
8421
- offset = offset >>> 0;
8422
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
8423
- this[offset] = (value & 0xff);
8424
- this[offset + 1] = (value >>> 8);
8425
- return offset + 2
8426
- };
8427
-
8428
- Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
8429
- value = +value;
8430
- offset = offset >>> 0;
8431
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
8432
- this[offset] = (value >>> 8);
8433
- this[offset + 1] = (value & 0xff);
8434
- return offset + 2
8435
- };
8436
-
8437
- Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
8438
- value = +value;
8439
- offset = offset >>> 0;
8440
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
8441
- this[offset] = (value & 0xff);
8442
- this[offset + 1] = (value >>> 8);
8443
- this[offset + 2] = (value >>> 16);
8444
- this[offset + 3] = (value >>> 24);
8445
- return offset + 4
8446
- };
8447
-
8448
- Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
8449
- value = +value;
8450
- offset = offset >>> 0;
8451
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
8452
- if (value < 0) value = 0xffffffff + value + 1;
8453
- this[offset] = (value >>> 24);
8454
- this[offset + 1] = (value >>> 16);
8455
- this[offset + 2] = (value >>> 8);
8456
- this[offset + 3] = (value & 0xff);
8457
- return offset + 4
8458
- };
8459
-
8460
- function checkIEEE754 (buf, value, offset, ext, max, min) {
8461
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
8462
- if (offset < 0) throw new RangeError('Index out of range')
8463
- }
8464
-
8465
- function writeFloat (buf, value, offset, littleEndian, noAssert) {
8466
- value = +value;
8467
- offset = offset >>> 0;
8468
- if (!noAssert) {
8469
- checkIEEE754(buf, value, offset, 4);
8470
- }
8471
- ieee754.write(buf, value, offset, littleEndian, 23, 4);
8472
- return offset + 4
8473
- }
8474
-
8475
- Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
8476
- return writeFloat(this, value, offset, true, noAssert)
8477
- };
8478
-
8479
- Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
8480
- return writeFloat(this, value, offset, false, noAssert)
8481
- };
8482
-
8483
- function writeDouble (buf, value, offset, littleEndian, noAssert) {
8484
- value = +value;
8485
- offset = offset >>> 0;
8486
- if (!noAssert) {
8487
- checkIEEE754(buf, value, offset, 8);
8488
- }
8489
- ieee754.write(buf, value, offset, littleEndian, 52, 8);
8490
- return offset + 8
8491
- }
8492
-
8493
- Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
8494
- return writeDouble(this, value, offset, true, noAssert)
8495
- };
8496
-
8497
- Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
8498
- return writeDouble(this, value, offset, false, noAssert)
8499
- };
8500
-
8501
- // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
8502
- Buffer.prototype.copy = function copy (target, targetStart, start, end) {
8503
- if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
8504
- if (!start) start = 0;
8505
- if (!end && end !== 0) end = this.length;
8506
- if (targetStart >= target.length) targetStart = target.length;
8507
- if (!targetStart) targetStart = 0;
8508
- if (end > 0 && end < start) end = start;
8509
-
8510
- // Copy 0 bytes; we're done
8511
- if (end === start) return 0
8512
- if (target.length === 0 || this.length === 0) return 0
8513
-
8514
- // Fatal error conditions
8515
- if (targetStart < 0) {
8516
- throw new RangeError('targetStart out of bounds')
8517
- }
8518
- if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
8519
- if (end < 0) throw new RangeError('sourceEnd out of bounds')
8520
-
8521
- // Are we oob?
8522
- if (end > this.length) end = this.length;
8523
- if (target.length - targetStart < end - start) {
8524
- end = target.length - targetStart + start;
8525
- }
8526
-
8527
- var len = end - start;
8528
-
8529
- if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
8530
- // Use built-in when available, missing from IE11
8531
- this.copyWithin(targetStart, start, end);
8532
- } else {
8533
- Uint8Array.prototype.set.call(
8534
- target,
8535
- this.subarray(start, end),
8536
- targetStart
8537
- );
8538
- }
8539
-
8540
- return len
8541
- };
8542
-
8543
- // Usage:
8544
- // buffer.fill(number[, offset[, end]])
8545
- // buffer.fill(buffer[, offset[, end]])
8546
- // buffer.fill(string[, offset[, end]][, encoding])
8547
- Buffer.prototype.fill = function fill (val, start, end, encoding) {
8548
- // Handle string cases:
8549
- if (typeof val === 'string') {
8550
- if (typeof start === 'string') {
8551
- encoding = start;
8552
- start = 0;
8553
- end = this.length;
8554
- } else if (typeof end === 'string') {
8555
- encoding = end;
8556
- end = this.length;
8557
- }
8558
- if (encoding !== undefined && typeof encoding !== 'string') {
8559
- throw new TypeError('encoding must be a string')
8560
- }
8561
- if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
8562
- throw new TypeError('Unknown encoding: ' + encoding)
8563
- }
8564
- if (val.length === 1) {
8565
- var code = val.charCodeAt(0);
8566
- if ((encoding === 'utf8' && code < 128) ||
8567
- encoding === 'latin1') {
8568
- // Fast path: If `val` fits into a single byte, use that numeric value.
8569
- val = code;
8570
- }
8571
- }
8572
- } else if (typeof val === 'number') {
8573
- val = val & 255;
8574
- } else if (typeof val === 'boolean') {
8575
- val = Number(val);
8576
- }
8577
-
8578
- // Invalid ranges are not set to a default, so can range check early.
8579
- if (start < 0 || this.length < start || this.length < end) {
8580
- throw new RangeError('Out of range index')
8581
- }
8582
-
8583
- if (end <= start) {
8584
- return this
8585
- }
8586
-
8587
- start = start >>> 0;
8588
- end = end === undefined ? this.length : end >>> 0;
8589
-
8590
- if (!val) val = 0;
8591
-
8592
- var i;
8593
- if (typeof val === 'number') {
8594
- for (i = start; i < end; ++i) {
8595
- this[i] = val;
8596
- }
8597
- } else {
8598
- var bytes = Buffer.isBuffer(val)
8599
- ? val
8600
- : Buffer.from(val, encoding);
8601
- var len = bytes.length;
8602
- if (len === 0) {
8603
- throw new TypeError('The value "' + val +
8604
- '" is invalid for argument "value"')
8605
- }
8606
- for (i = 0; i < end - start; ++i) {
8607
- this[i + start] = bytes[i % len];
8608
- }
8609
- }
8610
-
8611
- return this
8612
- };
8613
-
8614
- // HELPER FUNCTIONS
8615
- // ================
8616
-
8617
- var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
8618
-
8619
- function base64clean (str) {
8620
- // Node takes equal signs as end of the Base64 encoding
8621
- str = str.split('=')[0];
8622
- // Node strips out invalid characters like \n and \t from the string, base64-js does not
8623
- str = str.trim().replace(INVALID_BASE64_RE, '');
8624
- // Node converts strings with length < 2 to ''
8625
- if (str.length < 2) return ''
8626
- // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
8627
- while (str.length % 4 !== 0) {
8628
- str = str + '=';
8629
- }
8630
- return str
8631
- }
8632
-
8633
- function utf8ToBytes (string, units) {
8634
- units = units || Infinity;
8635
- var codePoint;
8636
- var length = string.length;
8637
- var leadSurrogate = null;
8638
- var bytes = [];
8639
-
8640
- for (var i = 0; i < length; ++i) {
8641
- codePoint = string.charCodeAt(i);
8642
-
8643
- // is surrogate component
8644
- if (codePoint > 0xD7FF && codePoint < 0xE000) {
8645
- // last char was a lead
8646
- if (!leadSurrogate) {
8647
- // no lead yet
8648
- if (codePoint > 0xDBFF) {
8649
- // unexpected trail
8650
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8651
- continue
8652
- } else if (i + 1 === length) {
8653
- // unpaired lead
8654
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8655
- continue
8656
- }
8657
-
8658
- // valid lead
8659
- leadSurrogate = codePoint;
8660
-
8661
- continue
8662
- }
8663
-
8664
- // 2 leads in a row
8665
- if (codePoint < 0xDC00) {
8666
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8667
- leadSurrogate = codePoint;
8668
- continue
8669
- }
8670
-
8671
- // valid surrogate pair
8672
- codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
8673
- } else if (leadSurrogate) {
8674
- // valid bmp char, but last char was a lead
8675
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8676
- }
8677
-
8678
- leadSurrogate = null;
8679
-
8680
- // encode utf8
8681
- if (codePoint < 0x80) {
8682
- if ((units -= 1) < 0) break
8683
- bytes.push(codePoint);
8684
- } else if (codePoint < 0x800) {
8685
- if ((units -= 2) < 0) break
8686
- bytes.push(
8687
- codePoint >> 0x6 | 0xC0,
8688
- codePoint & 0x3F | 0x80
8689
- );
8690
- } else if (codePoint < 0x10000) {
8691
- if ((units -= 3) < 0) break
8692
- bytes.push(
8693
- codePoint >> 0xC | 0xE0,
8694
- codePoint >> 0x6 & 0x3F | 0x80,
8695
- codePoint & 0x3F | 0x80
8696
- );
8697
- } else if (codePoint < 0x110000) {
8698
- if ((units -= 4) < 0) break
8699
- bytes.push(
8700
- codePoint >> 0x12 | 0xF0,
8701
- codePoint >> 0xC & 0x3F | 0x80,
8702
- codePoint >> 0x6 & 0x3F | 0x80,
8703
- codePoint & 0x3F | 0x80
8704
- );
8705
- } else {
8706
- throw new Error('Invalid code point')
8707
- }
8708
- }
8709
-
8710
- return bytes
8711
- }
8712
-
8713
- function asciiToBytes (str) {
8714
- var byteArray = [];
8715
- for (var i = 0; i < str.length; ++i) {
8716
- // Node's code seems to be doing this and not & 0x7F..
8717
- byteArray.push(str.charCodeAt(i) & 0xFF);
8718
- }
8719
- return byteArray
8720
- }
8721
-
8722
- function utf16leToBytes (str, units) {
8723
- var c, hi, lo;
8724
- var byteArray = [];
8725
- for (var i = 0; i < str.length; ++i) {
8726
- if ((units -= 2) < 0) break
8727
-
8728
- c = str.charCodeAt(i);
8729
- hi = c >> 8;
8730
- lo = c % 256;
8731
- byteArray.push(lo);
8732
- byteArray.push(hi);
8733
- }
8734
-
8735
- return byteArray
8736
- }
8737
-
8738
- function base64ToBytes (str) {
8739
- return base64.toByteArray(base64clean(str))
8740
- }
8741
-
8742
- function blitBuffer (src, dst, offset, length) {
8743
- for (var i = 0; i < length; ++i) {
8744
- if ((i + offset >= dst.length) || (i >= src.length)) break
8745
- dst[i + offset] = src[i];
8746
- }
8747
- return i
8748
- }
8749
-
8750
- // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
8751
- // the `instanceof` check but they should be treated as of that type.
8752
- // See: https://github.com/feross/buffer/issues/166
8753
- function isInstance (obj, type) {
8754
- return obj instanceof type ||
8755
- (obj != null && obj.constructor != null && obj.constructor.name != null &&
8756
- obj.constructor.name === type.name)
8757
- }
8758
- function numberIsNaN (obj) {
8759
- // For IE11 support
8760
- return obj !== obj // eslint-disable-line no-self-compare
8761
- }
8762
-
8763
- // Create lookup table for `toString('hex')`
8764
- // See: https://github.com/feross/buffer/issues/219
8765
- var hexSliceLookupTable = (function () {
8766
- var alphabet = '0123456789abcdef';
8767
- var table = new Array(256);
8768
- for (var i = 0; i < 16; ++i) {
8769
- var i16 = i * 16;
8770
- for (var j = 0; j < 16; ++j) {
8771
- table[i16 + j] = alphabet[i] + alphabet[j];
8772
- }
8773
- }
8774
- return table
8775
- })();
6968
+ throw new Error('BigInt not supported')
6969
+ }
8776
6970
  } (buffer));
8777
6971
  return buffer;
8778
6972
  }
8779
6973
 
8780
6974
  var bufferExports = requireBuffer();
8781
6975
 
6976
+ var dist = {};
6977
+
8782
6978
  var Codecs = {};
8783
6979
 
8784
6980
  var Frames = {};
@@ -8788,7 +6984,7 @@ var hasRequiredFrames;
8788
6984
  function requireFrames () {
8789
6985
  if (hasRequiredFrames) return Frames;
8790
6986
  hasRequiredFrames = 1;
8791
- (function (exports) {
6987
+ (function (exports$1) {
8792
6988
  /*
8793
6989
  * Copyright 2021-2022 the original author or authors.
8794
6990
  *
@@ -8804,8 +7000,8 @@ function requireFrames () {
8804
7000
  * See the License for the specific language governing permissions and
8805
7001
  * limitations under the License.
8806
7002
  */
8807
- Object.defineProperty(exports, "__esModule", { value: true });
8808
- exports.Frame = exports.Lengths = exports.Flags = exports.FrameTypes = void 0;
7003
+ Object.defineProperty(exports$1, "__esModule", { value: true });
7004
+ exports$1.Frame = exports$1.Lengths = exports$1.Flags = exports$1.FrameTypes = void 0;
8809
7005
  var FrameTypes;
8810
7006
  (function (FrameTypes) {
8811
7007
  FrameTypes[FrameTypes["RESERVED"] = 0] = "RESERVED";
@@ -8824,7 +7020,7 @@ function requireFrames () {
8824
7020
  FrameTypes[FrameTypes["RESUME"] = 13] = "RESUME";
8825
7021
  FrameTypes[FrameTypes["RESUME_OK"] = 14] = "RESUME_OK";
8826
7022
  FrameTypes[FrameTypes["EXT"] = 63] = "EXT";
8827
- })(FrameTypes = exports.FrameTypes || (exports.FrameTypes = {}));
7023
+ })(FrameTypes = exports$1.FrameTypes || (exports$1.FrameTypes = {}));
8828
7024
  (function (Flags) {
8829
7025
  Flags[Flags["NONE"] = 0] = "NONE";
8830
7026
  Flags[Flags["COMPLETE"] = 64] = "COMPLETE";
@@ -8835,7 +7031,7 @@ function requireFrames () {
8835
7031
  Flags[Flags["NEXT"] = 32] = "NEXT";
8836
7032
  Flags[Flags["RESPOND"] = 128] = "RESPOND";
8837
7033
  Flags[Flags["RESUME_ENABLE"] = 128] = "RESUME_ENABLE";
8838
- })(exports.Flags || (exports.Flags = {}));
7034
+ })(exports$1.Flags || (exports$1.Flags = {}));
8839
7035
  (function (Flags) {
8840
7036
  function hasMetadata(flags) {
8841
7037
  return (flags & Flags.METADATA) === Flags.METADATA;
@@ -8869,13 +7065,13 @@ function requireFrames () {
8869
7065
  return (flags & Flags.RESUME_ENABLE) === Flags.RESUME_ENABLE;
8870
7066
  }
8871
7067
  Flags.hasResume = hasResume;
8872
- })(exports.Flags || (exports.Flags = {}));
7068
+ })(exports$1.Flags || (exports$1.Flags = {}));
8873
7069
  (function (Lengths) {
8874
7070
  Lengths[Lengths["FRAME"] = 3] = "FRAME";
8875
7071
  Lengths[Lengths["HEADER"] = 6] = "HEADER";
8876
7072
  Lengths[Lengths["METADATA"] = 3] = "METADATA";
8877
7073
  Lengths[Lengths["REQUEST"] = 3] = "REQUEST";
8878
- })(exports.Lengths || (exports.Lengths = {}));
7074
+ })(exports$1.Lengths || (exports$1.Lengths = {}));
8879
7075
  (function (Frame) {
8880
7076
  function isConnection(frame) {
8881
7077
  return frame.streamId === 0;
@@ -8886,7 +7082,7 @@ function requireFrames () {
8886
7082
  frame.type <= FrameTypes.REQUEST_CHANNEL);
8887
7083
  }
8888
7084
  Frame.isRequest = isRequest;
8889
- })(exports.Frame || (exports.Frame = {}));
7085
+ })(exports$1.Frame || (exports$1.Frame = {}));
8890
7086
 
8891
7087
  } (Frames));
8892
7088
  return Frames;
@@ -8897,7 +7093,7 @@ var hasRequiredCodecs;
8897
7093
  function requireCodecs () {
8898
7094
  if (hasRequiredCodecs) return Codecs;
8899
7095
  hasRequiredCodecs = 1;
8900
- (function (exports) {
7096
+ (function (exports$1) {
8901
7097
  var __generator = (Codecs && Codecs.__generator) || function (thisArg, body) {
8902
7098
  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
8903
7099
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
@@ -8925,22 +7121,22 @@ function requireCodecs () {
8925
7121
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
8926
7122
  }
8927
7123
  };
8928
- Object.defineProperty(exports, "__esModule", { value: true });
8929
- exports.Deserializer = exports.sizeOfFrame = exports.serializeFrame = exports.deserializeFrame = exports.serializeFrameWithLength = exports.deserializeFrames = exports.deserializeFrameWithLength = exports.writeUInt64BE = exports.readUInt64BE = exports.writeUInt24BE = exports.readUInt24BE = exports.MAX_VERSION = exports.MAX_TTL = exports.MAX_STREAM_ID = exports.MAX_RESUME_LENGTH = exports.MAX_REQUEST_N = exports.MAX_REQUEST_COUNT = exports.MAX_MIME_LENGTH = exports.MAX_METADATA_LENGTH = exports.MAX_LIFETIME = exports.MAX_KEEPALIVE = exports.MAX_CODE = exports.FRAME_TYPE_OFFFSET = exports.FLAGS_MASK = void 0;
7124
+ Object.defineProperty(exports$1, "__esModule", { value: true });
7125
+ exports$1.Deserializer = exports$1.sizeOfFrame = exports$1.serializeFrame = exports$1.deserializeFrame = exports$1.serializeFrameWithLength = exports$1.deserializeFrames = exports$1.deserializeFrameWithLength = exports$1.writeUInt64BE = exports$1.readUInt64BE = exports$1.writeUInt24BE = exports$1.readUInt24BE = exports$1.MAX_VERSION = exports$1.MAX_TTL = exports$1.MAX_STREAM_ID = exports$1.MAX_RESUME_LENGTH = exports$1.MAX_REQUEST_N = exports$1.MAX_REQUEST_COUNT = exports$1.MAX_MIME_LENGTH = exports$1.MAX_METADATA_LENGTH = exports$1.MAX_LIFETIME = exports$1.MAX_KEEPALIVE = exports$1.MAX_CODE = exports$1.FRAME_TYPE_OFFFSET = exports$1.FLAGS_MASK = void 0;
8930
7126
  var Frames_1 = requireFrames();
8931
- exports.FLAGS_MASK = 0x3ff; // low 10 bits
8932
- exports.FRAME_TYPE_OFFFSET = 10; // frame type is offset 10 bytes within the uint16 containing type + flags
8933
- exports.MAX_CODE = 0x7fffffff; // uint31
8934
- exports.MAX_KEEPALIVE = 0x7fffffff; // uint31
8935
- exports.MAX_LIFETIME = 0x7fffffff; // uint31
8936
- exports.MAX_METADATA_LENGTH = 0xffffff; // uint24
8937
- exports.MAX_MIME_LENGTH = 0xff; // int8
8938
- exports.MAX_REQUEST_COUNT = 0x7fffffff; // uint31
8939
- exports.MAX_REQUEST_N = 0x7fffffff; // uint31
8940
- exports.MAX_RESUME_LENGTH = 0xffff; // uint16
8941
- exports.MAX_STREAM_ID = 0x7fffffff; // uint31
8942
- exports.MAX_TTL = 0x7fffffff; // uint31
8943
- exports.MAX_VERSION = 0xffff; // uint16
7127
+ exports$1.FLAGS_MASK = 0x3ff; // low 10 bits
7128
+ exports$1.FRAME_TYPE_OFFFSET = 10; // frame type is offset 10 bytes within the uint16 containing type + flags
7129
+ exports$1.MAX_CODE = 0x7fffffff; // uint31
7130
+ exports$1.MAX_KEEPALIVE = 0x7fffffff; // uint31
7131
+ exports$1.MAX_LIFETIME = 0x7fffffff; // uint31
7132
+ exports$1.MAX_METADATA_LENGTH = 0xffffff; // uint24
7133
+ exports$1.MAX_MIME_LENGTH = 0xff; // int8
7134
+ exports$1.MAX_REQUEST_COUNT = 0x7fffffff; // uint31
7135
+ exports$1.MAX_REQUEST_N = 0x7fffffff; // uint31
7136
+ exports$1.MAX_RESUME_LENGTH = 0xffff; // uint16
7137
+ exports$1.MAX_STREAM_ID = 0x7fffffff; // uint31
7138
+ exports$1.MAX_TTL = 0x7fffffff; // uint31
7139
+ exports$1.MAX_VERSION = 0xffff; // uint16
8944
7140
  /**
8945
7141
  * Mimimum value that would overflow bitwise operators (2^32).
8946
7142
  */
@@ -8954,7 +7150,7 @@ function requireCodecs () {
8954
7150
  var val3 = buffer.readUInt8(offset + 2);
8955
7151
  return val1 | val2 | val3;
8956
7152
  }
8957
- exports.readUInt24BE = readUInt24BE;
7153
+ exports$1.readUInt24BE = readUInt24BE;
8958
7154
  /**
8959
7155
  * Writes a uint24 to a buffer starting at the given offset, returning the
8960
7156
  * offset of the next byte.
@@ -8964,7 +7160,7 @@ function requireCodecs () {
8964
7160
  offset = buffer.writeUInt8((value >>> 8) & 0xff, offset); // 2nd byte
8965
7161
  return buffer.writeUInt8(value & 0xff, offset); // 1st byte
8966
7162
  }
8967
- exports.writeUInt24BE = writeUInt24BE;
7163
+ exports$1.writeUInt24BE = writeUInt24BE;
8968
7164
  /**
8969
7165
  * Read a uint64 (technically supports up to 53 bits per JS number
8970
7166
  * representation).
@@ -8974,7 +7170,7 @@ function requireCodecs () {
8974
7170
  var low = buffer.readUInt32BE(offset + 4);
8975
7171
  return high * BITWISE_OVERFLOW + low;
8976
7172
  }
8977
- exports.readUInt64BE = readUInt64BE;
7173
+ exports$1.readUInt64BE = readUInt64BE;
8978
7174
  /**
8979
7175
  * Write a uint64 (technically supports up to 53 bits per JS number
8980
7176
  * representation).
@@ -8985,7 +7181,7 @@ function requireCodecs () {
8985
7181
  offset = buffer.writeUInt32BE(high, offset); // first half of uint64
8986
7182
  return buffer.writeUInt32BE(low, offset); // second half of uint64
8987
7183
  }
8988
- exports.writeUInt64BE = writeUInt64BE;
7184
+ exports$1.writeUInt64BE = writeUInt64BE;
8989
7185
  /**
8990
7186
  * Frame header is:
8991
7187
  * - stream id (uint32 = 4)
@@ -9003,7 +7199,7 @@ function requireCodecs () {
9003
7199
  var frameLength = readUInt24BE(buffer, 0);
9004
7200
  return deserializeFrame(buffer.slice(UINT24_SIZE, UINT24_SIZE + frameLength));
9005
7201
  }
9006
- exports.deserializeFrameWithLength = deserializeFrameWithLength;
7202
+ exports$1.deserializeFrameWithLength = deserializeFrameWithLength;
9007
7203
  /**
9008
7204
  * Given a buffer that may contain zero or more length-prefixed frames followed
9009
7205
  * by zero or more bytes of a (partial) subsequent frame, returns an array of
@@ -9036,7 +7232,7 @@ function requireCodecs () {
9036
7232
  }
9037
7233
  });
9038
7234
  }
9039
- exports.deserializeFrames = deserializeFrames;
7235
+ exports$1.deserializeFrames = deserializeFrames;
9040
7236
  /**
9041
7237
  * Writes a frame to a buffer with a length prefix.
9042
7238
  */
@@ -9047,7 +7243,7 @@ function requireCodecs () {
9047
7243
  buffer.copy(lengthPrefixed, UINT24_SIZE);
9048
7244
  return lengthPrefixed;
9049
7245
  }
9050
- exports.serializeFrameWithLength = serializeFrameWithLength;
7246
+ exports$1.serializeFrameWithLength = serializeFrameWithLength;
9051
7247
  /**
9052
7248
  * Read a frame from the buffer.
9053
7249
  */
@@ -9062,8 +7258,8 @@ function requireCodecs () {
9062
7258
  // );
9063
7259
  var typeAndFlags = buffer.readUInt16BE(offset);
9064
7260
  offset += 2;
9065
- var type = typeAndFlags >>> exports.FRAME_TYPE_OFFFSET; // keep highest 6 bits
9066
- var flags = typeAndFlags & exports.FLAGS_MASK; // keep lowest 10 bits
7261
+ var type = typeAndFlags >>> exports$1.FRAME_TYPE_OFFFSET; // keep highest 6 bits
7262
+ var flags = typeAndFlags & exports$1.FLAGS_MASK; // keep lowest 10 bits
9067
7263
  switch (type) {
9068
7264
  case Frames_1.FrameTypes.SETUP:
9069
7265
  return deserializeSetupFrame(buffer, streamId, flags);
@@ -9100,7 +7296,7 @@ function requireCodecs () {
9100
7296
  // );
9101
7297
  }
9102
7298
  }
9103
- exports.deserializeFrame = deserializeFrame;
7299
+ exports$1.deserializeFrame = deserializeFrame;
9104
7300
  /**
9105
7301
  * Convert the frame to a (binary) buffer.
9106
7302
  */
@@ -9139,7 +7335,7 @@ function requireCodecs () {
9139
7335
  // );
9140
7336
  }
9141
7337
  }
9142
- exports.serializeFrame = serializeFrame;
7338
+ exports$1.serializeFrame = serializeFrame;
9143
7339
  /**
9144
7340
  * Byte size of frame without size prefix
9145
7341
  */
@@ -9178,7 +7374,7 @@ function requireCodecs () {
9178
7374
  // );
9179
7375
  }
9180
7376
  }
9181
- exports.sizeOfFrame = sizeOfFrame;
7377
+ exports$1.sizeOfFrame = sizeOfFrame;
9182
7378
  /**
9183
7379
  * Writes a SETUP frame into a new buffer and returns it.
9184
7380
  *
@@ -9813,7 +8009,7 @@ function requireCodecs () {
9813
8009
  function writeHeader(frame, buffer) {
9814
8010
  var offset = buffer.writeInt32BE(frame.streamId, 0);
9815
8011
  // shift frame to high 6 bits, extract lowest 10 bits from flags
9816
- return buffer.writeUInt16BE((frame.type << exports.FRAME_TYPE_OFFFSET) | (frame.flags & exports.FLAGS_MASK), offset);
8012
+ return buffer.writeUInt16BE((frame.type << exports$1.FRAME_TYPE_OFFFSET) | (frame.flags & exports$1.FLAGS_MASK), offset);
9817
8013
  }
9818
8014
  /**
9819
8015
  * Determine the length of the payload section of a frame. Only applies to
@@ -9894,7 +8090,7 @@ function requireCodecs () {
9894
8090
  };
9895
8091
  return Deserializer;
9896
8092
  }());
9897
- exports.Deserializer = Deserializer;
8093
+ exports$1.Deserializer = Deserializer;
9898
8094
 
9899
8095
  } (Codecs));
9900
8096
  return Codecs;
@@ -10040,7 +8236,7 @@ var hasRequiredErrors;
10040
8236
  function requireErrors () {
10041
8237
  if (hasRequiredErrors) return Errors;
10042
8238
  hasRequiredErrors = 1;
10043
- (function (exports) {
8239
+ (function (exports$1) {
10044
8240
  /*
10045
8241
  * Copyright 2021-2022 the original author or authors.
10046
8242
  *
@@ -10071,8 +8267,8 @@ function requireErrors () {
10071
8267
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10072
8268
  };
10073
8269
  })();
10074
- Object.defineProperty(exports, "__esModule", { value: true });
10075
- exports.ErrorCodes = exports.RSocketError = void 0;
8270
+ Object.defineProperty(exports$1, "__esModule", { value: true });
8271
+ exports$1.ErrorCodes = exports$1.RSocketError = void 0;
10076
8272
  var RSocketError = /** @class */ (function (_super) {
10077
8273
  __extends(RSocketError, _super);
10078
8274
  function RSocketError(code, message) {
@@ -10082,7 +8278,7 @@ function requireErrors () {
10082
8278
  }
10083
8279
  return RSocketError;
10084
8280
  }(Error));
10085
- exports.RSocketError = RSocketError;
8281
+ exports$1.RSocketError = RSocketError;
10086
8282
  (function (ErrorCodes) {
10087
8283
  ErrorCodes[ErrorCodes["RESERVED"] = 0] = "RESERVED";
10088
8284
  ErrorCodes[ErrorCodes["INVALID_SETUP"] = 1] = "INVALID_SETUP";
@@ -10096,7 +8292,7 @@ function requireErrors () {
10096
8292
  ErrorCodes[ErrorCodes["CANCELED"] = 515] = "CANCELED";
10097
8293
  ErrorCodes[ErrorCodes["INVALID"] = 516] = "INVALID";
10098
8294
  ErrorCodes[ErrorCodes["RESERVED_EXTENSION"] = 4294967295] = "RESERVED_EXTENSION";
10099
- })(exports.ErrorCodes || (exports.ErrorCodes = {}));
8295
+ })(exports$1.ErrorCodes || (exports$1.ErrorCodes = {}));
10100
8296
 
10101
8297
  } (Errors));
10102
8298
  return Errors;
@@ -10138,7 +8334,7 @@ var hasRequiredClientServerMultiplexerDemultiplexer;
10138
8334
  function requireClientServerMultiplexerDemultiplexer () {
10139
8335
  if (hasRequiredClientServerMultiplexerDemultiplexer) return ClientServerMultiplexerDemultiplexer;
10140
8336
  hasRequiredClientServerMultiplexerDemultiplexer = 1;
10141
- (function (exports) {
8337
+ (function (exports$1) {
10142
8338
  /*
10143
8339
  * Copyright 2021-2022 the original author or authors.
10144
8340
  *
@@ -10205,8 +8401,8 @@ function requireClientServerMultiplexerDemultiplexer () {
10205
8401
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
10206
8402
  }
10207
8403
  };
10208
- Object.defineProperty(exports, "__esModule", { value: true });
10209
- exports.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = exports.ResumableClientServerInputMultiplexerDemultiplexer = exports.ClientServerInputMultiplexerDemultiplexer = exports.StreamIdGenerator = void 0;
8404
+ Object.defineProperty(exports$1, "__esModule", { value: true });
8405
+ exports$1.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = exports$1.ResumableClientServerInputMultiplexerDemultiplexer = exports$1.ClientServerInputMultiplexerDemultiplexer = exports$1.StreamIdGenerator = void 0;
10210
8406
  var _1 = requireDist();
10211
8407
  var Deferred_1 = requireDeferred();
10212
8408
  var Errors_1 = requireErrors();
@@ -10229,7 +8425,7 @@ function requireClientServerMultiplexerDemultiplexer () {
10229
8425
  };
10230
8426
  return StreamIdGeneratorImpl;
10231
8427
  }());
10232
- })(exports.StreamIdGenerator || (exports.StreamIdGenerator = {}));
8428
+ })(exports$1.StreamIdGenerator || (exports$1.StreamIdGenerator = {}));
10233
8429
  var ClientServerInputMultiplexerDemultiplexer = /** @class */ (function (_super) {
10234
8430
  __extends(ClientServerInputMultiplexerDemultiplexer, _super);
10235
8431
  function ClientServerInputMultiplexerDemultiplexer(streamIdSupplier, outbound, closeable) {
@@ -10318,7 +8514,7 @@ function requireClientServerMultiplexerDemultiplexer () {
10318
8514
  };
10319
8515
  return ClientServerInputMultiplexerDemultiplexer;
10320
8516
  }(Deferred_1.Deferred));
10321
- exports.ClientServerInputMultiplexerDemultiplexer = ClientServerInputMultiplexerDemultiplexer;
8517
+ exports$1.ClientServerInputMultiplexerDemultiplexer = ClientServerInputMultiplexerDemultiplexer;
10322
8518
  var ResumableClientServerInputMultiplexerDemultiplexer = /** @class */ (function (_super) {
10323
8519
  __extends(ResumableClientServerInputMultiplexerDemultiplexer, _super);
10324
8520
  function ResumableClientServerInputMultiplexerDemultiplexer(streamIdSupplier, outbound, closeable, frameStore, token, sessionStoreOrReconnector, sessionTimeout) {
@@ -10475,7 +8671,7 @@ function requireClientServerMultiplexerDemultiplexer () {
10475
8671
  };
10476
8672
  return ResumableClientServerInputMultiplexerDemultiplexer;
10477
8673
  }(ClientServerInputMultiplexerDemultiplexer));
10478
- exports.ResumableClientServerInputMultiplexerDemultiplexer = ResumableClientServerInputMultiplexerDemultiplexer;
8674
+ exports$1.ResumableClientServerInputMultiplexerDemultiplexer = ResumableClientServerInputMultiplexerDemultiplexer;
10479
8675
  var ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = /** @class */ (function () {
10480
8676
  function ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer(outbound, closeable, delegate) {
10481
8677
  this.outbound = outbound;
@@ -10532,7 +8728,7 @@ function requireClientServerMultiplexerDemultiplexer () {
10532
8728
  };
10533
8729
  return ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer;
10534
8730
  }());
10535
- exports.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer;
8731
+ exports$1.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer;
10536
8732
 
10537
8733
  } (ClientServerMultiplexerDemultiplexer));
10538
8734
  return ClientServerMultiplexerDemultiplexer;
@@ -13518,7 +11714,7 @@ var hasRequiredDist;
13518
11714
  function requireDist () {
13519
11715
  if (hasRequiredDist) return dist;
13520
11716
  hasRequiredDist = 1;
13521
- (function (exports) {
11717
+ (function (exports$1) {
13522
11718
  /*
13523
11719
  * Copyright 2021-2022 the original author or authors.
13524
11720
  *
@@ -13541,19 +11737,19 @@ function requireDist () {
13541
11737
  if (k2 === undefined) k2 = k;
13542
11738
  o[k2] = m[k];
13543
11739
  }));
13544
- var __exportStar = (dist && dist.__exportStar) || function(m, exports) {
13545
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11740
+ var __exportStar = (dist && dist.__exportStar) || function(m, exports$1) {
11741
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);
13546
11742
  };
13547
- Object.defineProperty(exports, "__esModule", { value: true });
13548
- __exportStar(requireCodecs(), exports);
13549
- __exportStar(requireCommon(), exports);
13550
- __exportStar(requireDeferred(), exports);
13551
- __exportStar(requireErrors(), exports);
13552
- __exportStar(requireFrames(), exports);
13553
- __exportStar(requireRSocket(), exports);
13554
- __exportStar(requireRSocketConnector(), exports);
13555
- __exportStar(requireRSocketServer(), exports);
13556
- __exportStar(requireTransport(), exports);
11743
+ Object.defineProperty(exports$1, "__esModule", { value: true });
11744
+ __exportStar(requireCodecs(), exports$1);
11745
+ __exportStar(requireCommon(), exports$1);
11746
+ __exportStar(requireDeferred(), exports$1);
11747
+ __exportStar(requireErrors(), exports$1);
11748
+ __exportStar(requireFrames(), exports$1);
11749
+ __exportStar(requireRSocket(), exports$1);
11750
+ __exportStar(requireRSocketConnector(), exports$1);
11751
+ __exportStar(requireRSocketServer(), exports$1);
11752
+ __exportStar(requireTransport(), exports$1);
13557
11753
 
13558
11754
  } (dist));
13559
11755
  return dist;
@@ -13561,7 +11757,7 @@ function requireDist () {
13561
11757
 
13562
11758
  var distExports = requireDist();
13563
11759
 
13564
- var version = "1.44.0";
11760
+ var version = "1.46.0";
13565
11761
  var PACKAGE = {
13566
11762
  version: version};
13567
11763
 
@@ -13632,6 +11828,16 @@ class DataStream extends BaseObserver {
13632
11828
  * @returns a Data payload or Null if the stream closed.
13633
11829
  */
13634
11830
  async read() {
11831
+ if (this.closed) {
11832
+ return null;
11833
+ }
11834
+ // Wait for any pending processing to complete first.
11835
+ // This ensures we register our listener before calling processQueue(),
11836
+ // avoiding a race where processQueue() sees no reader and returns early.
11837
+ if (this.processingPromise) {
11838
+ await this.processingPromise;
11839
+ }
11840
+ // Re-check after await - stream may have closed while we were waiting
13635
11841
  if (this.closed) {
13636
11842
  return null;
13637
11843
  }
@@ -13671,7 +11877,7 @@ class DataStream extends BaseObserver {
13671
11877
  }
13672
11878
  const promise = (this.processingPromise = this._processQueue());
13673
11879
  promise.finally(() => {
13674
- return (this.processingPromise = null);
11880
+ this.processingPromise = null;
13675
11881
  });
13676
11882
  return promise;
13677
11883
  }
@@ -13703,7 +11909,6 @@ class DataStream extends BaseObserver {
13703
11909
  this.notifyDataAdded = null;
13704
11910
  }
13705
11911
  if (this.dataQueue.length > 0) {
13706
- // Next tick
13707
11912
  setTimeout(() => this.processQueue());
13708
11913
  }
13709
11914
  }
@@ -14083,7 +12288,7 @@ class AbstractRemote {
14083
12288
  else {
14084
12289
  contents = JSON.stringify(js);
14085
12290
  }
14086
- return bufferExports$1.Buffer.from(contents);
12291
+ return bufferExports.Buffer.from(contents);
14087
12292
  }
14088
12293
  const syncQueueRequestSize = fetchStrategy == FetchStrategy.Buffered ? 10 : 1;
14089
12294
  const request = await this.buildRequest(path);
@@ -14323,7 +12528,11 @@ class AbstractRemote {
14323
12528
  };
14324
12529
  const stream = new DataStream({
14325
12530
  logger: this.logger,
14326
- mapLine: mapLine
12531
+ mapLine: mapLine,
12532
+ pressure: {
12533
+ highWaterMark: 20,
12534
+ lowWaterMark: 10
12535
+ }
14327
12536
  });
14328
12537
  abortSignal?.addEventListener('abort', () => {
14329
12538
  closeReader();
@@ -14331,42 +12540,47 @@ class AbstractRemote {
14331
12540
  });
14332
12541
  const decoder = this.createTextDecoder();
14333
12542
  let buffer = '';
14334
- const l = stream.registerListener({
14335
- lowWater: async () => {
14336
- if (stream.closed || abortSignal?.aborted || readerReleased) {
12543
+ const consumeStream = async () => {
12544
+ while (!stream.closed && !abortSignal?.aborted && !readerReleased) {
12545
+ const { done, value } = await reader.read();
12546
+ if (done) {
12547
+ const remaining = buffer.trim();
12548
+ if (remaining.length != 0) {
12549
+ stream.enqueueData(remaining);
12550
+ }
12551
+ stream.close();
12552
+ await closeReader();
14337
12553
  return;
14338
12554
  }
14339
- try {
14340
- let didCompleteLine = false;
14341
- while (!didCompleteLine) {
14342
- const { done, value } = await reader.read();
14343
- if (done) {
14344
- const remaining = buffer.trim();
14345
- if (remaining.length != 0) {
14346
- stream.enqueueData(remaining);
14347
- }
14348
- stream.close();
14349
- await closeReader();
14350
- return;
14351
- }
14352
- const data = decoder.decode(value, { stream: true });
14353
- buffer += data;
14354
- const lines = buffer.split('\n');
14355
- for (var i = 0; i < lines.length - 1; i++) {
14356
- var l = lines[i].trim();
14357
- if (l.length > 0) {
14358
- stream.enqueueData(l);
14359
- didCompleteLine = true;
14360
- }
14361
- }
14362
- buffer = lines[lines.length - 1];
12555
+ const data = decoder.decode(value, { stream: true });
12556
+ buffer += data;
12557
+ const lines = buffer.split('\n');
12558
+ for (var i = 0; i < lines.length - 1; i++) {
12559
+ var l = lines[i].trim();
12560
+ if (l.length > 0) {
12561
+ stream.enqueueData(l);
14363
12562
  }
14364
12563
  }
14365
- catch (ex) {
14366
- stream.close();
14367
- throw ex;
12564
+ buffer = lines[lines.length - 1];
12565
+ // Implement backpressure by waiting for the low water mark to be reached
12566
+ if (stream.dataQueue.length > stream.highWatermark) {
12567
+ await new Promise((resolve) => {
12568
+ const dispose = stream.registerListener({
12569
+ lowWater: async () => {
12570
+ resolve();
12571
+ dispose();
12572
+ },
12573
+ closed: () => {
12574
+ resolve();
12575
+ dispose();
12576
+ }
12577
+ });
12578
+ });
14368
12579
  }
14369
- },
12580
+ }
12581
+ };
12582
+ consumeStream().catch(ex => this.logger.error('Error consuming stream', ex));
12583
+ const l = stream.registerListener({
14370
12584
  closed: () => {
14371
12585
  closeReader();
14372
12586
  l?.();
@@ -14445,18 +12659,17 @@ var SyncClientImplementation;
14445
12659
  *
14446
12660
  * This is the default option.
14447
12661
  *
14448
- * @deprecated Don't use {@link SyncClientImplementation.JAVASCRIPT} directly. Instead, use
14449
- * {@link DEFAULT_SYNC_CLIENT_IMPLEMENTATION} or omit the option. The explicit choice to use
14450
- * the JavaScript-based sync implementation will be removed from a future version of the SDK.
12662
+ * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with
12663
+ * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future
12664
+ * version of the PowerSync SDK.
14451
12665
  */
14452
12666
  SyncClientImplementation["JAVASCRIPT"] = "js";
14453
12667
  /**
14454
12668
  * This implementation offloads the sync line decoding and handling into the PowerSync
14455
12669
  * core extension.
14456
12670
  *
14457
- * @experimental
14458
- * While this implementation is more performant than {@link SyncClientImplementation.JAVASCRIPT},
14459
- * it has seen less real-world testing and is marked as __experimental__ at the moment.
12671
+ * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the
12672
+ * recommended client implementation for all apps.
14460
12673
  *
14461
12674
  * ## Compatibility warning
14462
12675
  *
@@ -14474,13 +12687,9 @@ var SyncClientImplementation;
14474
12687
  SyncClientImplementation["RUST"] = "rust";
14475
12688
  })(SyncClientImplementation || (SyncClientImplementation = {}));
14476
12689
  /**
14477
- * The default {@link SyncClientImplementation} to use.
14478
- *
14479
- * Please use this field instead of {@link SyncClientImplementation.JAVASCRIPT} directly. A future version
14480
- * of the PowerSync SDK will enable {@link SyncClientImplementation.RUST} by default and remove the JavaScript
14481
- * option.
12690
+ * The default {@link SyncClientImplementation} to use, {@link SyncClientImplementation.RUST}.
14482
12691
  */
14483
- const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.JAVASCRIPT;
12692
+ const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.RUST;
14484
12693
  const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
14485
12694
  const DEFAULT_RETRY_DELAY_MS = 5000;
14486
12695
  const DEFAULT_STREAMING_SYNC_OPTIONS = {
@@ -14890,6 +13099,9 @@ The next upload iteration will be delayed.`);
14890
13099
  if (rawTables != null && rawTables.length) {
14891
13100
  this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');
14892
13101
  }
13102
+ if (this.activeStreams.length) {
13103
+ this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');
13104
+ }
14893
13105
  this.logger.debug('Streaming sync iteration started');
14894
13106
  this.options.adapter.startSession();
14895
13107
  let [req, bucketMap] = await this.collectLocalBucketState();
@@ -15405,6 +13617,27 @@ The next upload iteration will be delayed.`);
15405
13617
  }
15406
13618
  }
15407
13619
 
13620
+ const CLAIM_STORE = new Map();
13621
+ /**
13622
+ * @internal
13623
+ * @experimental
13624
+ */
13625
+ const MEMORY_TRIGGER_CLAIM_MANAGER = {
13626
+ async obtainClaim(identifier) {
13627
+ if (CLAIM_STORE.has(identifier)) {
13628
+ throw new Error(`A claim is already present for ${identifier}`);
13629
+ }
13630
+ const release = async () => {
13631
+ CLAIM_STORE.delete(identifier);
13632
+ };
13633
+ CLAIM_STORE.set(identifier, release);
13634
+ return release;
13635
+ },
13636
+ async checkClaim(identifier) {
13637
+ return CLAIM_STORE.has(identifier);
13638
+ }
13639
+ };
13640
+
15408
13641
  /**
15409
13642
  * SQLite operations to track changes for with {@link TriggerManager}
15410
13643
  * @experimental
@@ -15416,9 +13649,20 @@ var DiffTriggerOperation;
15416
13649
  DiffTriggerOperation["DELETE"] = "DELETE";
15417
13650
  })(DiffTriggerOperation || (DiffTriggerOperation = {}));
15418
13651
 
13652
+ const DEFAULT_TRIGGER_MANAGER_CONFIGURATION = {
13653
+ useStorageByDefault: false
13654
+ };
13655
+ const TRIGGER_CLEANUP_INTERVAL_MS = 120_000; // 2 minutes
13656
+ /**
13657
+ * @internal
13658
+ * @experimental
13659
+ */
15419
13660
  class TriggerManagerImpl {
15420
13661
  options;
15421
13662
  schema;
13663
+ defaultConfig;
13664
+ cleanupTimeout;
13665
+ isDisposed;
15422
13666
  constructor(options) {
15423
13667
  this.options = options;
15424
13668
  this.schema = options.schema;
@@ -15427,6 +13671,33 @@ class TriggerManagerImpl {
15427
13671
  this.schema = schema;
15428
13672
  }
15429
13673
  });
13674
+ this.isDisposed = false;
13675
+ /**
13676
+ * Configure a cleanup to run on an interval.
13677
+ * The interval is configured using setTimeout to take the async
13678
+ * execution time of the callback into account.
13679
+ */
13680
+ this.defaultConfig = DEFAULT_TRIGGER_MANAGER_CONFIGURATION;
13681
+ const cleanupCallback = async () => {
13682
+ this.cleanupTimeout = null;
13683
+ if (this.isDisposed) {
13684
+ return;
13685
+ }
13686
+ try {
13687
+ await this.cleanupResources();
13688
+ }
13689
+ catch (ex) {
13690
+ this.db.logger.error(`Caught error while attempting to cleanup triggers`, ex);
13691
+ }
13692
+ finally {
13693
+ // if not closed, set another timeout
13694
+ if (this.isDisposed) {
13695
+ return;
13696
+ }
13697
+ this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);
13698
+ }
13699
+ };
13700
+ this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);
15430
13701
  }
15431
13702
  get db() {
15432
13703
  return this.options.db;
@@ -15444,13 +13715,95 @@ class TriggerManagerImpl {
15444
13715
  await tx.execute(/* sql */ `DROP TRIGGER IF EXISTS ${triggerId}; `);
15445
13716
  }
15446
13717
  }
13718
+ dispose() {
13719
+ this.isDisposed = true;
13720
+ if (this.cleanupTimeout) {
13721
+ clearTimeout(this.cleanupTimeout);
13722
+ }
13723
+ }
13724
+ /**
13725
+ * Updates default config settings for platform specific use-cases.
13726
+ */
13727
+ updateDefaults(config) {
13728
+ this.defaultConfig = {
13729
+ ...this.defaultConfig,
13730
+ ...config
13731
+ };
13732
+ }
13733
+ generateTriggerName(operation, destinationTable, triggerId) {
13734
+ return `__ps_temp_trigger_${operation.toLowerCase()}__${destinationTable}__${triggerId}`;
13735
+ }
13736
+ /**
13737
+ * Cleanup any SQLite triggers or tables that are no longer in use.
13738
+ */
13739
+ async cleanupResources() {
13740
+ // we use the database here since cleanupResources is called during the PowerSyncDatabase initialization
13741
+ await this.db.database.writeLock(async (ctx) => {
13742
+ /**
13743
+ * Note: We only cleanup persisted triggers. These are tracked in the sqlite_master table.
13744
+ * temporary triggers will not be affected by this.
13745
+ * Query all triggers that match our naming pattern
13746
+ */
13747
+ const triggers = await ctx.getAll(/* sql */ `
13748
+ SELECT
13749
+ name
13750
+ FROM
13751
+ sqlite_master
13752
+ WHERE
13753
+ type = 'trigger'
13754
+ AND name LIKE '__ps_temp_trigger_%'
13755
+ `);
13756
+ /** Use regex to extract table names and IDs from trigger names
13757
+ * Trigger naming convention: __ps_temp_trigger_<operation>__<destination_table>__<id>
13758
+ */
13759
+ const triggerPattern = /^__ps_temp_trigger_(?:insert|update|delete)__(.+)__([a-f0-9_]{36})$/i;
13760
+ const trackedItems = new Map();
13761
+ for (const trigger of triggers) {
13762
+ const match = trigger.name.match(triggerPattern);
13763
+ if (match) {
13764
+ const [, table, id] = match;
13765
+ // Collect all trigger names for each id combo
13766
+ const existing = trackedItems.get(id);
13767
+ if (existing) {
13768
+ existing.triggerNames.push(trigger.name);
13769
+ }
13770
+ else {
13771
+ trackedItems.set(id, { table, id, triggerNames: [trigger.name] });
13772
+ }
13773
+ }
13774
+ }
13775
+ for (const trackedItem of trackedItems.values()) {
13776
+ // check if there is anything holding on to this item
13777
+ const hasClaim = await this.options.claimManager.checkClaim(trackedItem.id);
13778
+ if (hasClaim) {
13779
+ // This does not require cleanup
13780
+ continue;
13781
+ }
13782
+ this.db.logger.debug(`Clearing resources for trigger ${trackedItem.id} with table ${trackedItem.table}`);
13783
+ // We need to delete the triggers and table
13784
+ for (const triggerName of trackedItem.triggerNames) {
13785
+ await ctx.execute(`DROP TRIGGER IF EXISTS ${triggerName}`);
13786
+ }
13787
+ await ctx.execute(`DROP TABLE IF EXISTS ${trackedItem.table}`);
13788
+ }
13789
+ });
13790
+ }
15447
13791
  async createDiffTrigger(options) {
15448
13792
  await this.db.waitForReady();
15449
- const { source, destination, columns, when, hooks } = options;
13793
+ const { source, destination, columns, when, hooks,
13794
+ // Fall back to the provided default if not given on this level
13795
+ useStorage = this.defaultConfig.useStorageByDefault } = options;
15450
13796
  const operations = Object.keys(when);
15451
13797
  if (operations.length == 0) {
15452
13798
  throw new Error('At least one WHEN operation must be specified for the trigger.');
15453
13799
  }
13800
+ /**
13801
+ * The clause to use when executing
13802
+ * CREATE ${tableTriggerTypeClause} TABLE
13803
+ * OR
13804
+ * CREATE ${tableTriggerTypeClause} TRIGGER
13805
+ */
13806
+ const tableTriggerTypeClause = !useStorage ? 'TEMP' : '';
15454
13807
  const whenClauses = Object.fromEntries(Object.entries(when).map(([operation, filter]) => [operation, `WHEN ${filter}`]));
15455
13808
  /**
15456
13809
  * Allow specifying the View name as the source.
@@ -15464,6 +13817,7 @@ class TriggerManagerImpl {
15464
13817
  const internalSource = sourceDefinition.internalName;
15465
13818
  const triggerIds = [];
15466
13819
  const id = await this.getUUID();
13820
+ const releaseStorageClaim = useStorage ? await this.options.claimManager.obtainClaim(id) : null;
15467
13821
  /**
15468
13822
  * We default to replicating all columns if no columns array is provided.
15469
13823
  */
@@ -15496,26 +13850,27 @@ class TriggerManagerImpl {
15496
13850
  return this.db.writeLock(async (tx) => {
15497
13851
  await this.removeTriggers(tx, triggerIds);
15498
13852
  await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
13853
+ await releaseStorageClaim?.();
15499
13854
  });
15500
13855
  };
15501
13856
  const setup = async (tx) => {
15502
13857
  // Allow user code to execute in this lock context before the trigger is created.
15503
13858
  await hooks?.beforeCreate?.(tx);
15504
13859
  await tx.execute(/* sql */ `
15505
- CREATE TEMP TABLE ${destination} (
13860
+ CREATE ${tableTriggerTypeClause} TABLE ${destination} (
15506
13861
  operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
15507
13862
  id TEXT,
15508
13863
  operation TEXT,
15509
13864
  timestamp TEXT,
15510
13865
  value TEXT,
15511
13866
  previous_value TEXT
15512
- );
13867
+ )
15513
13868
  `);
15514
13869
  if (operations.includes(DiffTriggerOperation.INSERT)) {
15515
- const insertTriggerId = `ps_temp_trigger_insert_${id}`;
13870
+ const insertTriggerId = this.generateTriggerName(DiffTriggerOperation.INSERT, destination, id);
15516
13871
  triggerIds.push(insertTriggerId);
15517
13872
  await tx.execute(/* sql */ `
15518
- CREATE TEMP TRIGGER ${insertTriggerId} AFTER INSERT ON ${internalSource} ${whenClauses[DiffTriggerOperation.INSERT]} BEGIN
13873
+ CREATE ${tableTriggerTypeClause} TRIGGER ${insertTriggerId} AFTER INSERT ON ${internalSource} ${whenClauses[DiffTriggerOperation.INSERT]} BEGIN
15519
13874
  INSERT INTO
15520
13875
  ${destination} (id, operation, timestamp, value)
15521
13876
  VALUES
@@ -15526,14 +13881,14 @@ class TriggerManagerImpl {
15526
13881
  ${jsonFragment('NEW')}
15527
13882
  );
15528
13883
 
15529
- END;
13884
+ END
15530
13885
  `);
15531
13886
  }
15532
13887
  if (operations.includes(DiffTriggerOperation.UPDATE)) {
15533
- const updateTriggerId = `ps_temp_trigger_update_${id}`;
13888
+ const updateTriggerId = this.generateTriggerName(DiffTriggerOperation.UPDATE, destination, id);
15534
13889
  triggerIds.push(updateTriggerId);
15535
13890
  await tx.execute(/* sql */ `
15536
- CREATE TEMP TRIGGER ${updateTriggerId} AFTER
13891
+ CREATE ${tableTriggerTypeClause} TRIGGER ${updateTriggerId} AFTER
15537
13892
  UPDATE ON ${internalSource} ${whenClauses[DiffTriggerOperation.UPDATE]} BEGIN
15538
13893
  INSERT INTO
15539
13894
  ${destination} (id, operation, timestamp, value, previous_value)
@@ -15550,11 +13905,11 @@ class TriggerManagerImpl {
15550
13905
  `);
15551
13906
  }
15552
13907
  if (operations.includes(DiffTriggerOperation.DELETE)) {
15553
- const deleteTriggerId = `ps_temp_trigger_delete_${id}`;
13908
+ const deleteTriggerId = this.generateTriggerName(DiffTriggerOperation.DELETE, destination, id);
15554
13909
  triggerIds.push(deleteTriggerId);
15555
13910
  // Create delete trigger for basic JSON
15556
13911
  await tx.execute(/* sql */ `
15557
- CREATE TEMP TRIGGER ${deleteTriggerId} AFTER DELETE ON ${internalSource} ${whenClauses[DiffTriggerOperation.DELETE]} BEGIN
13912
+ CREATE ${tableTriggerTypeClause} TRIGGER ${deleteTriggerId} AFTER DELETE ON ${internalSource} ${whenClauses[DiffTriggerOperation.DELETE]} BEGIN
15558
13913
  INSERT INTO
15559
13914
  ${destination} (id, operation, timestamp, value)
15560
13915
  VALUES
@@ -15598,7 +13953,7 @@ class TriggerManagerImpl {
15598
13953
  // If no array is provided, we use all columns from the source table.
15599
13954
  const contextColumns = columns ?? sourceDefinition.columns.map((col) => col.name);
15600
13955
  const id = await this.getUUID();
15601
- const destination = `ps_temp_track_${source}_${id}`;
13956
+ const destination = `__ps_temp_track_${source}_${id}`;
15602
13957
  // register an onChange before the trigger is created
15603
13958
  const abortController = new AbortController();
15604
13959
  const abortOnChange = () => abortController.abort();
@@ -15753,6 +14108,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
15753
14108
  * Allows creating SQLite triggers which can be used to track various operations on SQLite tables.
15754
14109
  */
15755
14110
  triggers;
14111
+ triggersImpl;
15756
14112
  logger;
15757
14113
  constructor(options) {
15758
14114
  super();
@@ -15816,9 +14172,10 @@ class AbstractPowerSyncDatabase extends BaseObserver {
15816
14172
  logger: this.logger
15817
14173
  });
15818
14174
  this._isReadyPromise = this.initialize();
15819
- this.triggers = new TriggerManagerImpl({
14175
+ this.triggers = this.triggersImpl = new TriggerManagerImpl({
15820
14176
  db: this,
15821
- schema: this.schema
14177
+ schema: this.schema,
14178
+ ...this.generateTriggerManagerConfig()
15822
14179
  });
15823
14180
  }
15824
14181
  /**
@@ -15844,6 +14201,15 @@ class AbstractPowerSyncDatabase extends BaseObserver {
15844
14201
  get connecting() {
15845
14202
  return this.currentStatus?.connecting || false;
15846
14203
  }
14204
+ /**
14205
+ * Generates a base configuration for {@link TriggerManagerImpl}.
14206
+ * Implementations should override this if necessary.
14207
+ */
14208
+ generateTriggerManagerConfig() {
14209
+ return {
14210
+ claimManager: MEMORY_TRIGGER_CLAIM_MANAGER
14211
+ };
14212
+ }
15847
14213
  /**
15848
14214
  * @returns A promise which will resolve once initialization is completed.
15849
14215
  */
@@ -15904,14 +14270,15 @@ class AbstractPowerSyncDatabase extends BaseObserver {
15904
14270
  async initialize() {
15905
14271
  await this._initialize();
15906
14272
  await this.bucketStorageAdapter.init();
15907
- await this._loadVersion();
14273
+ await this.loadVersion();
15908
14274
  await this.updateSchema(this.options.schema);
15909
14275
  await this.resolveOfflineSyncStatus();
15910
14276
  await this.database.execute('PRAGMA RECURSIVE_TRIGGERS=TRUE');
14277
+ await this.triggersImpl.cleanupResources();
15911
14278
  this.ready = true;
15912
14279
  this.iterateListeners((cb) => cb.initialized?.());
15913
14280
  }
15914
- async _loadVersion() {
14281
+ async loadVersion() {
15915
14282
  try {
15916
14283
  const { version } = await this.database.get('SELECT powersync_rs_version() as version');
15917
14284
  this.sdkVersion = version;
@@ -16027,7 +14394,6 @@ class AbstractPowerSyncDatabase extends BaseObserver {
16027
14394
  await this.disconnect();
16028
14395
  await this.waitForReady();
16029
14396
  const { clearLocal } = options;
16030
- // TODO DB name, verify this is necessary with extension
16031
14397
  await this.database.writeTransaction(async (tx) => {
16032
14398
  await tx.execute('SELECT powersync_clear(?)', [clearLocal ? 1 : 0]);
16033
14399
  });
@@ -16059,6 +14425,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
16059
14425
  if (this.closed) {
16060
14426
  return;
16061
14427
  }
14428
+ this.triggersImpl.dispose();
16062
14429
  await this.iterateAsyncListeners(async (cb) => cb.closing?.());
16063
14430
  const { disconnect } = options;
16064
14431
  if (disconnect) {
@@ -17050,6 +15417,27 @@ class SyncDataBatch {
17050
15417
  }
17051
15418
  }
17052
15419
 
15420
+ /**
15421
+ * Thrown when an underlying database connection is closed.
15422
+ * This is particularly relevant when worker connections are marked as closed while
15423
+ * operations are still in progress.
15424
+ */
15425
+ class ConnectionClosedError extends Error {
15426
+ static NAME = 'ConnectionClosedError';
15427
+ static MATCHES(input) {
15428
+ /**
15429
+ * If there are weird package issues which cause multiple versions of classes to be present, the instanceof
15430
+ * check might fail. This also performs a failsafe check.
15431
+ * This might also happen if the Error is serialized and parsed over a bridging channel like a MessagePort.
15432
+ */
15433
+ return (input instanceof ConnectionClosedError || (input instanceof Error && input.name == ConnectionClosedError.NAME));
15434
+ }
15435
+ constructor(message) {
15436
+ super(message);
15437
+ this.name = ConnectionClosedError.NAME;
15438
+ }
15439
+ }
15440
+
17053
15441
  // https://www.sqlite.org/lang_expr.html#castexpr
17054
15442
  var ColumnType;
17055
15443
  (function (ColumnType) {
@@ -17608,22 +15996,22 @@ const parseQuery = (query, parameters) => {
17608
15996
  //# sourceMappingURL=bundle.mjs.map
17609
15997
 
17610
15998
 
17611
- /***/ }),
15999
+ /***/ },
17612
16000
 
17613
- /***/ "./lib/src/db/adapters/LockedAsyncDatabaseAdapter.js":
16001
+ /***/ "./lib/src/db/adapters/LockedAsyncDatabaseAdapter.js"
17614
16002
  /*!***********************************************************!*\
17615
16003
  !*** ./lib/src/db/adapters/LockedAsyncDatabaseAdapter.js ***!
17616
16004
  \***********************************************************/
17617
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
16005
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
17618
16006
 
17619
16007
  __webpack_require__.r(__webpack_exports__);
17620
16008
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
17621
16009
  /* harmony export */ LockedAsyncDatabaseAdapter: () => (/* binding */ LockedAsyncDatabaseAdapter)
17622
16010
  /* harmony export */ });
17623
16011
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
17624
- /* harmony import */ var _shared_navigator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../..//shared/navigator */ "./lib/src/shared/navigator.js");
17625
- /* harmony import */ var _WorkerWrappedAsyncDatabaseConnection__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./WorkerWrappedAsyncDatabaseConnection */ "./lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js");
17626
- /* harmony import */ var _wa_sqlite_WASQLiteConnection__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./wa-sqlite/WASQLiteConnection */ "./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js");
16012
+ /* harmony import */ var _shared_navigator_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../shared/navigator.js */ "./lib/src/shared/navigator.js");
16013
+ /* harmony import */ var _WorkerWrappedAsyncDatabaseConnection_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./WorkerWrappedAsyncDatabaseConnection.js */ "./lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js");
16014
+ /* harmony import */ var _wa_sqlite_WASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./wa-sqlite/WASQLiteConnection.js */ "./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js");
17627
16015
 
17628
16016
 
17629
16017
 
@@ -17645,6 +16033,7 @@ class LockedAsyncDatabaseAdapter extends _powersync_common__WEBPACK_IMPORTED_MOD
17645
16033
  _config = null;
17646
16034
  pendingAbortControllers;
17647
16035
  requiresHolds;
16036
+ databaseOpenPromise = null;
17648
16037
  closing;
17649
16038
  closed;
17650
16039
  constructor(options) {
@@ -17694,29 +16083,86 @@ class LockedAsyncDatabaseAdapter extends _powersync_common__WEBPACK_IMPORTED_MOD
17694
16083
  async init() {
17695
16084
  return this.initPromise;
17696
16085
  }
16086
+ async openInternalDB() {
16087
+ /**
16088
+ * Execute opening of the db in a lock in order not to interfere with other operations.
16089
+ */
16090
+ return this._acquireLock(async () => {
16091
+ // Dispose any previous table change listener.
16092
+ this._disposeTableChangeListener?.();
16093
+ this._disposeTableChangeListener = null;
16094
+ this._db?.close().catch((ex) => this.logger.warn(`Error closing database before opening new instance`, ex));
16095
+ const isReOpen = !!this._db;
16096
+ this._db = null;
16097
+ this._db = await this.options.openConnection();
16098
+ await this._db.init();
16099
+ this._config = await this._db.getConfig();
16100
+ await this.registerOnChangeListener(this._db);
16101
+ if (isReOpen) {
16102
+ this.iterateListeners((cb) => cb.databaseReOpened?.());
16103
+ }
16104
+ /**
16105
+ * This is only required for the long-lived shared IndexedDB connections.
16106
+ */
16107
+ this.requiresHolds = this._config.vfs == _wa_sqlite_WASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_3__.WASQLiteVFS.IDBBatchAtomicVFS;
16108
+ });
16109
+ }
16110
+ _reOpen() {
16111
+ this.databaseOpenPromise = this.openInternalDB().finally(() => {
16112
+ this.databaseOpenPromise = null;
16113
+ });
16114
+ return this.databaseOpenPromise;
16115
+ }
16116
+ /**
16117
+ * Re-opens the underlying database.
16118
+ * Returns a pending operation if one is already in progress.
16119
+ */
16120
+ async reOpenInternalDB() {
16121
+ if (!this.options.reOpenOnConnectionClosed) {
16122
+ throw new Error(`Cannot re-open underlying database, reOpenOnConnectionClosed is not enabled`);
16123
+ }
16124
+ if (this.databaseOpenPromise) {
16125
+ return this.databaseOpenPromise;
16126
+ }
16127
+ return this._reOpen();
16128
+ }
17697
16129
  async _init() {
17698
- this._db = await this.options.openConnection();
17699
- await this._db.init();
17700
- this._config = await this._db.getConfig();
17701
- await this.registerOnChangeListener(this._db);
17702
- this.iterateListeners((cb) => cb.initialized?.());
17703
16130
  /**
17704
- * This is only required for the long-lived shared IndexedDB connections.
16131
+ * For OPFS, we can see this open call sometimes fail due to NoModificationAllowedError.
16132
+ * We should be able to recover from this by re-opening the database.
17705
16133
  */
17706
- this.requiresHolds = this._config.vfs == _wa_sqlite_WASQLiteConnection__WEBPACK_IMPORTED_MODULE_3__.WASQLiteVFS.IDBBatchAtomicVFS;
16134
+ const maxAttempts = 3;
16135
+ for (let count = 0; count < maxAttempts; count++) {
16136
+ try {
16137
+ await this.openInternalDB();
16138
+ break;
16139
+ }
16140
+ catch (ex) {
16141
+ if (count == maxAttempts - 1) {
16142
+ throw ex;
16143
+ }
16144
+ this.logger.warn(`Attempt ${count + 1} of ${maxAttempts} to open database failed, retrying in 1 second...`, ex);
16145
+ await new Promise((resolve) => setTimeout(resolve, 1000));
16146
+ }
16147
+ }
16148
+ this.iterateListeners((cb) => cb.initialized?.());
17707
16149
  }
17708
16150
  getConfiguration() {
17709
16151
  if (!this._config) {
17710
16152
  throw new Error(`Cannot get config before initialization is completed`);
17711
16153
  }
17712
- return this._config;
16154
+ return {
16155
+ ...this._config,
16156
+ // This can be overridden by the adapter later
16157
+ requiresPersistentTriggers: false
16158
+ };
17713
16159
  }
17714
16160
  async waitForInitialized() {
17715
16161
  // Awaiting this will expose errors on function calls like .execute etc
17716
16162
  await this.initPromise;
17717
16163
  }
17718
16164
  async shareConnection() {
17719
- if (false == this._db instanceof _WorkerWrappedAsyncDatabaseConnection__WEBPACK_IMPORTED_MODULE_2__.WorkerWrappedAsyncDatabaseConnection) {
16165
+ if (false == this._db instanceof _WorkerWrappedAsyncDatabaseConnection_js__WEBPACK_IMPORTED_MODULE_2__.WorkerWrappedAsyncDatabaseConnection) {
17720
16166
  throw new Error(`Only worker connections can be shared`);
17721
16167
  }
17722
16168
  return this._db.shareConnection();
@@ -17750,7 +16196,14 @@ class LockedAsyncDatabaseAdapter extends _powersync_common__WEBPACK_IMPORTED_MOD
17750
16196
  */
17751
16197
  async close() {
17752
16198
  this.closing = true;
17753
- this._disposeTableChangeListener?.();
16199
+ /**
16200
+ * Note that we obtain a reference to the callback to avoid calling the callback with `this` as the context.
16201
+ * This is to avoid Comlink attempting to clone `this` when calling the method.
16202
+ */
16203
+ const dispose = this._disposeTableChangeListener;
16204
+ if (dispose) {
16205
+ dispose();
16206
+ }
17754
16207
  this.pendingAbortControllers.forEach((controller) => controller.abort('Closed'));
17755
16208
  await this.baseDB?.close?.();
17756
16209
  this.closed = true;
@@ -17770,44 +16223,73 @@ class LockedAsyncDatabaseAdapter extends _powersync_common__WEBPACK_IMPORTED_MOD
17770
16223
  async readLock(fn, options) {
17771
16224
  await this.waitForInitialized();
17772
16225
  return this.acquireLock(async () => fn(this.generateDBHelpers({ execute: this._execute, executeRaw: this._executeRaw })), {
17773
- timeoutMs: options?.timeoutMs
16226
+ timeoutMs: options?.timeoutMs ?? this.options.defaultLockTimeoutMs
17774
16227
  });
17775
16228
  }
17776
16229
  async writeLock(fn, options) {
17777
16230
  await this.waitForInitialized();
17778
16231
  return this.acquireLock(async () => fn(this.generateDBHelpers({ execute: this._execute, executeRaw: this._executeRaw })), {
17779
- timeoutMs: options?.timeoutMs
16232
+ timeoutMs: options?.timeoutMs ?? this.options.defaultLockTimeoutMs
17780
16233
  });
17781
16234
  }
17782
- async acquireLock(callback, options) {
17783
- await this.waitForInitialized();
16235
+ async _acquireLock(callback, options) {
17784
16236
  if (this.closing) {
17785
16237
  throw new Error(`Cannot acquire lock, the database is closing`);
17786
16238
  }
17787
16239
  const abortController = new AbortController();
17788
16240
  this.pendingAbortControllers.add(abortController);
17789
16241
  const { timeoutMs } = options ?? {};
17790
- const timoutId = timeoutMs
16242
+ const timeoutId = timeoutMs
17791
16243
  ? setTimeout(() => {
17792
16244
  abortController.abort(`Timeout after ${timeoutMs}ms`);
17793
16245
  this.pendingAbortControllers.delete(abortController);
17794
16246
  }, timeoutMs)
17795
16247
  : null;
17796
- return (0,_shared_navigator__WEBPACK_IMPORTED_MODULE_1__.getNavigatorLocks)().request(`db-lock-${this._dbIdentifier}`, { signal: abortController.signal }, async () => {
16248
+ return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_1__.getNavigatorLocks)().request(`db-lock-${this._dbIdentifier}`, { signal: abortController.signal }, async () => {
17797
16249
  this.pendingAbortControllers.delete(abortController);
17798
- if (timoutId) {
17799
- clearTimeout(timoutId);
16250
+ if (timeoutId) {
16251
+ clearTimeout(timeoutId);
17800
16252
  }
17801
- const holdId = this.requiresHolds ? await this.baseDB.markHold() : null;
16253
+ return await callback();
16254
+ });
16255
+ }
16256
+ async acquireLock(callback, options) {
16257
+ await this.waitForInitialized();
16258
+ // The database is being opened in the background. Wait for it here.
16259
+ if (this.databaseOpenPromise) {
16260
+ await this.databaseOpenPromise;
16261
+ }
16262
+ return this._acquireLock(async () => {
16263
+ let holdId = null;
17802
16264
  try {
16265
+ /**
16266
+ * We can't await this since it uses the same lock as we're in now.
16267
+ * If there is a pending open, this call will throw.
16268
+ * If there is no pending open, but there is also no database - the open
16269
+ * might have failed. We need to re-open the database.
16270
+ */
16271
+ if (this.databaseOpenPromise || !this._db) {
16272
+ throw new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.ConnectionClosedError('Connection is busy re-opening');
16273
+ }
16274
+ holdId = this.requiresHolds ? await this.baseDB.markHold() : null;
17803
16275
  return await callback();
17804
16276
  }
16277
+ catch (ex) {
16278
+ if (_powersync_common__WEBPACK_IMPORTED_MODULE_0__.ConnectionClosedError.MATCHES(ex)) {
16279
+ if (this.options.reOpenOnConnectionClosed && !this.databaseOpenPromise && !this.closing) {
16280
+ // Immediately re-open the database. We need to miss as little table updates as possible.
16281
+ // Note, don't await this since it uses the same lock as we're in now.
16282
+ this.reOpenInternalDB();
16283
+ }
16284
+ }
16285
+ throw ex;
16286
+ }
17805
16287
  finally {
17806
16288
  if (holdId) {
17807
16289
  await this.baseDB.releaseHold(holdId);
17808
16290
  }
17809
16291
  }
17810
- });
16292
+ }, options);
17811
16293
  }
17812
16294
  async readTransaction(fn, options) {
17813
16295
  return this.readLock(this.wrapTransaction(fn));
@@ -17922,29 +16404,32 @@ class LockedAsyncDatabaseAdapter extends _powersync_common__WEBPACK_IMPORTED_MOD
17922
16404
  }
17923
16405
 
17924
16406
 
17925
- /***/ }),
16407
+ /***/ },
17926
16408
 
17927
- /***/ "./lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js":
16409
+ /***/ "./lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js"
17928
16410
  /*!*********************************************************************!*\
17929
16411
  !*** ./lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js ***!
17930
16412
  \*********************************************************************/
17931
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
16413
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
17932
16414
 
17933
16415
  __webpack_require__.r(__webpack_exports__);
17934
16416
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
17935
16417
  /* harmony export */ WorkerWrappedAsyncDatabaseConnection: () => (/* binding */ WorkerWrappedAsyncDatabaseConnection)
17936
16418
  /* harmony export */ });
17937
- /* harmony import */ var comlink__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! comlink */ "../../node_modules/comlink/dist/esm/comlink.mjs");
16419
+ /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
16420
+ /* harmony import */ var comlink__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! comlink */ "../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs");
16421
+
17938
16422
 
17939
16423
  /**
17940
16424
  * Wraps a provided instance of {@link AsyncDatabaseConnection}, providing necessary proxy
17941
16425
  * functions for worker listeners.
17942
16426
  */
17943
- class WorkerWrappedAsyncDatabaseConnection {
16427
+ class WorkerWrappedAsyncDatabaseConnection extends _powersync_common__WEBPACK_IMPORTED_MODULE_0__.BaseObserver {
17944
16428
  options;
17945
16429
  lockAbortController = new AbortController();
17946
16430
  notifyRemoteClosed;
17947
16431
  constructor(options) {
16432
+ super();
17948
16433
  this.options = options;
17949
16434
  if (options.remoteCanCloseUnexpectedly) {
17950
16435
  this.notifyRemoteClosed = new AbortController();
@@ -17977,17 +16462,20 @@ class WorkerWrappedAsyncDatabaseConnection {
17977
16462
  isAutoCommit() {
17978
16463
  return this.withRemote(() => this.baseConnection.isAutoCommit());
17979
16464
  }
17980
- withRemote(workerPromise) {
16465
+ withRemote(workerPromise, fireActionOnAbort = false) {
17981
16466
  const controller = this.notifyRemoteClosed;
17982
16467
  if (controller) {
17983
16468
  return new Promise((resolve, reject) => {
17984
16469
  if (controller.signal.aborted) {
17985
- reject(new Error('Called operation on closed remote'));
17986
- // Don't run the operation if we're going to reject
17987
- return;
16470
+ reject(new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.ConnectionClosedError('Called operation on closed remote'));
16471
+ if (!fireActionOnAbort) {
16472
+ // Don't run the operation if we're going to reject
16473
+ // We might want to fire-and-forget the operation in some cases (like a close operation)
16474
+ return;
16475
+ }
17988
16476
  }
17989
16477
  function handleAbort() {
17990
- reject(new Error('Remote peer closed with request in flight'));
16478
+ reject(new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.ConnectionClosedError('Remote peer closed with request in flight'));
17991
16479
  }
17992
16480
  function completePromise(action) {
17993
16481
  controller.signal.removeEventListener('abort', handleAbort);
@@ -18041,7 +16529,7 @@ class WorkerWrappedAsyncDatabaseConnection {
18041
16529
  reject(ex);
18042
16530
  }
18043
16531
  }));
18044
- const newPort = await remote[comlink__WEBPACK_IMPORTED_MODULE_0__.createEndpoint]();
16532
+ const newPort = await remote[comlink__WEBPACK_IMPORTED_MODULE_1__.createEndpoint]();
18045
16533
  return { port: newPort, identifier };
18046
16534
  }
18047
16535
  /**
@@ -18049,17 +16537,19 @@ class WorkerWrappedAsyncDatabaseConnection {
18049
16537
  * This can be extended by custom implementations in order to handle proxy events.
18050
16538
  */
18051
16539
  async registerOnTableChange(callback) {
18052
- return this.baseConnection.registerOnTableChange(comlink__WEBPACK_IMPORTED_MODULE_0__.proxy(callback));
16540
+ return this.baseConnection.registerOnTableChange(comlink__WEBPACK_IMPORTED_MODULE_1__.proxy(callback));
18053
16541
  }
18054
16542
  async close() {
18055
16543
  // Abort any pending lock requests.
18056
16544
  this.lockAbortController.abort();
18057
16545
  try {
18058
- await this.withRemote(() => this.baseConnection.close());
16546
+ // fire and forget the close operation
16547
+ await this.withRemote(() => this.baseConnection.close(), true);
18059
16548
  }
18060
16549
  finally {
18061
- this.options.remote[comlink__WEBPACK_IMPORTED_MODULE_0__.releaseProxy]();
16550
+ this.options.remote[comlink__WEBPACK_IMPORTED_MODULE_1__.releaseProxy]();
18062
16551
  this.options.onClose?.();
16552
+ this.iterateListeners((l) => l.closing?.());
18063
16553
  }
18064
16554
  }
18065
16555
  execute(sql, params) {
@@ -18077,13 +16567,13 @@ class WorkerWrappedAsyncDatabaseConnection {
18077
16567
  }
18078
16568
 
18079
16569
 
18080
- /***/ }),
16570
+ /***/ },
18081
16571
 
18082
- /***/ "./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js":
16572
+ /***/ "./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js"
18083
16573
  /*!*************************************************************!*\
18084
16574
  !*** ./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js ***!
18085
16575
  \*************************************************************/
18086
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
16576
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
18087
16577
 
18088
16578
  __webpack_require__.r(__webpack_exports__);
18089
16579
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -18095,9 +16585,9 @@ __webpack_require__.r(__webpack_exports__);
18095
16585
  /* harmony export */ WASQLiteVFS: () => (/* binding */ WASQLiteVFS),
18096
16586
  /* harmony export */ WASqliteConnection: () => (/* binding */ WASqliteConnection)
18097
16587
  /* harmony export */ });
18098
- /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
16588
+ /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
18099
16589
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
18100
- /* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! async-mutex */ "../../node_modules/async-mutex/index.mjs");
16590
+ /* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! async-mutex */ "../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs");
18101
16591
 
18102
16592
 
18103
16593
 
@@ -18114,28 +16604,28 @@ var WASQLiteVFS;
18114
16604
  * @internal
18115
16605
  */
18116
16606
  const AsyncWASQLiteModuleFactory = async () => {
18117
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_dist_wa-sqlite-async_mjs").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs */ "../../node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs"));
16607
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-f60d0d").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs"));
18118
16608
  return factory();
18119
16609
  };
18120
16610
  /**
18121
16611
  * @internal
18122
16612
  */
18123
16613
  const MultiCipherAsyncWASQLiteModuleFactory = async () => {
18124
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite-async_mjs").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs */ "../../node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs"));
16614
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-3a94cf").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs"));
18125
16615
  return factory();
18126
16616
  };
18127
16617
  /**
18128
16618
  * @internal
18129
16619
  */
18130
16620
  const SyncWASQLiteModuleFactory = async () => {
18131
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite.mjs */ "../../node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite.mjs"));
16621
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_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.4.1/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite.mjs"));
18132
16622
  return factory();
18133
16623
  };
18134
16624
  /**
18135
16625
  * @internal
18136
16626
  */
18137
16627
  const MultiCipherSyncWASQLiteModuleFactory = async () => {
18138
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite_mjs").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs */ "../../node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs"));
16628
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-868779").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs"));
18139
16629
  return factory();
18140
16630
  };
18141
16631
  /**
@@ -18150,7 +16640,7 @@ const DEFAULT_MODULE_FACTORIES = {
18150
16640
  else {
18151
16641
  module = await AsyncWASQLiteModuleFactory();
18152
16642
  }
18153
- const { IDBBatchAtomicVFS } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_src_examples_IDBBatchAtomicVFS_js").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js */ "../../node_modules/@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js"));
16643
+ const { IDBBatchAtomicVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-0d2437").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js"));
18154
16644
  return {
18155
16645
  module,
18156
16646
  // @ts-expect-error The types for this static method are missing upstream
@@ -18166,7 +16656,7 @@ const DEFAULT_MODULE_FACTORIES = {
18166
16656
  module = await SyncWASQLiteModuleFactory();
18167
16657
  }
18168
16658
  // @ts-expect-error The types for this static method are missing upstream
18169
- const { AccessHandlePoolVFS } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js */ "../../node_modules/@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js"));
16659
+ const { AccessHandlePoolVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-3622cf").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js"));
18170
16660
  return {
18171
16661
  module,
18172
16662
  vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)
@@ -18181,10 +16671,11 @@ const DEFAULT_MODULE_FACTORIES = {
18181
16671
  module = await SyncWASQLiteModuleFactory();
18182
16672
  }
18183
16673
  // @ts-expect-error The types for this static method are missing upstream
18184
- const { OPFSCoopSyncVFS } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_src_examples_OPFSCoopSyncVFS_js").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js */ "../../node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js"));
16674
+ const { OPFSCoopSyncVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-1d4e74").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js"));
16675
+ const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);
18185
16676
  return {
18186
16677
  module,
18187
- vfs: await OPFSCoopSyncVFS.create(options.dbFileName, module)
16678
+ vfs
18188
16679
  };
18189
16680
  }
18190
16681
  };
@@ -18410,7 +16901,15 @@ class WASqliteConnection extends _powersync_common__WEBPACK_IMPORTED_MODULE_1__.
18410
16901
  }
18411
16902
  async close() {
18412
16903
  this.broadcastChannel?.close();
18413
- await this.sqliteAPI.close(this.dbP);
16904
+ await this.acquireExecuteLock(async () => {
16905
+ /**
16906
+ * Running the close operation inside the same execute mutex prevents errors like:
16907
+ * ```
16908
+ * unable to close due to unfinalized statements or unfinished backups
16909
+ * ```
16910
+ */
16911
+ await this.sqliteAPI.close(this.dbP);
16912
+ });
18414
16913
  }
18415
16914
  async registerOnTableChange(callback) {
18416
16915
  return this.registerListener({
@@ -18492,20 +16991,20 @@ class WASqliteConnection extends _powersync_common__WEBPACK_IMPORTED_MODULE_1__.
18492
16991
  }
18493
16992
 
18494
16993
 
18495
- /***/ }),
16994
+ /***/ },
18496
16995
 
18497
- /***/ "./lib/src/db/sync/WebRemote.js":
16996
+ /***/ "./lib/src/db/sync/WebRemote.js"
18498
16997
  /*!**************************************!*\
18499
16998
  !*** ./lib/src/db/sync/WebRemote.js ***!
18500
16999
  \**************************************/
18501
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
17000
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
18502
17001
 
18503
17002
  __webpack_require__.r(__webpack_exports__);
18504
17003
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
18505
17004
  /* harmony export */ WebRemote: () => (/* binding */ WebRemote)
18506
17005
  /* harmony export */ });
18507
17006
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
18508
- /* harmony import */ var _userAgent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./userAgent */ "./lib/src/db/sync/userAgent.js");
17007
+ /* harmony import */ var _userAgent_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./userAgent.js */ "./lib/src/db/sync/userAgent.js");
18509
17008
 
18510
17009
 
18511
17010
  /*
@@ -18531,7 +17030,7 @@ class WebRemote extends _powersync_common__WEBPACK_IMPORTED_MODULE_0__.AbstractR
18531
17030
  getUserAgent() {
18532
17031
  let ua = [super.getUserAgent(), `powersync-web`];
18533
17032
  try {
18534
- ua.push(...(0,_userAgent__WEBPACK_IMPORTED_MODULE_1__.getUserAgentInfo)());
17033
+ ua.push(...(0,_userAgent_js__WEBPACK_IMPORTED_MODULE_1__.getUserAgentInfo)());
18535
17034
  }
18536
17035
  catch (e) {
18537
17036
  this.logger.warn('Failed to get user agent info', e);
@@ -18545,27 +17044,27 @@ class WebRemote extends _powersync_common__WEBPACK_IMPORTED_MODULE_0__.AbstractR
18545
17044
  /**
18546
17045
  * Dynamic import to be used only when needed.
18547
17046
  */
18548
- const { BSON } = await __webpack_require__.e(/*! import() */ "node_modules_bson_lib_bson_mjs").then(__webpack_require__.bind(__webpack_require__, /*! bson */ "../../node_modules/bson/lib/bson.mjs"));
17047
+ const { BSON } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_bson_6_10_4_node_modules_bson_lib_bson_mjs").then(__webpack_require__.bind(__webpack_require__, /*! bson */ "../../node_modules/.pnpm/bson@6.10.4/node_modules/bson/lib/bson.mjs"));
18549
17048
  this._bson = BSON;
18550
17049
  return this._bson;
18551
17050
  }
18552
17051
  }
18553
17052
 
18554
17053
 
18555
- /***/ }),
17054
+ /***/ },
18556
17055
 
18557
- /***/ "./lib/src/db/sync/WebStreamingSyncImplementation.js":
17056
+ /***/ "./lib/src/db/sync/WebStreamingSyncImplementation.js"
18558
17057
  /*!***********************************************************!*\
18559
17058
  !*** ./lib/src/db/sync/WebStreamingSyncImplementation.js ***!
18560
17059
  \***********************************************************/
18561
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
17060
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
18562
17061
 
18563
17062
  __webpack_require__.r(__webpack_exports__);
18564
17063
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
18565
17064
  /* harmony export */ WebStreamingSyncImplementation: () => (/* binding */ WebStreamingSyncImplementation)
18566
17065
  /* harmony export */ });
18567
17066
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
18568
- /* harmony import */ var _shared_navigator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../shared/navigator */ "./lib/src/shared/navigator.js");
17067
+ /* harmony import */ var _shared_navigator_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../shared/navigator.js */ "./lib/src/shared/navigator.js");
18569
17068
 
18570
17069
 
18571
17070
  class WebStreamingSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODULE_0__.AbstractStreamingSyncImplementation {
@@ -18581,18 +17080,18 @@ class WebStreamingSyncImplementation extends _powersync_common__WEBPACK_IMPORTED
18581
17080
  if (lockOptions.type == _powersync_common__WEBPACK_IMPORTED_MODULE_0__.LockType.SYNC) {
18582
17081
  this.logger.debug('requesting lock for ', identifier);
18583
17082
  }
18584
- return (0,_shared_navigator__WEBPACK_IMPORTED_MODULE_1__.getNavigatorLocks)().request(identifier, { signal: lockOptions.signal }, lockOptions.callback);
17083
+ return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_1__.getNavigatorLocks)().request(identifier, { signal: lockOptions.signal }, lockOptions.callback);
18585
17084
  }
18586
17085
  }
18587
17086
 
18588
17087
 
18589
- /***/ }),
17088
+ /***/ },
18590
17089
 
18591
- /***/ "./lib/src/db/sync/userAgent.js":
17090
+ /***/ "./lib/src/db/sync/userAgent.js"
18592
17091
  /*!**************************************!*\
18593
17092
  !*** ./lib/src/db/sync/userAgent.js ***!
18594
17093
  \**************************************/
18595
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
17094
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
18596
17095
 
18597
17096
  __webpack_require__.r(__webpack_exports__);
18598
17097
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -18664,13 +17163,13 @@ function getOsInfo(nav) {
18664
17163
  }
18665
17164
 
18666
17165
 
18667
- /***/ }),
17166
+ /***/ },
18668
17167
 
18669
- /***/ "./lib/src/shared/navigator.js":
17168
+ /***/ "./lib/src/shared/navigator.js"
18670
17169
  /*!*************************************!*\
18671
17170
  !*** ./lib/src/shared/navigator.js ***!
18672
17171
  \*************************************/
18673
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
17172
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
18674
17173
 
18675
17174
  __webpack_require__.r(__webpack_exports__);
18676
17175
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -18684,13 +17183,13 @@ const getNavigatorLocks = () => {
18684
17183
  };
18685
17184
 
18686
17185
 
18687
- /***/ }),
17186
+ /***/ },
18688
17187
 
18689
- /***/ "./lib/src/worker/sync/BroadcastLogger.js":
17188
+ /***/ "./lib/src/worker/sync/BroadcastLogger.js"
18690
17189
  /*!************************************************!*\
18691
17190
  !*** ./lib/src/worker/sync/BroadcastLogger.js ***!
18692
17191
  \************************************************/
18693
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
17192
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
18694
17193
 
18695
17194
  __webpack_require__.r(__webpack_exports__);
18696
17195
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -18827,13 +17326,13 @@ class BroadcastLogger {
18827
17326
  }
18828
17327
 
18829
17328
 
18830
- /***/ }),
17329
+ /***/ },
18831
17330
 
18832
- /***/ "./lib/src/worker/sync/SharedSyncImplementation.js":
17331
+ /***/ "./lib/src/worker/sync/SharedSyncImplementation.js"
18833
17332
  /*!*********************************************************!*\
18834
17333
  !*** ./lib/src/worker/sync/SharedSyncImplementation.js ***!
18835
17334
  \*********************************************************/
18836
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
17335
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
18837
17336
 
18838
17337
  __webpack_require__.r(__webpack_exports__);
18839
17338
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -18841,13 +17340,13 @@ __webpack_require__.r(__webpack_exports__);
18841
17340
  /* harmony export */ SharedSyncImplementation: () => (/* binding */ SharedSyncImplementation)
18842
17341
  /* harmony export */ });
18843
17342
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
18844
- /* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! async-mutex */ "../../node_modules/async-mutex/index.mjs");
18845
- /* harmony import */ var comlink__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! comlink */ "../../node_modules/comlink/dist/esm/comlink.mjs");
18846
- /* harmony import */ var _db_sync_WebRemote__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../db/sync/WebRemote */ "./lib/src/db/sync/WebRemote.js");
18847
- /* harmony import */ var _db_sync_WebStreamingSyncImplementation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../db/sync/WebStreamingSyncImplementation */ "./lib/src/db/sync/WebStreamingSyncImplementation.js");
18848
- /* harmony import */ var _db_adapters_LockedAsyncDatabaseAdapter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../db/adapters/LockedAsyncDatabaseAdapter */ "./lib/src/db/adapters/LockedAsyncDatabaseAdapter.js");
18849
- /* harmony import */ var _db_adapters_WorkerWrappedAsyncDatabaseConnection__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../db/adapters/WorkerWrappedAsyncDatabaseConnection */ "./lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js");
18850
- /* harmony import */ var _BroadcastLogger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./BroadcastLogger */ "./lib/src/worker/sync/BroadcastLogger.js");
17343
+ /* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! async-mutex */ "../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs");
17344
+ /* 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");
17345
+ /* harmony import */ var _db_sync_WebRemote_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../db/sync/WebRemote.js */ "./lib/src/db/sync/WebRemote.js");
17346
+ /* harmony import */ var _db_sync_WebStreamingSyncImplementation_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../db/sync/WebStreamingSyncImplementation.js */ "./lib/src/db/sync/WebStreamingSyncImplementation.js");
17347
+ /* harmony import */ var _db_adapters_LockedAsyncDatabaseAdapter_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../db/adapters/LockedAsyncDatabaseAdapter.js */ "./lib/src/db/adapters/LockedAsyncDatabaseAdapter.js");
17348
+ /* harmony import */ var _db_adapters_WorkerWrappedAsyncDatabaseConnection_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../db/adapters/WorkerWrappedAsyncDatabaseConnection.js */ "./lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js");
17349
+ /* harmony import */ var _BroadcastLogger_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./BroadcastLogger.js */ "./lib/src/worker/sync/BroadcastLogger.js");
18851
17350
 
18852
17351
 
18853
17352
 
@@ -18885,7 +17384,6 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
18885
17384
  statusListener;
18886
17385
  fetchCredentialsController;
18887
17386
  uploadDataController;
18888
- dbAdapter;
18889
17387
  syncParams;
18890
17388
  logger;
18891
17389
  lastConnectOptions;
@@ -18894,10 +17392,10 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
18894
17392
  connectionManager;
18895
17393
  syncStatus;
18896
17394
  broadCastLogger;
17395
+ distributedDB;
18897
17396
  constructor() {
18898
17397
  super();
18899
17398
  this.ports = [];
18900
- this.dbAdapter = null;
18901
17399
  this.syncParams = null;
18902
17400
  this.logger = (0,_powersync_common__WEBPACK_IMPORTED_MODULE_0__.createLogger)('shared-sync');
18903
17401
  this.lastConnectOptions = undefined;
@@ -18910,26 +17408,23 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
18910
17408
  }
18911
17409
  });
18912
17410
  });
17411
+ // Should be configured once we get params
17412
+ this.distributedDB = null;
18913
17413
  this.syncStatus = new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.SyncStatus({});
18914
- this.broadCastLogger = new _BroadcastLogger__WEBPACK_IMPORTED_MODULE_6__.BroadcastLogger(this.ports);
17414
+ this.broadCastLogger = new _BroadcastLogger_js__WEBPACK_IMPORTED_MODULE_7__.BroadcastLogger(this.ports);
18915
17415
  this.connectionManager = new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.ConnectionManager({
18916
17416
  createSyncImplementation: async () => {
18917
- return this.portMutex.runExclusive(async () => {
18918
- await this.waitForReady();
18919
- if (!this.dbAdapter) {
18920
- await this.openInternalDB();
17417
+ await this.waitForReady();
17418
+ const sync = this.generateStreamingImplementation();
17419
+ const onDispose = sync.registerListener({
17420
+ statusChanged: (status) => {
17421
+ this.updateAllStatuses(status.toJSON());
18921
17422
  }
18922
- const sync = this.generateStreamingImplementation();
18923
- const onDispose = sync.registerListener({
18924
- statusChanged: (status) => {
18925
- this.updateAllStatuses(status.toJSON());
18926
- }
18927
- });
18928
- return {
18929
- sync,
18930
- onDispose
18931
- };
18932
17423
  });
17424
+ return {
17425
+ sync,
17426
+ onDispose
17427
+ };
18933
17428
  },
18934
17429
  logger: this.logger
18935
17430
  });
@@ -18940,6 +17435,30 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
18940
17435
  get isConnected() {
18941
17436
  return this.connectionManager.syncStreamImplementation?.isConnected ?? false;
18942
17437
  }
17438
+ /**
17439
+ * Gets the last client port which we know is safe from unexpected closes.
17440
+ */
17441
+ async getLastWrappedPort() {
17442
+ // Find the last port which is not closing
17443
+ return await this.portMutex.runExclusive(() => {
17444
+ for (let i = this.ports.length - 1; i >= 0; i--) {
17445
+ if (!this.ports[i].isClosing) {
17446
+ return this.ports[i];
17447
+ }
17448
+ }
17449
+ return;
17450
+ });
17451
+ }
17452
+ /**
17453
+ * In some very rare cases a specific tab might not respond to requests.
17454
+ * This returns a random port which is not closing.
17455
+ */
17456
+ async getRandomWrappedPort() {
17457
+ return await this.portMutex.runExclusive(() => {
17458
+ const nonClosingPorts = this.ports.filter((p) => !p.isClosing);
17459
+ return nonClosingPorts[Math.floor(Math.random() * nonClosingPorts.length)];
17460
+ });
17461
+ }
18943
17462
  async waitForStatus(status) {
18944
17463
  return this.withSyncImplementation(async (sync) => {
18945
17464
  return sync.waitForStatus(status);
@@ -18980,28 +17499,53 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
18980
17499
  async setParams(params) {
18981
17500
  await this.portMutex.runExclusive(async () => {
18982
17501
  this.collectActiveSubscriptions();
18983
- if (this.syncParams) {
18984
- // Cannot modify already existing sync implementation params
18985
- // But we can ask for a DB adapter, if required, at this point.
18986
- if (!this.dbAdapter) {
18987
- await this.openInternalDB();
18988
- }
18989
- return;
18990
- }
18991
- // First time setting params
18992
- this.syncParams = params;
18993
- if (params.streamOptions?.flags?.broadcastLogs) {
18994
- this.logger = this.broadCastLogger;
18995
- }
18996
- self.onerror = (event) => {
18997
- // Share any uncaught events on the broadcast logger
18998
- this.logger.error('Uncaught exception in PowerSync shared sync worker', event);
18999
- };
19000
- if (!this.dbAdapter) {
19001
- await this.openInternalDB();
17502
+ });
17503
+ if (this.syncParams) {
17504
+ // Cannot modify already existing sync implementation params
17505
+ return;
17506
+ }
17507
+ // First time setting params
17508
+ this.syncParams = params;
17509
+ if (params.streamOptions?.flags?.broadcastLogs) {
17510
+ this.logger = this.broadCastLogger;
17511
+ }
17512
+ const lockedAdapter = new _db_adapters_LockedAsyncDatabaseAdapter_js__WEBPACK_IMPORTED_MODULE_5__.LockedAsyncDatabaseAdapter({
17513
+ name: params.dbParams.dbFilename,
17514
+ openConnection: async () => {
17515
+ // Gets a connection from the clients when a new connection is requested.
17516
+ const db = await this.openInternalDB();
17517
+ db.registerListener({
17518
+ closing: () => {
17519
+ lockedAdapter.reOpenInternalDB();
17520
+ }
17521
+ });
17522
+ return db;
17523
+ },
17524
+ logger: this.logger,
17525
+ reOpenOnConnectionClosed: true
17526
+ });
17527
+ this.distributedDB = lockedAdapter;
17528
+ await lockedAdapter.init();
17529
+ lockedAdapter.registerListener({
17530
+ databaseReOpened: () => {
17531
+ // We may have missed some table updates while the database was closed.
17532
+ // We can poke the crud in case we missed any updates.
17533
+ this.connectionManager.syncStreamImplementation?.triggerCrudUpload();
17534
+ /**
17535
+ * FIXME or IMPROVE ME
17536
+ * The Rust client implementation stores sync state on the connection level.
17537
+ * Reopening the database causes a state machine error which should cause the
17538
+ * StreamingSyncImplementation to reconnect. It would be nicer if we could trigger
17539
+ * this reconnect earlier.
17540
+ * This reconnect is not required for IndexedDB.
17541
+ */
19002
17542
  }
19003
- this.iterateListeners((l) => l.initialized?.());
19004
17543
  });
17544
+ self.onerror = (event) => {
17545
+ // Share any uncaught events on the broadcast logger
17546
+ this.logger.error('Uncaught exception in PowerSync shared sync worker', event);
17547
+ };
17548
+ this.iterateListeners((l) => l.initialized?.());
19005
17549
  }
19006
17550
  async dispose() {
19007
17551
  await this.waitForReady();
@@ -19028,9 +17572,10 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
19028
17572
  return await this.portMutex.runExclusive(() => {
19029
17573
  const portProvider = {
19030
17574
  port,
19031
- clientProvider: comlink__WEBPACK_IMPORTED_MODULE_7__.wrap(port),
17575
+ clientProvider: comlink__WEBPACK_IMPORTED_MODULE_2__.wrap(port),
19032
17576
  currentSubscriptions: [],
19033
- closeListeners: []
17577
+ closeListeners: [],
17578
+ isClosing: false
19034
17579
  };
19035
17580
  this.ports.push(portProvider);
19036
17581
  // Give the newly connected client the latest status
@@ -19046,14 +17591,16 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
19046
17591
  * clients.
19047
17592
  */
19048
17593
  async removePort(port) {
17594
+ // Ports might be removed faster than we can process them.
17595
+ port.isClosing = true;
19049
17596
  // Remove the port within a mutex context.
19050
17597
  // Warns if the port is not found. This should not happen in practice.
19051
17598
  // We return early if the port is not found.
19052
- const { trackedPort, shouldReconnect } = await this.portMutex.runExclusive(async () => {
17599
+ return await this.portMutex.runExclusive(async () => {
19053
17600
  const index = this.ports.findIndex((p) => p == port);
19054
17601
  if (index < 0) {
19055
17602
  this.logger.warn(`Could not remove port ${port} since it is not present in active ports.`);
19056
- return {};
17603
+ return () => { };
19057
17604
  }
19058
17605
  const trackedPort = this.ports[index];
19059
17606
  // Remove from the list of active ports
@@ -19067,35 +17614,13 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
19067
17614
  abortController.controller.abort(new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.AbortOperation('Closing pending requests after client port is removed'));
19068
17615
  }
19069
17616
  });
19070
- const shouldReconnect = !!this.connectionManager.syncStreamImplementation && this.ports.length > 0;
19071
- return {
19072
- shouldReconnect,
19073
- trackedPort
19074
- };
19075
- });
19076
- if (!trackedPort) {
19077
- // We could not find the port to remove
19078
- return () => { };
19079
- }
19080
- for (const closeListener of trackedPort.closeListeners) {
19081
- await closeListener();
19082
- }
19083
- if (this.dbAdapter && this.dbAdapter == trackedPort.db) {
19084
- // Unconditionally close the connection because the database it's writing to has just been closed.
19085
- // The connection has been closed previously, this might throw. We should be able to ignore it.
19086
- await this.connectionManager
19087
- .disconnect()
19088
- .catch((ex) => this.logger.warn('Error while disconnecting. Will attempt to reconnect.', ex));
19089
- // Clearing the adapter will result in a new one being opened in connect
19090
- this.dbAdapter = null;
19091
- if (shouldReconnect) {
19092
- await this.connectionManager.connect(CONNECTOR_PLACEHOLDER, this.lastConnectOptions ?? {});
17617
+ // Close the worker wrapped database connection, we can't accurately rely on this connection
17618
+ for (const closeListener of trackedPort.closeListeners) {
17619
+ await closeListener();
19093
17620
  }
19094
- }
19095
- // Re-index subscriptions, the subscriptions of the removed port would no longer be considered.
19096
- this.collectActiveSubscriptions();
19097
- // Release proxy
19098
- return () => trackedPort.clientProvider[comlink__WEBPACK_IMPORTED_MODULE_7__.releaseProxy]();
17621
+ this.collectActiveSubscriptions();
17622
+ return () => trackedPort.clientProvider[comlink__WEBPACK_IMPORTED_MODULE_2__.releaseProxy]();
17623
+ });
19099
17624
  }
19100
17625
  triggerCrudUpload() {
19101
17626
  this.withSyncImplementation(async (sync) => {
@@ -19131,11 +17656,14 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
19131
17656
  // This should only be called after initialization has completed
19132
17657
  const syncParams = this.syncParams;
19133
17658
  // Create a new StreamingSyncImplementation for each connect call. This is usually done is all SDKs.
19134
- return new _db_sync_WebStreamingSyncImplementation__WEBPACK_IMPORTED_MODULE_3__.WebStreamingSyncImplementation({
19135
- adapter: new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.SqliteBucketStorage(this.dbAdapter, this.logger),
19136
- remote: new _db_sync_WebRemote__WEBPACK_IMPORTED_MODULE_2__.WebRemote({
17659
+ return new _db_sync_WebStreamingSyncImplementation_js__WEBPACK_IMPORTED_MODULE_4__.WebStreamingSyncImplementation({
17660
+ adapter: new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.SqliteBucketStorage(this.distributedDB, this.logger),
17661
+ remote: new _db_sync_WebRemote_js__WEBPACK_IMPORTED_MODULE_3__.WebRemote({
19137
17662
  invalidateCredentials: async () => {
19138
- const lastPort = this.ports[this.ports.length - 1];
17663
+ const lastPort = await this.getLastWrappedPort();
17664
+ if (!lastPort) {
17665
+ throw new Error('No client port found to invalidate credentials');
17666
+ }
19139
17667
  try {
19140
17668
  this.logger.log('calling the last port client provider to invalidate credentials');
19141
17669
  lastPort.clientProvider.invalidateCredentials();
@@ -19145,7 +17673,10 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
19145
17673
  }
19146
17674
  },
19147
17675
  fetchCredentials: async () => {
19148
- const lastPort = this.ports[this.ports.length - 1];
17676
+ const lastPort = await this.getLastWrappedPort();
17677
+ if (!lastPort) {
17678
+ throw new Error('No client port found to fetch credentials');
17679
+ }
19149
17680
  return new Promise(async (resolve, reject) => {
19150
17681
  const abortController = new AbortController();
19151
17682
  this.fetchCredentialsController = {
@@ -19167,7 +17698,10 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
19167
17698
  }
19168
17699
  }, this.logger),
19169
17700
  uploadCrud: async () => {
19170
- const lastPort = this.ports[this.ports.length - 1];
17701
+ const lastPort = await this.getLastWrappedPort();
17702
+ if (!lastPort) {
17703
+ throw new Error('No client port found to upload crud');
17704
+ }
19171
17705
  return new Promise(async (resolve, reject) => {
19172
17706
  const abortController = new AbortController();
19173
17707
  this.uploadDataController = {
@@ -19193,38 +17727,81 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
19193
17727
  logger: this.logger
19194
17728
  });
19195
17729
  }
17730
+ /**
17731
+ * Opens a worker wrapped database connection. Using the last connected client port.
17732
+ */
19196
17733
  async openInternalDB() {
19197
- const lastClient = this.ports[this.ports.length - 1];
19198
- if (!lastClient) {
17734
+ const client = await this.getRandomWrappedPort();
17735
+ if (!client) {
19199
17736
  // Should not really happen in practice
19200
17737
  throw new Error(`Could not open DB connection since no client is connected.`);
19201
17738
  }
19202
- const workerPort = await lastClient.clientProvider.getDBWorkerPort();
19203
- const remote = comlink__WEBPACK_IMPORTED_MODULE_7__.wrap(workerPort);
17739
+ // Fail-safe timeout for opening a database connection.
17740
+ const timeout = setTimeout(() => {
17741
+ abortController.abort();
17742
+ }, 10_000);
17743
+ /**
17744
+ * Handle cases where the client might close while opening a connection.
17745
+ */
17746
+ const abortController = new AbortController();
17747
+ const closeListener = () => {
17748
+ abortController.abort();
17749
+ };
17750
+ const removeCloseListener = () => {
17751
+ const index = client.closeListeners.indexOf(closeListener);
17752
+ if (index >= 0) {
17753
+ client.closeListeners.splice(index, 1);
17754
+ }
17755
+ };
17756
+ client.closeListeners.push(closeListener);
17757
+ const workerPort = await withAbort({
17758
+ action: () => client.clientProvider.getDBWorkerPort(),
17759
+ signal: abortController.signal,
17760
+ cleanupOnAbort: (port) => {
17761
+ port.close();
17762
+ }
17763
+ }).catch((ex) => {
17764
+ removeCloseListener();
17765
+ throw ex;
17766
+ });
17767
+ const remote = comlink__WEBPACK_IMPORTED_MODULE_2__.wrap(workerPort);
19204
17768
  const identifier = this.syncParams.dbParams.dbFilename;
19205
- const db = await remote(this.syncParams.dbParams);
19206
- const locked = new _db_adapters_LockedAsyncDatabaseAdapter__WEBPACK_IMPORTED_MODULE_4__.LockedAsyncDatabaseAdapter({
19207
- name: identifier,
19208
- openConnection: async () => {
19209
- const wrapped = new _db_adapters_WorkerWrappedAsyncDatabaseConnection__WEBPACK_IMPORTED_MODULE_5__.WorkerWrappedAsyncDatabaseConnection({
19210
- remote,
19211
- baseConnection: db,
19212
- identifier,
19213
- // It's possible for this worker to outlive the client hosting the database for us. We need to be prepared for
19214
- // that and ensure pending requests are aborted when the tab is closed.
19215
- remoteCanCloseUnexpectedly: true
19216
- });
19217
- lastClient.closeListeners.push(async () => {
19218
- this.logger.info('Aborting open connection because associated tab closed.');
19219
- await wrapped.close().catch((ex) => this.logger.warn('error closing database connection', ex));
19220
- wrapped.markRemoteClosed();
19221
- });
19222
- return wrapped;
19223
- },
19224
- logger: this.logger
17769
+ /**
17770
+ * The open could fail if the tab is closed while we're busy opening the database.
17771
+ * This operation is typically executed inside an exclusive portMutex lock.
17772
+ * We typically execute the closeListeners using the portMutex in a different context.
17773
+ * We can't rely on the closeListeners to abort the operation if the tab is closed.
17774
+ */
17775
+ const db = await withAbort({
17776
+ action: () => remote(this.syncParams.dbParams),
17777
+ signal: abortController.signal,
17778
+ cleanupOnAbort: (db) => {
17779
+ db.close();
17780
+ }
17781
+ }).finally(() => {
17782
+ // We can remove the close listener here since we no longer need it past this point.
17783
+ removeCloseListener();
17784
+ });
17785
+ clearTimeout(timeout);
17786
+ const wrapped = new _db_adapters_WorkerWrappedAsyncDatabaseConnection_js__WEBPACK_IMPORTED_MODULE_6__.WorkerWrappedAsyncDatabaseConnection({
17787
+ remote,
17788
+ baseConnection: db,
17789
+ identifier,
17790
+ // It's possible for this worker to outlive the client hosting the database for us. We need to be prepared for
17791
+ // that and ensure pending requests are aborted when the tab is closed.
17792
+ remoteCanCloseUnexpectedly: true
17793
+ });
17794
+ client.closeListeners.push(async () => {
17795
+ this.logger.info('Aborting open connection because associated tab closed.');
17796
+ /**
17797
+ * Don't await this close operation. It might never resolve if the tab is closed.
17798
+ * We mark the remote as closed first, this will reject any pending requests.
17799
+ * We then call close. The close operation is configured to fire-and-forget, the main promise will reject immediately.
17800
+ */
17801
+ wrapped.markRemoteClosed();
17802
+ wrapped.close().catch((ex) => this.logger.warn('error closing database connection', ex));
19225
17803
  });
19226
- await locked.init();
19227
- this.dbAdapter = lastClient.db = locked;
17804
+ return wrapped;
19228
17805
  }
19229
17806
  /**
19230
17807
  * A method to update the all shared statuses for each
@@ -19234,36 +17811,54 @@ class SharedSyncImplementation extends _powersync_common__WEBPACK_IMPORTED_MODUL
19234
17811
  this.syncStatus = new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.SyncStatus(status);
19235
17812
  this.ports.forEach((p) => p.clientProvider.statusChanged(status));
19236
17813
  }
19237
- /**
19238
- * A function only used for unit tests which updates the internal
19239
- * sync stream client and all tab client's sync status
19240
- */
19241
- async _testUpdateAllStatuses(status) {
19242
- if (!this.connectionManager.syncStreamImplementation) {
19243
- throw new Error('Cannot update status without a sync stream implementation');
17814
+ }
17815
+ /**
17816
+ * Runs the action with an abort controller.
17817
+ */
17818
+ function withAbort(options) {
17819
+ const { action, signal, cleanupOnAbort } = options;
17820
+ return new Promise((resolve, reject) => {
17821
+ if (signal.aborted) {
17822
+ reject(new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.AbortOperation('Operation aborted by abort controller'));
17823
+ return;
19244
17824
  }
19245
- // Only assigning, don't call listeners for this test
19246
- this.connectionManager.syncStreamImplementation.syncStatus = new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.SyncStatus(status);
19247
- this.updateAllStatuses(status);
19248
- }
17825
+ function handleAbort() {
17826
+ signal.removeEventListener('abort', handleAbort);
17827
+ reject(new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.AbortOperation('Operation aborted by abort controller'));
17828
+ }
17829
+ signal.addEventListener('abort', handleAbort, { once: true });
17830
+ function completePromise(action) {
17831
+ signal.removeEventListener('abort', handleAbort);
17832
+ action();
17833
+ }
17834
+ action()
17835
+ .then((data) => {
17836
+ // We already rejected due to the abort, allow for cleanup
17837
+ if (signal.aborted) {
17838
+ return completePromise(() => cleanupOnAbort?.(data));
17839
+ }
17840
+ completePromise(() => resolve(data));
17841
+ })
17842
+ .catch((e) => completePromise(() => reject(e)));
17843
+ });
19249
17844
  }
19250
17845
 
19251
17846
 
19252
- /***/ }),
17847
+ /***/ },
19253
17848
 
19254
- /***/ "./lib/src/worker/sync/WorkerClient.js":
17849
+ /***/ "./lib/src/worker/sync/WorkerClient.js"
19255
17850
  /*!*********************************************!*\
19256
17851
  !*** ./lib/src/worker/sync/WorkerClient.js ***!
19257
17852
  \*********************************************/
19258
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
17853
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
19259
17854
 
19260
17855
  __webpack_require__.r(__webpack_exports__);
19261
17856
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
19262
17857
  /* harmony export */ WorkerClient: () => (/* binding */ WorkerClient)
19263
17858
  /* harmony export */ });
19264
- /* harmony import */ var comlink__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! comlink */ "../../node_modules/comlink/dist/esm/comlink.mjs");
19265
- /* harmony import */ var _SharedSyncImplementation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SharedSyncImplementation */ "./lib/src/worker/sync/SharedSyncImplementation.js");
19266
- /* harmony import */ var _shared_navigator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../shared/navigator */ "./lib/src/shared/navigator.js");
17859
+ /* harmony import */ var comlink__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! comlink */ "../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs");
17860
+ /* harmony import */ var _shared_navigator_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../shared/navigator.js */ "./lib/src/shared/navigator.js");
17861
+ /* harmony import */ var _SharedSyncImplementation_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./SharedSyncImplementation.js */ "./lib/src/worker/sync/SharedSyncImplementation.js");
19267
17862
 
19268
17863
 
19269
17864
 
@@ -19277,23 +17872,21 @@ class WorkerClient {
19277
17872
  sync;
19278
17873
  port;
19279
17874
  resolvedPort = null;
17875
+ resolvedPortPromise = null;
19280
17876
  constructor(sync, port) {
19281
17877
  this.sync = sync;
19282
17878
  this.port = port;
19283
- }
19284
- async initialize() {
17879
+ comlink__WEBPACK_IMPORTED_MODULE_0__.expose(this, this.port);
19285
17880
  /**
19286
17881
  * Adds an extra listener which can remove this port
19287
17882
  * from the list of monitored ports.
19288
17883
  */
19289
17884
  this.port.addEventListener('message', async (event) => {
19290
17885
  const payload = event.data;
19291
- if (payload?.event == _SharedSyncImplementation__WEBPACK_IMPORTED_MODULE_0__.SharedSyncClientEvent.CLOSE_CLIENT) {
17886
+ if (payload?.event == _SharedSyncImplementation_js__WEBPACK_IMPORTED_MODULE_2__.SharedSyncClientEvent.CLOSE_CLIENT) {
19292
17887
  await this.removePort();
19293
17888
  }
19294
17889
  });
19295
- this.resolvedPort = await this.sync.addPort(this.port);
19296
- comlink__WEBPACK_IMPORTED_MODULE_2__.expose(this, this.port);
19297
17890
  }
19298
17891
  async removePort() {
19299
17892
  if (this.resolvedPort) {
@@ -19302,7 +17895,7 @@ class WorkerClient {
19302
17895
  const release = await this.sync.removePort(resolved);
19303
17896
  this.resolvedPort = null;
19304
17897
  this.port.postMessage({
19305
- event: _SharedSyncImplementation__WEBPACK_IMPORTED_MODULE_0__.SharedSyncClientEvent.CLOSE_ACK,
17898
+ event: _SharedSyncImplementation_js__WEBPACK_IMPORTED_MODULE_2__.SharedSyncClientEvent.CLOSE_ACK,
19306
17899
  data: {}
19307
17900
  });
19308
17901
  release?.();
@@ -19314,8 +17907,11 @@ class WorkerClient {
19314
17907
  * When the client tab is closed, its lock will be returned. So when the shared worker attempts to acquire the lock,
19315
17908
  * it can consider the connection to be closed.
19316
17909
  */
19317
- addLockBasedCloseSignal(name) {
19318
- (0,_shared_navigator__WEBPACK_IMPORTED_MODULE_1__.getNavigatorLocks)().request(name, async () => {
17910
+ async addLockBasedCloseSignal(name) {
17911
+ // Only add the port once the lock has been obtained on the client.
17912
+ this.resolvedPort = await this.sync.addPort(this.port);
17913
+ // Don't await this lock request
17914
+ (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_1__.getNavigatorLocks)().request(name, async () => {
19319
17915
  await this.removePort();
19320
17916
  });
19321
17917
  }
@@ -19346,13 +17942,10 @@ class WorkerClient {
19346
17942
  disconnect() {
19347
17943
  return this.sync.disconnect();
19348
17944
  }
19349
- async _testUpdateAllStatuses(status) {
19350
- return this.sync._testUpdateAllStatuses(status);
19351
- }
19352
17945
  }
19353
17946
 
19354
17947
 
19355
- /***/ })
17948
+ /***/ }
19356
17949
 
19357
17950
  /******/ });
19358
17951
  /************************************************************************/
@@ -19366,6 +17959,12 @@ class WorkerClient {
19366
17959
  /******/ if (cachedModule !== undefined) {
19367
17960
  /******/ return cachedModule.exports;
19368
17961
  /******/ }
17962
+ /******/ // Check if module exists (development only)
17963
+ /******/ if (__webpack_modules__[moduleId] === undefined) {
17964
+ /******/ var e = new Error("Cannot find module '" + moduleId + "'");
17965
+ /******/ e.code = 'MODULE_NOT_FOUND';
17966
+ /******/ throw e;
17967
+ /******/ }
19369
17968
  /******/ // Create a new module (and put it into the cache)
19370
17969
  /******/ var module = __webpack_module_cache__[moduleId] = {
19371
17970
  /******/ // no module.id needed
@@ -19519,18 +18118,18 @@ var __webpack_exports__ = {};
19519
18118
  \****************************************************************/
19520
18119
  __webpack_require__.r(__webpack_exports__);
19521
18120
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
19522
- /* harmony import */ var _SharedSyncImplementation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./SharedSyncImplementation */ "./lib/src/worker/sync/SharedSyncImplementation.js");
19523
- /* harmony import */ var _WorkerClient__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./WorkerClient */ "./lib/src/worker/sync/WorkerClient.js");
18121
+ /* harmony import */ var _SharedSyncImplementation_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./SharedSyncImplementation.js */ "./lib/src/worker/sync/SharedSyncImplementation.js");
18122
+ /* harmony import */ var _WorkerClient_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./WorkerClient.js */ "./lib/src/worker/sync/WorkerClient.js");
19524
18123
 
19525
18124
 
19526
18125
 
19527
18126
  const _self = self;
19528
18127
  const logger = (0,_powersync_common__WEBPACK_IMPORTED_MODULE_0__.createBaseLogger)();
19529
18128
  logger.useDefaults();
19530
- const sharedSyncImplementation = new _SharedSyncImplementation__WEBPACK_IMPORTED_MODULE_1__.SharedSyncImplementation();
18129
+ const sharedSyncImplementation = new _SharedSyncImplementation_js__WEBPACK_IMPORTED_MODULE_1__.SharedSyncImplementation();
19531
18130
  _self.onconnect = async function (event) {
19532
18131
  const port = event.ports[0];
19533
- await new _WorkerClient__WEBPACK_IMPORTED_MODULE_2__.WorkerClient(sharedSyncImplementation, port).initialize();
18132
+ new _WorkerClient_js__WEBPACK_IMPORTED_MODULE_2__.WorkerClient(sharedSyncImplementation, port);
19534
18133
  };
19535
18134
 
19536
18135
  })();