@powersync/web 1.33.0 → 1.35.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.
- package/dist/26d61ca9f5694d064635.wasm +0 -0
- package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js +70 -70
- package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js.map +1 -1
- package/dist/{_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-2530150.index.umd.js → _journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js} +77 -77
- package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js.map +1 -0
- package/dist/b4c6283dc473b6b3fd24.wasm +0 -0
- package/dist/c78985091a0b22aaef03.wasm +0 -0
- package/dist/ca59e199e1138b553fad.wasm +0 -0
- package/dist/index.umd.js +140 -178
- package/dist/index.umd.js.map +1 -1
- package/dist/worker/SharedSyncImplementation.umd.js +18187 -18190
- package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
- package/dist/worker/WASQLiteDB.umd.js +16981 -16984
- package/dist/worker/WASQLiteDB.umd.js.map +1 -1
- package/dist/worker/node_modules_pnpm_bson_6_10_4_node_modules_bson_lib_bson_mjs.umd.js.map +1 -1
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-b9c070.umd.js +31 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-b9c070.umd.js.map +1 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-c99c07.umd.js +31 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-c99c07.umd.js.map +1 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-cc5fcc.umd.js +31 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-cc5fcc.umd.js.map +1 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +31 -0
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map +1 -0
- package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-0d2437.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-0df390.umd.js} +16 -16
- package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-0d2437.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-0df390.umd.js.map} +1 -1
- package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-3622cf.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-151024.umd.js} +12 -12
- package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-3622cf.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-151024.umd.js.map} +1 -1
- package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-1d4e74.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-c01ef0.umd.js} +12 -12
- package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-1d4e74.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-c01ef0.umd.js.map} +1 -1
- package/lib/package.json +3 -3
- package/lib/src/index.d.ts +1 -0
- package/lib/src/index.js +1 -0
- package/lib/tsconfig.tsbuildinfo +1 -1
- package/package.json +5 -5
- package/src/index.ts +1 -0
- package/dist/0b19af1befc07ce338dd.wasm +0 -0
- package/dist/2632c3bda9473da74fd5.wasm +0 -0
- package/dist/64f5351ba3784bfe2f3e.wasm +0 -0
- package/dist/9318ca94aac4d0fe0135.wasm +0 -0
- package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-2530150.index.umd.js.map +0 -1
- package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-2530151.index.umd.js +0 -555
- package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-2530151.index.umd.js.map +0 -1
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-3a94cf.umd.js +0 -44
- 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 +0 -1
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-868779.umd.js +0 -44
- 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 +0 -1
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-f60d0d.umd.js +0 -44
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-f60d0d.umd.js.map +0 -1
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +0 -44
- package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker/WASQLiteDB.umd.js","mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACl7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;AClRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;AClSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACrWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;AC1icA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;AChZA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACRA;AACA;AACA;AACA;AACA;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACPA;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","sources":["webpack://sdk_web/../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js","webpack://sdk_web/../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js","webpack://sdk_web/../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs","webpack://sdk_web/../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs","webpack://sdk_web/../common/dist/bundle.mjs","webpack://sdk_web/./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js","webpack://sdk_web/./lib/src/shared/navigator.js","webpack://sdk_web/./lib/src/worker/db/SharedWASQLiteConnection.js","webpack://sdk_web/./lib/src/worker/db/WorkerWASQLiteConnection.js","webpack://sdk_web/webpack/bootstrap","webpack://sdk_web/webpack/runtime/define property getters","webpack://sdk_web/webpack/runtime/ensure chunk","webpack://sdk_web/webpack/runtime/get javascript chunk filename","webpack://sdk_web/webpack/runtime/global","webpack://sdk_web/webpack/runtime/hasOwnProperty shorthand","webpack://sdk_web/webpack/runtime/make namespace object","webpack://sdk_web/webpack/runtime/publicPath","webpack://sdk_web/webpack/runtime/importScripts chunk loading","webpack://sdk_web/./lib/src/worker/db/WASQLiteDB.worker.js"],"sourcesContent":["// Copyright 2021 Roy T. Hashimoto. All Rights Reserved.\n\nimport * as SQLite from './sqlite-constants.js';\nexport * from './sqlite-constants.js';\n\n/**\n * Need to have a serializer for bigint\n * https://github.com/GoogleChromeLabs/jsbi/issues/30\n */\nif (typeof BigInt.prototype['toJSON'] == 'undefined') {\n BigInt.prototype['toJSON'] = function() {\n return this.toString();\n };\n}\n\nconst MAX_INT64 = 0x7fffffffffffffffn;\nconst MIN_INT64 = -0x8000000000000000n;\n\nconst AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;\n\nexport class SQLiteError extends Error {\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\n\nconst async = true;\n\n\n/**\n * Builds a Javascript API from the Emscripten module. This API is still\n * low-level and closely corresponds to the C API exported by the module,\n * but differs in some specifics like throwing exceptions on errors.\n * @param {*} Module SQLite Emscripten module\n * @returns {SQLiteAPI}\n */\nexport function Factory(Module) {\n /** @type {SQLiteAPI} */ const sqlite3 = {};\n\n Module.retryOps = [];\n const sqliteFreeAddress = Module._getSqliteFree();\n\n // Allocate some space for 32-bit returned values.\n const tmp = Module._malloc(8);\n const tmpPtr = [tmp, tmp + 4];\n\n const textEncoder = new TextEncoder();\n // Convert a JS string to a C string. sqlite3_malloc is used to allocate\n // memory (use sqlite3_free to deallocate).\n function createUTF8(s) {\n if (typeof s !== 'string') return 0;\n const utf8 = textEncoder.encode(s);\n const zts = Module._sqlite3_malloc(utf8.byteLength + 1);\n Module.HEAPU8.set(utf8, zts);\n Module.HEAPU8[zts + utf8.byteLength] = 0;\n return zts;\n }\n\n /**\n * Concatenate 32-bit numbers into a 64-bit (signed) BigInt.\n * @param {number} lo32\n * @param {number} hi32\n * @returns {bigint}\n */\n function cvt32x2ToBigInt(lo32, hi32) {\n return (BigInt(hi32) << 32n) | (BigInt(lo32) & 0xffffffffn);\n }\n\n // /**\n // * Setup table change update callback\n // */\n // var onTableChangedFunctionPointer = Module.addFunction(onTableUpdate);\n // var passFnPointer = Module.cwrap('passFnPointer', 'undefined', ['number']);\n // passFnPointer(onTableChangedFunctionPointer);\n /**\n * Concatenate 32-bit numbers and return as number or BigInt, depending\n * on the value.\n * @param {number} lo32\n * @param {number} hi32\n * @returns {number|bigint}\n */\n const cvt32x2AsSafe = (function() {\n const hiMax = BigInt(Number.MAX_SAFE_INTEGER) >> 32n;\n const hiMin = BigInt(Number.MIN_SAFE_INTEGER) >> 32n;\n\n return function(lo32, hi32) {\n if (hi32 > hiMax || hi32 < hiMin) {\n // Can't be expressed as a Number so use BigInt.\n return cvt32x2ToBigInt(lo32, hi32);\n } else {\n // Combine the upper and lower 32-bit numbers. The complication is\n // that lo32 is a signed integer which makes manipulating its bits\n // a little tricky - the sign bit gets handled separately.\n return hi32 * 0x100000000 + (lo32 & 0x7fffffff) - (lo32 & 0x80000000);\n }\n };\n })();\n\n const databases = new Set();\n function verifyDatabase(db) {\n if (!databases.has(db)) {\n throw new SQLiteError('not a database', SQLite.SQLITE_MISUSE);\n }\n }\n\n const mapStmtToDB = new Map();\n function verifyStatement(stmt) {\n if (!mapStmtToDB.has(stmt)) {\n throw new SQLiteError('not a statement', SQLite.SQLITE_MISUSE);\n }\n }\n\n sqlite3.bind_collection = function(stmt, bindings) {\n verifyStatement(stmt);\n const isArray = Array.isArray(bindings);\n const nBindings = sqlite3.bind_parameter_count(stmt);\n for (let i = 1; i <= nBindings; ++i) {\n const key = isArray ? i - 1 : sqlite3.bind_parameter_name(stmt, i);\n const value = bindings[key];\n if (value !== undefined) {\n sqlite3.bind(stmt, i, value);\n }\n }\n return SQLite.SQLITE_OK;\n };\n\n sqlite3.bind = function(stmt, i, value) {\n verifyStatement(stmt);\n switch (typeof value) {\n case 'number':\n if (value === (value | 0)) {\n return sqlite3.bind_int(stmt, i, value);\n } else {\n return sqlite3.bind_double(stmt, i, value);\n }\n case 'string':\n return sqlite3.bind_text(stmt, i, value);\n case \"boolean\":\n return sqlite3.bind_int(stmt, i, value ? 1 : 0);\n default:\n if (value instanceof Uint8Array || Array.isArray(value)) {\n return sqlite3.bind_blob(stmt, i, value);\n } else if (value === null) {\n return sqlite3.bind_null(stmt, i);\n } else if (typeof value === 'bigint') {\n return sqlite3.bind_int64(stmt, i, value);\n } else if (value === undefined) {\n // Existing binding (or NULL) will be used.\n return SQLite.SQLITE_NOTICE;\n } else {\n console.warn('unknown binding converted to null', value);\n return sqlite3.bind_null(stmt, i);\n }\n }\n };\n\n sqlite3.bind_blob = (function() {\n const fname = 'sqlite3_bind_blob';\n const f = Module.cwrap(fname, ...decl('nnnnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n // @ts-ignore\n const byteLength = value.byteLength ?? value.length;\n const ptr = Module._sqlite3_malloc(byteLength);\n Module.HEAPU8.subarray(ptr).set(value);\n const result = f(stmt, i, ptr, byteLength, sqliteFreeAddress);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_parameter_count = (function() {\n const fname = 'sqlite3_bind_parameter_count';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return result;\n };\n })();\n\n sqlite3.bind_double = (function() {\n const fname = 'sqlite3_bind_double';\n const f = Module.cwrap(fname, ...decl('nnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n const result = f(stmt, i, value);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_int = (function() {\n const fname = 'sqlite3_bind_int';\n const f = Module.cwrap(fname, ...decl('nnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n if (value > 0x7fffffff || value < -0x80000000) return SQLite.SQLITE_RANGE;\n\n const result = f(stmt, i, value);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_int64 = (function() {\n const fname = 'sqlite3_bind_int64';\n const f = Module.cwrap(fname, ...decl('nnnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n if (value > MAX_INT64 || value < MIN_INT64) return SQLite.SQLITE_RANGE;\n\n const lo32 = value & 0xffffffffn;\n const hi32 = value >> 32n;\n const result = f(stmt, i, Number(lo32), Number(hi32));\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_null = (function() {\n const fname = 'sqlite3_bind_null';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, i) {\n verifyStatement(stmt);\n const result = f(stmt, i);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_parameter_name = (function() {\n const fname = 'sqlite3_bind_parameter_name';\n const f = Module.cwrap(fname, ...decl('n:s'));\n return function(stmt, i) {\n verifyStatement(stmt);\n const result = f(stmt, i);\n return result;\n };\n })();\n\n sqlite3.bind_text = (function() {\n const fname = 'sqlite3_bind_text';\n const f = Module.cwrap(fname, ...decl('nnnnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n const ptr = createUTF8(value);\n const result = f(stmt, i, ptr, -1, sqliteFreeAddress);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.changes = (function() {\n const fname = 'sqlite3_changes';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(db) {\n verifyDatabase(db);\n const result = f(db);\n return result;\n };\n })();\n\n sqlite3.clear_bindings = (function() {\n const fname = 'sqlite3_clear_bindings';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.last_insert_id = (function() {\n const fname = 'sqlite3_last_insert_rowid';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(db) {\n verifyDatabase(db);\n const result = f(db);\n // trace(fname, result);\n return result;\n };\n })();\n \n sqlite3.close = (function() {\n const fname = 'sqlite3_close';\n const f = Module.cwrap(fname, ...decl('n:n'), { async });\n return async function(db) {\n verifyDatabase(db);\n const result = await f(db);\n databases.delete(db);\n return check(fname, result, db);\n };\n })();\n\n sqlite3.column = function(stmt, iCol) {\n verifyStatement(stmt);\n const type = sqlite3.column_type(stmt, iCol);\n switch (type) {\n case SQLite.SQLITE_BLOB:\n return sqlite3.column_blob(stmt, iCol);\n case SQLite.SQLITE_FLOAT:\n return sqlite3.column_double(stmt, iCol);\n case SQLite.SQLITE_INTEGER:\n const lo32 = sqlite3.column_int(stmt, iCol);\n const hi32 = Module.getTempRet0();\n return cvt32x2AsSafe(lo32, hi32);\n case SQLite.SQLITE_NULL:\n return null;\n case SQLite.SQLITE_TEXT:\n return sqlite3.column_text(stmt, iCol);\n default:\n throw new SQLiteError('unknown type', type);\n }\n };\n\n sqlite3.column_blob = (function() {\n const fname = 'sqlite3_column_blob';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const nBytes = sqlite3.column_bytes(stmt, iCol);\n const address = f(stmt, iCol);\n const result = Module.HEAPU8.subarray(address, address + nBytes);\n return result;\n };\n })();\n\n sqlite3.column_bytes = (function() {\n const fname = 'sqlite3_column_bytes';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_count = (function() {\n const fname = 'sqlite3_column_count';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return result;\n };\n })();\n\n sqlite3.column_double = (function() {\n const fname = 'sqlite3_column_double';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_int = (function() {\n // Retrieve int64 but use only the lower 32 bits. The upper 32-bits are\n // accessible with Module.getTempRet0().\n const fname = 'sqlite3_column_int64';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_int64 = (function() {\n const fname = 'sqlite3_column_int64';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const lo32 = f(stmt, iCol);\n const hi32 = Module.getTempRet0();\n const result = cvt32x2ToBigInt(lo32, hi32);\n return result;\n };\n })();\n\n sqlite3.column_name = (function() {\n const fname = 'sqlite3_column_name';\n const f = Module.cwrap(fname, ...decl('nn:s'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_names = function(stmt) {\n const columns = [];\n const nColumns = sqlite3.column_count(stmt);\n for (let i = 0; i < nColumns; ++i) {\n columns.push(sqlite3.column_name(stmt, i));\n }\n return columns;\n };\n\n sqlite3.column_text = (function() {\n const fname = 'sqlite3_column_text';\n const f = Module.cwrap(fname, ...decl('nn:s'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_type = (function() {\n const fname = 'sqlite3_column_type';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.create_function = function(db, zFunctionName, nArg, eTextRep, pApp, xFunc, xStep, xFinal) {\n verifyDatabase(db);\n \n // Convert SQLite callback arguments to JavaScript-friendly arguments.\n function adapt(f) {\n return f instanceof AsyncFunction ?\n (async (ctx, n, values) => f(ctx, Module.HEAP32.subarray(values / 4, values / 4 + n))) :\n ((ctx, n, values) => f(ctx, Module.HEAP32.subarray(values / 4, values / 4 + n)));\n }\n\n const result = Module.create_function(\n db,\n zFunctionName,\n nArg,\n eTextRep,\n pApp,\n xFunc && adapt(xFunc),\n xStep && adapt(xStep),\n xFinal);\n return check('sqlite3_create_function', result, db);\n };\n\n sqlite3.data_count = (function() {\n const fname = 'sqlite3_data_count';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return result;\n };\n })();\n\n sqlite3.exec = async function(db, sql, callback) {\n for await (const stmt of sqlite3.statements(db, sql)) {\n let columns;\n while ((await sqlite3.step(stmt)) === SQLite.SQLITE_ROW) {\n if (callback) {\n columns = columns ?? sqlite3.column_names(stmt);\n const row = sqlite3.row(stmt);\n await callback(row, columns);\n }\n }\n }\n return SQLite.SQLITE_OK;\n };\n\n sqlite3.finalize = (function() {\n const fname = 'sqlite3_finalize';\n const f = Module.cwrap(fname, ...decl('n:n'), { async });\n return async function(stmt) {\n const result = await f(stmt);\n mapStmtToDB.delete(stmt)\n\n // Don't throw on error here. Typically the error has already been\n // thrown and finalize() is part of the cleanup.\n return result;\n };\n })();\n\n sqlite3.get_autocommit = (function() {\n const fname = 'sqlite3_get_autocommit';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(db) {\n const result = f(db);\n return result;\n };\n })();\n\n sqlite3.libversion = (function() {\n const fname = 'sqlite3_libversion';\n const f = Module.cwrap(fname, ...decl(':s'));\n return function() {\n const result = f();\n return result;\n };\n })();\n\n sqlite3.libversion_number = (function() {\n const fname = 'sqlite3_libversion_number';\n const f = Module.cwrap(fname, ...decl(':n'));\n return function() {\n const result = f();\n return result;\n };\n })();\n\n sqlite3.limit = (function() {\n const fname = 'sqlite3_limit';\n const f = Module.cwrap(fname, ...decl('nnn:n'));\n return function(db, id, newVal) {\n const result = f(db, id, newVal);\n return result;\n };\n })();\n\n sqlite3.open_v2 = (function() {\n const fname = 'sqlite3_open_v2';\n const f = Module.cwrap(fname, ...decl('snnn:n'), { async });\n return async function(zFilename, flags, zVfs) {\n flags = flags || SQLite.SQLITE_OPEN_CREATE | SQLite.SQLITE_OPEN_READWRITE;\n zVfs = createUTF8(zVfs);\n try {\n // Allow retry operations.\n const rc = await retry(() => f(zFilename, tmpPtr[0], flags, zVfs));\n\n const db = Module.getValue(tmpPtr[0], '*');\n databases.add(db);\n\n Module.ccall('RegisterExtensionFunctions', 'number', ['number'], [db]);\n check(fname, rc);\n return db;\n } finally {\n Module._sqlite3_free(zVfs);\n }\n };\n })();\n\n sqlite3.progress_handler = function(db, nProgressOps, handler, userData) {\n verifyDatabase(db);\n Module.progress_handler(db, nProgressOps, handler, userData);\n };;\n\n sqlite3.reset = (function() {\n const fname = 'sqlite3_reset';\n const f = Module.cwrap(fname, ...decl('n:n'), { async });\n return async function(stmt) {\n verifyStatement(stmt);\n const result = await f(stmt);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.result = function(context, value) {\n switch (typeof value) {\n case 'number':\n if (value === (value | 0)) {\n sqlite3.result_int(context, value);\n } else {\n sqlite3.result_double(context, value);\n }\n break;\n case 'string':\n sqlite3.result_text(context, value);\n break;\n default:\n if (value instanceof Uint8Array || Array.isArray(value)) {\n sqlite3.result_blob(context, value);\n } else if (value === null) {\n sqlite3.result_null(context);\n } else if (typeof value === 'bigint') {\n return sqlite3.result_int64(context, value);\n } else {\n console.warn('unknown result converted to null', value);\n sqlite3.result_null(context);\n }\n break;\n }\n };\n\n sqlite3.result_blob = (function() {\n const fname = 'sqlite3_result_blob';\n const f = Module.cwrap(fname, ...decl('nnnn:n'));\n return function(context, value) {\n // @ts-ignore\n const byteLength = value.byteLength ?? value.length;\n const ptr = Module._sqlite3_malloc(byteLength);\n Module.HEAPU8.subarray(ptr).set(value);\n f(context, ptr, byteLength, sqliteFreeAddress); // void return\n };\n })();\n\n sqlite3.result_double = (function() {\n const fname = 'sqlite3_result_double';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(context, value) {\n f(context, value); // void return\n };\n })();\n\n sqlite3.result_int = (function() {\n const fname = 'sqlite3_result_int';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(context, value) {\n f(context, value); // void return\n };\n })();\n\n sqlite3.result_int64 = (function() {\n const fname = 'sqlite3_result_int64';\n const f = Module.cwrap(fname, ...decl('nnn:n'));\n return function(context, value) {\n if (value > MAX_INT64 || value < MIN_INT64) return SQLite.SQLITE_RANGE;\n\n const lo32 = value & 0xffffffffn;\n const hi32 = value >> 32n;\n f(context, Number(lo32), Number(hi32)); // void return\n };\n })();\n\n sqlite3.result_null = (function() {\n const fname = 'sqlite3_result_null';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(context) {\n f(context); // void return\n };\n })();\n\n sqlite3.result_text = (function() {\n const fname = 'sqlite3_result_text';\n const f = Module.cwrap(fname, ...decl('nnnn:n'));\n return function(context, value) {\n const ptr = createUTF8(value);\n f(context, ptr, -1, sqliteFreeAddress); // void return\n };\n })();\n\n sqlite3.row = function(stmt) {\n const row = [];\n const nColumns = sqlite3.data_count(stmt);\n for (let i = 0; i < nColumns; ++i) {\n const value = sqlite3.column(stmt, i);\n\n // Copy blob if aliasing volatile WebAssembly memory. This avoids an\n // unnecessary copy if users monkey patch column_blob to copy.\n // @ts-ignore\n row.push(value?.buffer === Module.HEAPU8.buffer ? value.slice() : value);\n }\n return row;\n };\n\n sqlite3.set_authorizer = function(db, xAuth, pApp) {\n verifyDatabase(db);\n\n // Convert SQLite callback arguments to JavaScript-friendly arguments.\n function cvtArgs(_, iAction, p3, p4, p5, p6) {\n return [\n _,\n iAction,\n Module.UTF8ToString(p3),\n Module.UTF8ToString(p4),\n Module.UTF8ToString(p5),\n Module.UTF8ToString(p6)\n ];\n };\n function adapt(f) {\n return f instanceof AsyncFunction ?\n (async (_, iAction, p3, p4, p5, p6) => f(...cvtArgs(_, iAction, p3, p4, p5, p6))) :\n ((_, iAction, p3, p4, p5, p6) => f(...cvtArgs(_, iAction, p3, p4, p5, p6)));\n }\n\n const result = Module.set_authorizer(db, adapt(xAuth), pApp);\n return check('sqlite3_set_authorizer', result, db);\n };\n\n sqlite3.sql = (function() {\n const fname = 'sqlite3_sql';\n const f = Module.cwrap(fname, ...decl('n:s'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return result;\n };\n })();\n\n sqlite3.statements = function(db, sql, options = {}) {\n const prepare = Module.cwrap(\n 'sqlite3_prepare_v3',\n 'number',\n ['number', 'number', 'number', 'number', 'number', 'number'],\n { async: true });\n\n return (async function*() {\n const onFinally = [];\n try {\n // Encode SQL string to UTF-8.\n const utf8 = textEncoder.encode(sql);\n\n // Copy encoded string to WebAssembly memory. The SQLite docs say\n // zero-termination is a minor optimization so add room for that.\n // Also add space for the statement handle and SQL tail pointer.\n const allocSize = utf8.byteLength - (utf8.byteLength % 4) + 12;\n const pzHead = Module._sqlite3_malloc(allocSize);\n const pzEnd = pzHead + utf8.byteLength + 1;\n onFinally.push(() => Module._sqlite3_free(pzHead));\n Module.HEAPU8.set(utf8, pzHead);\n Module.HEAPU8[pzEnd - 1] = 0;\n \n // Use extra space for the statement handle and SQL tail pointer.\n const pStmt = pzHead + allocSize - 8;\n const pzTail = pzHead + allocSize - 4;\n\n // Ensure that statement handles are not leaked.\n let stmt;\n function maybeFinalize() {\n if (stmt && !options.unscoped) {\n sqlite3.finalize(stmt);\n }\n stmt = 0;\n }\n onFinally.push(maybeFinalize);\n \n // Loop over statements.\n Module.setValue(pzTail, pzHead, '*');\n do {\n // Reclaim resources for the previous iteration.\n maybeFinalize();\n\n // Call sqlite3_prepare_v3() for the next statement.\n // Allow retry operations.\n const zTail = Module.getValue(pzTail, '*');\n const rc = await retry(() => {\n return prepare(\n db,\n zTail,\n pzEnd - pzTail,\n options.flags || 0,\n pStmt,\n pzTail);\n });\n\n if (rc !== SQLite.SQLITE_OK) {\n check('sqlite3_prepare_v3', rc, db);\n }\n \n stmt = Module.getValue(pStmt, '*');\n if (stmt) {\n mapStmtToDB.set(stmt, db);\n yield stmt;\n }\n } while (stmt);\n } finally {\n while (onFinally.length) {\n onFinally.pop()();\n }\n }\n })();\n };\n\n sqlite3.step = (function() {\n const fname = 'sqlite3_step';\n const f = Module.cwrap(fname, ...decl('n:n'), { async });\n return async function(stmt) {\n verifyStatement(stmt);\n\n // Allow retry operations.\n const rc = await retry(() => f(stmt));\n\n return check(fname, rc, mapStmtToDB.get(stmt), [SQLite.SQLITE_ROW, SQLite.SQLITE_DONE]);\n };\n })();\n\n sqlite3.commit_hook = function(db, xCommitHook) {\n verifyDatabase(db);\n Module.commit_hook(db, xCommitHook);\n };\n\n sqlite3.update_hook = function(db, xUpdateHook) {\n verifyDatabase(db);\n\n // Convert SQLite callback arguments to JavaScript-friendly arguments.\n function cvtArgs(iUpdateType, dbName, tblName, lo32, hi32) {\n return [\n iUpdateType,\n Module.UTF8ToString(dbName),\n Module.UTF8ToString(tblName),\n\t\tcvt32x2ToBigInt(lo32, hi32)\n ];\n };\n function adapt(f) {\n return f instanceof AsyncFunction ?\n (async (iUpdateType, dbName, tblName, lo32, hi32) => f(...cvtArgs(iUpdateType, dbName, tblName, lo32, hi32))) :\n ((iUpdateType, dbName, tblName, lo32, hi32) => f(...cvtArgs(iUpdateType, dbName, tblName, lo32, hi32)));\n }\n\n Module.update_hook(db, adapt(xUpdateHook));\n };;\n\n sqlite3.value = function(pValue) {\n const type = sqlite3.value_type(pValue);\n switch (type) {\n case SQLite.SQLITE_BLOB:\n return sqlite3.value_blob(pValue);\n case SQLite.SQLITE_FLOAT:\n return sqlite3.value_double(pValue);\n case SQLite.SQLITE_INTEGER:\n const lo32 = sqlite3.value_int(pValue);\n const hi32 = Module.getTempRet0();\n return cvt32x2AsSafe(lo32, hi32);\n case SQLite.SQLITE_NULL:\n return null;\n case SQLite.SQLITE_TEXT:\n return sqlite3.value_text(pValue);\n default:\n throw new SQLiteError('unknown type', type);\n }\n };\n\n sqlite3.value_blob = (function() {\n const fname = 'sqlite3_value_blob';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const nBytes = sqlite3.value_bytes(pValue);\n const address = f(pValue);\n const result = Module.HEAPU8.subarray(address, address + nBytes);\n return result;\n };\n })();\n\n sqlite3.value_bytes = (function() {\n const fname = 'sqlite3_value_bytes';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.value_double = (function() {\n const fname = 'sqlite3_value_double';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.value_int = (function() {\n const fname = 'sqlite3_value_int64';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.value_int64 = (function() {\n const fname = 'sqlite3_value_int64';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const lo32 = f(pValue);\n const hi32 = Module.getTempRet0();\n const result = cvt32x2ToBigInt(lo32, hi32);\n return result;\n };\n })();\n\n sqlite3.value_text = (function() {\n const fname = 'sqlite3_value_text';\n const f = Module.cwrap(fname, ...decl('n:s'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.value_type = (function() {\n const fname = 'sqlite3_value_type';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.vfs_register = function(vfs, makeDefault) {\n const result = Module.vfs_register(vfs, makeDefault);\n return check('sqlite3_vfs_register', result);\n };\n\n function check(fname, result, db = null, allowed = [SQLite.SQLITE_OK]) {\n if (allowed.includes(result)) return result;\n const message = db ? Module.ccall('sqlite3_errmsg', 'string', ['number'], [db]) : fname;\n throw new SQLiteError(message, result);\n }\n\n // This function is used to automatically retry failed calls that\n // have pending retry operations that should allow the retry to\n // succeed.\n async function retry(f) {\n let rc;\n do {\n // Wait for all pending retry operations to complete. This is\n // normally empty on the first loop iteration.\n if (Module.retryOps.length) {\n try {\n await Promise.all(Module.retryOps);\n } finally {\n Module.retryOps = [];\n }\n }\n \n rc = await f();\n\n // Retry on failure with new pending retry operations.\n } while (rc && Module.retryOps.length);\n return rc;\n }\n\n return sqlite3;\n}\n\n// Helper function to use a more compact signature specification.\nfunction decl(s) {\n const result = [];\n const m = s.match(/([ns@]*):([nsv@])/);\n switch (m[2]) {\n case 'n':\n result.push('number');\n break;\n case 's':\n result.push('string');\n break;\n case 'v':\n result.push(null);\n break;\n }\n\n const args = [];\n for (let c of m[1]) {\n switch (c) {\n case 'n':\n args.push('number');\n break;\n case 's':\n args.push('string');\n break;\n }\n }\n result.push(args);\n return result;\n}\n","// Primary result codes.\n// https://www.sqlite.org/rescode.html\nexport const SQLITE_OK = 0;\nexport const SQLITE_ERROR = 1;\nexport const SQLITE_INTERNAL = 2;\nexport const SQLITE_PERM = 3;\nexport const SQLITE_ABORT = 4;\nexport const SQLITE_BUSY = 5;\nexport const SQLITE_LOCKED = 6;\nexport const SQLITE_NOMEM = 7;\nexport const SQLITE_READONLY = 8;\nexport const SQLITE_INTERRUPT = 9;\nexport const SQLITE_IOERR = 10;\nexport const SQLITE_CORRUPT = 11;\nexport const SQLITE_NOTFOUND = 12;\nexport const SQLITE_FULL = 13;\nexport const SQLITE_CANTOPEN = 14;\nexport const SQLITE_PROTOCOL = 15;\nexport const SQLITE_EMPTY = 16;\nexport const SQLITE_SCHEMA = 17;\nexport const SQLITE_TOOBIG = 18;\nexport const SQLITE_CONSTRAINT = 19;\nexport const SQLITE_MISMATCH = 20;\nexport const SQLITE_MISUSE = 21;\nexport const SQLITE_NOLFS = 22;\nexport const SQLITE_AUTH = 23;\nexport const SQLITE_FORMAT = 24;\nexport const SQLITE_RANGE = 25;\nexport const SQLITE_NOTADB = 26;\nexport const SQLITE_NOTICE = 27;\nexport const SQLITE_WARNING = 28;\nexport const SQLITE_ROW = 100;\nexport const SQLITE_DONE = 101;\n\n// Extended error codes.\nexport const SQLITE_IOERR_ACCESS = 3338;\nexport const SQLITE_IOERR_CHECKRESERVEDLOCK = 3594;\nexport const SQLITE_IOERR_CLOSE = 4106;\nexport const SQLITE_IOERR_DATA = 8202;\nexport const SQLITE_IOERR_DELETE = 2570;\nexport const SQLITE_IOERR_DELETE_NOENT = 5898;\nexport const SQLITE_IOERR_DIR_FSYNC = 1290;\nexport const SQLITE_IOERR_FSTAT = 1802;\nexport const SQLITE_IOERR_FSYNC = 1034;\nexport const SQLITE_IOERR_GETTEMPPATH = 6410;\nexport const SQLITE_IOERR_LOCK = 3850;\nexport const SQLITE_IOERR_NOMEM = 3082;\nexport const SQLITE_IOERR_READ = 266;\nexport const SQLITE_IOERR_RDLOCK = 2314;\nexport const SQLITE_IOERR_SEEK = 5642;\nexport const SQLITE_IOERR_SHORT_READ = 522;\nexport const SQLITE_IOERR_TRUNCATE = 1546;\nexport const SQLITE_IOERR_UNLOCK = 2058;\nexport const SQLITE_IOERR_VNODE = 6922;\nexport const SQLITE_IOERR_WRITE = 778;\nexport const SQLITE_IOERR_BEGIN_ATOMIC = 7434;\nexport const SQLITE_IOERR_COMMIT_ATOMIC = 7690;\nexport const SQLITE_IOERR_ROLLBACK_ATOMIC = 7946;\n\n// Other extended result codes.\nexport const SQLITE_CONSTRAINT_CHECK = 275;\nexport const SQLITE_CONSTRAINT_COMMITHOOK = 531;\nexport const SQLITE_CONSTRAINT_FOREIGNKEY = 787;\nexport const SQLITE_CONSTRAINT_FUNCTION = 1043;\nexport const SQLITE_CONSTRAINT_NOTNULL = 1299;\nexport const SQLITE_CONSTRAINT_PINNED = 2835;\nexport const SQLITE_CONSTRAINT_PRIMARYKEY = 1555;\nexport const SQLITE_CONSTRAINT_ROWID = 2579;\nexport const SQLITE_CONSTRAINT_TRIGGER = 1811;\nexport const SQLITE_CONSTRAINT_UNIQUE = 2067;\nexport const SQLITE_CONSTRAINT_VTAB = 2323;\n\n// Open flags.\n// https://www.sqlite.org/c3ref/c_open_autoproxy.html\nexport const SQLITE_OPEN_READONLY = 0x00000001;\nexport const SQLITE_OPEN_READWRITE = 0x00000002;\nexport const SQLITE_OPEN_CREATE = 0x00000004;\nexport const SQLITE_OPEN_DELETEONCLOSE = 0x00000008;\nexport const SQLITE_OPEN_EXCLUSIVE = 0x00000010;\nexport const SQLITE_OPEN_AUTOPROXY = 0x00000020;\nexport const SQLITE_OPEN_URI = 0x00000040;\nexport const SQLITE_OPEN_MEMORY = 0x00000080;\nexport const SQLITE_OPEN_MAIN_DB = 0x00000100;\nexport const SQLITE_OPEN_TEMP_DB = 0x00000200;\nexport const SQLITE_OPEN_TRANSIENT_DB = 0x00000400;\nexport const SQLITE_OPEN_MAIN_JOURNAL = 0x00000800;\nexport const SQLITE_OPEN_TEMP_JOURNAL = 0x00001000;\nexport const SQLITE_OPEN_SUBJOURNAL = 0x00002000;\nexport const SQLITE_OPEN_SUPER_JOURNAL = 0x00004000;\nexport const SQLITE_OPEN_NOMUTEX = 0x00008000;\nexport const SQLITE_OPEN_FULLMUTEX = 0x00010000;\nexport const SQLITE_OPEN_SHAREDCACHE = 0x00020000;\nexport const SQLITE_OPEN_PRIVATECACHE = 0x00040000;\nexport const SQLITE_OPEN_WAL = 0x00080000;\nexport const SQLITE_OPEN_NOFOLLOW = 0x01000000;\n\n// Locking levels.\n// https://www.sqlite.org/c3ref/c_lock_exclusive.html\nexport const SQLITE_LOCK_NONE = 0;\nexport const SQLITE_LOCK_SHARED = 1;\nexport const SQLITE_LOCK_RESERVED = 2;\nexport const SQLITE_LOCK_PENDING = 3;\nexport const SQLITE_LOCK_EXCLUSIVE = 4;\n\n// Device characteristics.\n// https://www.sqlite.org/c3ref/c_iocap_atomic.html\nexport const SQLITE_IOCAP_ATOMIC = 0x00000001;\nexport const SQLITE_IOCAP_ATOMIC512 = 0x00000002;\nexport const SQLITE_IOCAP_ATOMIC1K = 0x00000004;\nexport const SQLITE_IOCAP_ATOMIC2K = 0x00000008;\nexport const SQLITE_IOCAP_ATOMIC4K = 0x00000010;\nexport const SQLITE_IOCAP_ATOMIC8K = 0x00000020;\nexport const SQLITE_IOCAP_ATOMIC16K = 0x00000040;\nexport const SQLITE_IOCAP_ATOMIC32K = 0x00000080;\nexport const SQLITE_IOCAP_ATOMIC64K = 0x00000100;\nexport const SQLITE_IOCAP_SAFE_APPEND = 0x00000200;\nexport const SQLITE_IOCAP_SEQUENTIAL = 0x00000400;\nexport const SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN = 0x00000800;\nexport const SQLITE_IOCAP_POWERSAFE_OVERWRITE = 0x00001000;\nexport const SQLITE_IOCAP_IMMUTABLE = 0x00002000;\nexport const SQLITE_IOCAP_BATCH_ATOMIC = 0x00004000;\n\n// xAccess flags.\n// https://www.sqlite.org/c3ref/c_access_exists.html\nexport const SQLITE_ACCESS_EXISTS = 0;\nexport const SQLITE_ACCESS_READWRITE = 1;\nexport const SQLITE_ACCESS_READ = 2;\n\n// File control opcodes\n// https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlbeginatomicwrite\nexport const SQLITE_FCNTL_LOCKSTATE = 1; \nexport const SQLITE_FCNTL_GET_LOCKPROXYFILE = 2; \nexport const SQLITE_FCNTL_SET_LOCKPROXYFILE = 3; \nexport const SQLITE_FCNTL_LAST_ERRNO = 4; \nexport const SQLITE_FCNTL_SIZE_HINT = 5; \nexport const SQLITE_FCNTL_CHUNK_SIZE = 6; \nexport const SQLITE_FCNTL_FILE_POINTER = 7; \nexport const SQLITE_FCNTL_SYNC_OMITTED = 8; \nexport const SQLITE_FCNTL_WIN32_AV_RETRY = 9; \nexport const SQLITE_FCNTL_PERSIST_WAL = 10; \nexport const SQLITE_FCNTL_OVERWRITE = 11; \nexport const SQLITE_FCNTL_VFSNAME = 12; \nexport const SQLITE_FCNTL_POWERSAFE_OVERWRITE = 13; \nexport const SQLITE_FCNTL_PRAGMA = 14; \nexport const SQLITE_FCNTL_BUSYHANDLER = 15; \nexport const SQLITE_FCNTL_TEMPFILENAME = 16; \nexport const SQLITE_FCNTL_MMAP_SIZE = 18; \nexport const SQLITE_FCNTL_TRACE = 19; \nexport const SQLITE_FCNTL_HAS_MOVED = 20; \nexport const SQLITE_FCNTL_SYNC = 21; \nexport const SQLITE_FCNTL_COMMIT_PHASETWO = 22; \nexport const SQLITE_FCNTL_WIN32_SET_HANDLE = 23; \nexport const SQLITE_FCNTL_WAL_BLOCK = 24; \nexport const SQLITE_FCNTL_ZIPVFS = 25; \nexport const SQLITE_FCNTL_RBU = 26; \nexport const SQLITE_FCNTL_VFS_POINTER = 27; \nexport const SQLITE_FCNTL_JOURNAL_POINTER = 28; \nexport const SQLITE_FCNTL_WIN32_GET_HANDLE = 29; \nexport const SQLITE_FCNTL_PDB = 30; \nexport const SQLITE_FCNTL_BEGIN_ATOMIC_WRITE = 31; \nexport const SQLITE_FCNTL_COMMIT_ATOMIC_WRITE = 32; \nexport const SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE = 33; \nexport const SQLITE_FCNTL_LOCK_TIMEOUT = 34; \nexport const SQLITE_FCNTL_DATA_VERSION = 35; \nexport const SQLITE_FCNTL_SIZE_LIMIT = 36; \nexport const SQLITE_FCNTL_CKPT_DONE = 37; \nexport const SQLITE_FCNTL_RESERVE_BYTES = 38; \nexport const SQLITE_FCNTL_CKPT_START = 39;\n\n// Fundamental datatypes.\n// https://www.sqlite.org/c3ref/c_blob.html\nexport const SQLITE_INTEGER = 1;\nexport const SQLITE_FLOAT = 2;\nexport const SQLITE_TEXT = 3;\nexport const SQLITE_BLOB = 4;\nexport const SQLITE_NULL = 5;\n\n// Special destructor behavior.\n// https://www.sqlite.org/c3ref/c_static.html\nexport const SQLITE_STATIC = 0;\nexport const SQLITE_TRANSIENT = -1;\n\n// Text encodings.\n// https://sqlite.org/c3ref/c_any.html\nexport const SQLITE_UTF8 = 1; /* IMP: R-37514-35566 */\nexport const SQLITE_UTF16LE = 2; /* IMP: R-03371-37637 */\nexport const SQLITE_UTF16BE = 3; /* IMP: R-51971-34154 */\nexport const SQLITE_UTF16 = 4; /* Use native byte order */\n\n// Module constraint ops.\nexport const SQLITE_INDEX_CONSTRAINT_EQ = 2;\nexport const SQLITE_INDEX_CONSTRAINT_GT = 4;\nexport const SQLITE_INDEX_CONSTRAINT_LE = 8;\nexport const SQLITE_INDEX_CONSTRAINT_LT = 16;\nexport const SQLITE_INDEX_CONSTRAINT_GE = 32;\nexport const SQLITE_INDEX_CONSTRAINT_MATCH = 64;\nexport const SQLITE_INDEX_CONSTRAINT_LIKE = 65;\nexport const SQLITE_INDEX_CONSTRAINT_GLOB = 66;\nexport const SQLITE_INDEX_CONSTRAINT_REGEXP = 67;\nexport const SQLITE_INDEX_CONSTRAINT_NE = 68;\nexport const SQLITE_INDEX_CONSTRAINT_ISNOT = 69;\nexport const SQLITE_INDEX_CONSTRAINT_ISNOTNULL = 70;\nexport const SQLITE_INDEX_CONSTRAINT_ISNULL = 71;\nexport const SQLITE_INDEX_CONSTRAINT_IS = 72;\nexport const SQLITE_INDEX_CONSTRAINT_FUNCTION = 150;\nexport const SQLITE_INDEX_SCAN_UNIQUE = 1; /* Scan visits at most = 1 row */\n\n// Function flags\nexport const SQLITE_DETERMINISTIC = 0x000000800;\nexport const SQLITE_DIRECTONLY = 0x000080000;\nexport const SQLITE_SUBTYPE = 0x000100000;\nexport const SQLITE_INNOCUOUS = 0x000200000;\n\n// Sync flags\nexport const SQLITE_SYNC_NORMAL = 0x00002;\nexport const SQLITE_SYNC_FULL = 0x00003;\nexport const SQLITE_SYNC_DATAONLY = 0x00010;\n\n// Authorizer action codes\nexport const SQLITE_CREATE_INDEX = 1;\nexport const SQLITE_CREATE_TABLE = 2;\nexport const SQLITE_CREATE_TEMP_INDEX = 3;\nexport const SQLITE_CREATE_TEMP_TABLE = 4;\nexport const SQLITE_CREATE_TEMP_TRIGGER = 5;\nexport const SQLITE_CREATE_TEMP_VIEW = 6;\nexport const SQLITE_CREATE_TRIGGER = 7;\nexport const SQLITE_CREATE_VIEW = 8;\nexport const SQLITE_DELETE = 9;\nexport const SQLITE_DROP_INDEX = 10;\nexport const SQLITE_DROP_TABLE = 11;\nexport const SQLITE_DROP_TEMP_INDEX = 12;\nexport const SQLITE_DROP_TEMP_TABLE = 13;\nexport const SQLITE_DROP_TEMP_TRIGGER = 14;\nexport const SQLITE_DROP_TEMP_VIEW = 15;\nexport const SQLITE_DROP_TRIGGER = 16;\nexport const SQLITE_DROP_VIEW = 17;\nexport const SQLITE_INSERT = 18;\nexport const SQLITE_PRAGMA = 19;\nexport const SQLITE_READ = 20;\nexport const SQLITE_SELECT = 21;\nexport const SQLITE_TRANSACTION = 22;\nexport const SQLITE_UPDATE = 23;\nexport const SQLITE_ATTACH = 24;\nexport const SQLITE_DETACH = 25;\nexport const SQLITE_ALTER_TABLE = 26;\nexport const SQLITE_REINDEX = 27;\nexport const SQLITE_ANALYZE = 28;\nexport const SQLITE_CREATE_VTABLE = 29;\nexport const SQLITE_DROP_VTABLE = 30;\nexport const SQLITE_FUNCTION = 31;\nexport const SQLITE_SAVEPOINT = 32;\nexport const SQLITE_COPY = 0;\nexport const SQLITE_RECURSIVE = 33;\n\n// Authorizer return codes\nexport const SQLITE_DENY = 1;\nexport const SQLITE_IGNORE = 2;\n\n// Limit categories\nexport const SQLITE_LIMIT_LENGTH = 0;\nexport const SQLITE_LIMIT_SQL_LENGTH = 1;\nexport const SQLITE_LIMIT_COLUMN = 2;\nexport const SQLITE_LIMIT_EXPR_DEPTH = 3;\nexport const SQLITE_LIMIT_COMPOUND_SELECT = 4;\nexport const SQLITE_LIMIT_VDBE_OP = 5;\nexport const SQLITE_LIMIT_FUNCTION_ARG = 6;\nexport const SQLITE_LIMIT_ATTACHED = 7;\nexport const SQLITE_LIMIT_LIKE_PATTERN_LENGTH = 8;\nexport const SQLITE_LIMIT_VARIABLE_NUMBER = 9;\nexport const SQLITE_LIMIT_TRIGGER_DEPTH = 10;\nexport const SQLITE_LIMIT_WORKER_THREADS = 11;\n\nexport const SQLITE_PREPARE_PERSISTENT = 0x01;\nexport const SQLITE_PREPARE_NORMALIZED = 0x02;\nexport const SQLITE_PREPARE_NO_VTAB = 0x04;","const E_TIMEOUT = new Error('timeout while waiting for mutex to become available');\nconst E_ALREADY_LOCKED = new Error('mutex already locked');\nconst E_CANCELED = new Error('request for lock canceled');\n\nvar __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Semaphore {\n constructor(_value, _cancelError = E_CANCELED) {\n this._value = _value;\n this._cancelError = _cancelError;\n this._queue = [];\n this._weightedWaiters = [];\n }\n acquire(weight = 1, priority = 0) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n return new Promise((resolve, reject) => {\n const task = { resolve, reject, weight, priority };\n const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority);\n if (i === -1 && weight <= this._value) {\n // Needs immediate dispatch, skip the queue\n this._dispatchItem(task);\n }\n else {\n this._queue.splice(i + 1, 0, task);\n }\n });\n }\n runExclusive(callback_1) {\n return __awaiter$2(this, arguments, void 0, function* (callback, weight = 1, priority = 0) {\n const [value, release] = yield this.acquire(weight, priority);\n try {\n return yield callback(value);\n }\n finally {\n release();\n }\n });\n }\n waitForUnlock(weight = 1, priority = 0) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n if (this._couldLockImmediately(weight, priority)) {\n return Promise.resolve();\n }\n else {\n return new Promise((resolve) => {\n if (!this._weightedWaiters[weight - 1])\n this._weightedWaiters[weight - 1] = [];\n insertSorted(this._weightedWaiters[weight - 1], { resolve, priority });\n });\n }\n }\n isLocked() {\n return this._value <= 0;\n }\n getValue() {\n return this._value;\n }\n setValue(value) {\n this._value = value;\n this._dispatchQueue();\n }\n release(weight = 1) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n this._value += weight;\n this._dispatchQueue();\n }\n cancel() {\n this._queue.forEach((entry) => entry.reject(this._cancelError));\n this._queue = [];\n }\n _dispatchQueue() {\n this._drainUnlockWaiters();\n while (this._queue.length > 0 && this._queue[0].weight <= this._value) {\n this._dispatchItem(this._queue.shift());\n this._drainUnlockWaiters();\n }\n }\n _dispatchItem(item) {\n const previousValue = this._value;\n this._value -= item.weight;\n item.resolve([previousValue, this._newReleaser(item.weight)]);\n }\n _newReleaser(weight) {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n this.release(weight);\n };\n }\n _drainUnlockWaiters() {\n if (this._queue.length === 0) {\n for (let weight = this._value; weight > 0; weight--) {\n const waiters = this._weightedWaiters[weight - 1];\n if (!waiters)\n continue;\n waiters.forEach((waiter) => waiter.resolve());\n this._weightedWaiters[weight - 1] = [];\n }\n }\n else {\n const queuedPriority = this._queue[0].priority;\n for (let weight = this._value; weight > 0; weight--) {\n const waiters = this._weightedWaiters[weight - 1];\n if (!waiters)\n continue;\n const i = waiters.findIndex((waiter) => waiter.priority <= queuedPriority);\n (i === -1 ? waiters : waiters.splice(0, i))\n .forEach((waiter => waiter.resolve()));\n }\n }\n }\n _couldLockImmediately(weight, priority) {\n return (this._queue.length === 0 || this._queue[0].priority < priority) &&\n weight <= this._value;\n }\n}\nfunction insertSorted(a, v) {\n const i = findIndexFromEnd(a, (other) => v.priority <= other.priority);\n a.splice(i + 1, 0, v);\n}\nfunction findIndexFromEnd(a, predicate) {\n for (let i = a.length - 1; i >= 0; i--) {\n if (predicate(a[i])) {\n return i;\n }\n }\n return -1;\n}\n\nvar __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Mutex {\n constructor(cancelError) {\n this._semaphore = new Semaphore(1, cancelError);\n }\n acquire() {\n return __awaiter$1(this, arguments, void 0, function* (priority = 0) {\n const [, releaser] = yield this._semaphore.acquire(1, priority);\n return releaser;\n });\n }\n runExclusive(callback, priority = 0) {\n return this._semaphore.runExclusive(() => callback(), 1, priority);\n }\n isLocked() {\n return this._semaphore.isLocked();\n }\n waitForUnlock(priority = 0) {\n return this._semaphore.waitForUnlock(1, priority);\n }\n release() {\n if (this._semaphore.isLocked())\n this._semaphore.release();\n }\n cancel() {\n return this._semaphore.cancel();\n }\n}\n\nvar __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nfunction withTimeout(sync, timeout, timeoutError = E_TIMEOUT) {\n return {\n acquire: (weightOrPriority, priority) => {\n let weight;\n if (isSemaphore(sync)) {\n weight = weightOrPriority;\n }\n else {\n weight = undefined;\n priority = weightOrPriority;\n }\n if (weight !== undefined && weight <= 0) {\n throw new Error(`invalid weight ${weight}: must be positive`);\n }\n return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n let isTimeout = false;\n const handle = setTimeout(() => {\n isTimeout = true;\n reject(timeoutError);\n }, timeout);\n try {\n const ticket = yield (isSemaphore(sync)\n ? sync.acquire(weight, priority)\n : sync.acquire(priority));\n if (isTimeout) {\n const release = Array.isArray(ticket) ? ticket[1] : ticket;\n release();\n }\n else {\n clearTimeout(handle);\n resolve(ticket);\n }\n }\n catch (e) {\n if (!isTimeout) {\n clearTimeout(handle);\n reject(e);\n }\n }\n }));\n },\n runExclusive(callback, weight, priority) {\n return __awaiter(this, void 0, void 0, function* () {\n let release = () => undefined;\n try {\n const ticket = yield this.acquire(weight, priority);\n if (Array.isArray(ticket)) {\n release = ticket[1];\n return yield callback(ticket[0]);\n }\n else {\n release = ticket;\n return yield callback();\n }\n }\n finally {\n release();\n }\n });\n },\n release(weight) {\n sync.release(weight);\n },\n cancel() {\n return sync.cancel();\n },\n waitForUnlock: (weightOrPriority, priority) => {\n let weight;\n if (isSemaphore(sync)) {\n weight = weightOrPriority;\n }\n else {\n weight = undefined;\n priority = weightOrPriority;\n }\n if (weight !== undefined && weight <= 0) {\n throw new Error(`invalid weight ${weight}: must be positive`);\n }\n return new Promise((resolve, reject) => {\n const handle = setTimeout(() => reject(timeoutError), timeout);\n (isSemaphore(sync)\n ? sync.waitForUnlock(weight, priority)\n : sync.waitForUnlock(priority)).then(() => {\n clearTimeout(handle);\n resolve();\n });\n });\n },\n isLocked: () => sync.isLocked(),\n getValue: () => sync.getValue(),\n setValue: (value) => sync.setValue(value),\n };\n}\nfunction isSemaphore(sync) {\n return sync.getValue !== undefined;\n}\n\n// eslint-disable-next-lisne @typescript-eslint/explicit-module-boundary-types\nfunction tryAcquire(sync, alreadyAcquiredError = E_ALREADY_LOCKED) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return withTimeout(sync, 0, alreadyAcquiredError);\n}\n\nexport { E_ALREADY_LOCKED, E_CANCELED, E_TIMEOUT, Mutex, Semaphore, tryAcquire, withTimeout };\n","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nconst proxyMarker = Symbol(\"Comlink.proxy\");\nconst createEndpoint = Symbol(\"Comlink.endpoint\");\nconst releaseProxy = Symbol(\"Comlink.releaseProxy\");\nconst finalizer = Symbol(\"Comlink.finalizer\");\nconst throwMarker = Symbol(\"Comlink.thrown\");\nconst isObject = (val) => (typeof val === \"object\" && val !== null) || typeof val === \"function\";\n/**\n * Internal transfer handle to handle objects marked to proxy.\n */\nconst proxyTransferHandler = {\n canHandle: (val) => isObject(val) && val[proxyMarker],\n serialize(obj) {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port1);\n return [port2, [port2]];\n },\n deserialize(port) {\n port.start();\n return wrap(port);\n },\n};\n/**\n * Internal transfer handler to handle thrown exceptions.\n */\nconst throwTransferHandler = {\n canHandle: (value) => isObject(value) && throwMarker in value,\n serialize({ value }) {\n let serialized;\n if (value instanceof Error) {\n serialized = {\n isError: true,\n value: {\n message: value.message,\n name: value.name,\n stack: value.stack,\n },\n };\n }\n else {\n serialized = { isError: false, value };\n }\n return [serialized, []];\n },\n deserialize(serialized) {\n if (serialized.isError) {\n throw Object.assign(new Error(serialized.value.message), serialized.value);\n }\n throw serialized.value;\n },\n};\n/**\n * Allows customizing the serialization of certain values.\n */\nconst transferHandlers = new Map([\n [\"proxy\", proxyTransferHandler],\n [\"throw\", throwTransferHandler],\n]);\nfunction isAllowedOrigin(allowedOrigins, origin) {\n for (const allowedOrigin of allowedOrigins) {\n if (origin === allowedOrigin || allowedOrigin === \"*\") {\n return true;\n }\n if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {\n return true;\n }\n }\n return false;\n}\nfunction expose(obj, ep = globalThis, allowedOrigins = [\"*\"]) {\n ep.addEventListener(\"message\", function callback(ev) {\n if (!ev || !ev.data) {\n return;\n }\n if (!isAllowedOrigin(allowedOrigins, ev.origin)) {\n console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);\n return;\n }\n const { id, type, path } = Object.assign({ path: [] }, ev.data);\n const argumentList = (ev.data.argumentList || []).map(fromWireValue);\n let returnValue;\n try {\n const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);\n const rawValue = path.reduce((obj, prop) => obj[prop], obj);\n switch (type) {\n case \"GET\" /* MessageType.GET */:\n {\n returnValue = rawValue;\n }\n break;\n case \"SET\" /* MessageType.SET */:\n {\n parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);\n returnValue = true;\n }\n break;\n case \"APPLY\" /* MessageType.APPLY */:\n {\n returnValue = rawValue.apply(parent, argumentList);\n }\n break;\n case \"CONSTRUCT\" /* MessageType.CONSTRUCT */:\n {\n const value = new rawValue(...argumentList);\n returnValue = proxy(value);\n }\n break;\n case \"ENDPOINT\" /* MessageType.ENDPOINT */:\n {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port2);\n returnValue = transfer(port1, [port1]);\n }\n break;\n case \"RELEASE\" /* MessageType.RELEASE */:\n {\n returnValue = undefined;\n }\n break;\n default:\n return;\n }\n }\n catch (value) {\n returnValue = { value, [throwMarker]: 0 };\n }\n Promise.resolve(returnValue)\n .catch((value) => {\n return { value, [throwMarker]: 0 };\n })\n .then((returnValue) => {\n const [wireValue, transferables] = toWireValue(returnValue);\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n if (type === \"RELEASE\" /* MessageType.RELEASE */) {\n // detach and deactive after sending release response above.\n ep.removeEventListener(\"message\", callback);\n closeEndPoint(ep);\n if (finalizer in obj && typeof obj[finalizer] === \"function\") {\n obj[finalizer]();\n }\n }\n })\n .catch((error) => {\n // Send Serialization Error To Caller\n const [wireValue, transferables] = toWireValue({\n value: new TypeError(\"Unserializable return value\"),\n [throwMarker]: 0,\n });\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n });\n });\n if (ep.start) {\n ep.start();\n }\n}\nfunction isMessagePort(endpoint) {\n return endpoint.constructor.name === \"MessagePort\";\n}\nfunction closeEndPoint(endpoint) {\n if (isMessagePort(endpoint))\n endpoint.close();\n}\nfunction wrap(ep, target) {\n const pendingListeners = new Map();\n ep.addEventListener(\"message\", function handleMessage(ev) {\n const { data } = ev;\n if (!data || !data.id) {\n return;\n }\n const resolver = pendingListeners.get(data.id);\n if (!resolver) {\n return;\n }\n try {\n resolver(data);\n }\n finally {\n pendingListeners.delete(data.id);\n }\n });\n return createProxy(ep, pendingListeners, [], target);\n}\nfunction throwIfProxyReleased(isReleased) {\n if (isReleased) {\n throw new Error(\"Proxy has been released and is not useable\");\n }\n}\nfunction releaseEndpoint(ep) {\n return requestResponseMessage(ep, new Map(), {\n type: \"RELEASE\" /* MessageType.RELEASE */,\n }).then(() => {\n closeEndPoint(ep);\n });\n}\nconst proxyCounter = new WeakMap();\nconst proxyFinalizers = \"FinalizationRegistry\" in globalThis &&\n new FinalizationRegistry((ep) => {\n const newCount = (proxyCounter.get(ep) || 0) - 1;\n proxyCounter.set(ep, newCount);\n if (newCount === 0) {\n releaseEndpoint(ep);\n }\n });\nfunction registerProxy(proxy, ep) {\n const newCount = (proxyCounter.get(ep) || 0) + 1;\n proxyCounter.set(ep, newCount);\n if (proxyFinalizers) {\n proxyFinalizers.register(proxy, ep, proxy);\n }\n}\nfunction unregisterProxy(proxy) {\n if (proxyFinalizers) {\n proxyFinalizers.unregister(proxy);\n }\n}\nfunction createProxy(ep, pendingListeners, path = [], target = function () { }) {\n let isProxyReleased = false;\n const proxy = new Proxy(target, {\n get(_target, prop) {\n throwIfProxyReleased(isProxyReleased);\n if (prop === releaseProxy) {\n return () => {\n unregisterProxy(proxy);\n releaseEndpoint(ep);\n pendingListeners.clear();\n isProxyReleased = true;\n };\n }\n if (prop === \"then\") {\n if (path.length === 0) {\n return { then: () => proxy };\n }\n const r = requestResponseMessage(ep, pendingListeners, {\n type: \"GET\" /* MessageType.GET */,\n path: path.map((p) => p.toString()),\n }).then(fromWireValue);\n return r.then.bind(r);\n }\n return createProxy(ep, pendingListeners, [...path, prop]);\n },\n set(_target, prop, rawValue) {\n throwIfProxyReleased(isProxyReleased);\n // FIXME: ES6 Proxy Handler `set` methods are supposed to return a\n // boolean. To show good will, we return true asynchronously ¯\\_(ツ)_/¯\n const [value, transferables] = toWireValue(rawValue);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"SET\" /* MessageType.SET */,\n path: [...path, prop].map((p) => p.toString()),\n value,\n }, transferables).then(fromWireValue);\n },\n apply(_target, _thisArg, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const last = path[path.length - 1];\n if (last === createEndpoint) {\n return requestResponseMessage(ep, pendingListeners, {\n type: \"ENDPOINT\" /* MessageType.ENDPOINT */,\n }).then(fromWireValue);\n }\n // We just pretend that `bind()` didn’t happen.\n if (last === \"bind\") {\n return createProxy(ep, pendingListeners, path.slice(0, -1));\n }\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"APPLY\" /* MessageType.APPLY */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n construct(_target, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"CONSTRUCT\" /* MessageType.CONSTRUCT */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n });\n registerProxy(proxy, ep);\n return proxy;\n}\nfunction myFlat(arr) {\n return Array.prototype.concat.apply([], arr);\n}\nfunction processArguments(argumentList) {\n const processed = argumentList.map(toWireValue);\n return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];\n}\nconst transferCache = new WeakMap();\nfunction transfer(obj, transfers) {\n transferCache.set(obj, transfers);\n return obj;\n}\nfunction proxy(obj) {\n return Object.assign(obj, { [proxyMarker]: true });\n}\nfunction windowEndpoint(w, context = globalThis, targetOrigin = \"*\") {\n return {\n postMessage: (msg, transferables) => w.postMessage(msg, targetOrigin, transferables),\n addEventListener: context.addEventListener.bind(context),\n removeEventListener: context.removeEventListener.bind(context),\n };\n}\nfunction toWireValue(value) {\n for (const [name, handler] of transferHandlers) {\n if (handler.canHandle(value)) {\n const [serializedValue, transferables] = handler.serialize(value);\n return [\n {\n type: \"HANDLER\" /* WireValueType.HANDLER */,\n name,\n value: serializedValue,\n },\n transferables,\n ];\n }\n }\n return [\n {\n type: \"RAW\" /* WireValueType.RAW */,\n value,\n },\n transferCache.get(value) || [],\n ];\n}\nfunction fromWireValue(value) {\n switch (value.type) {\n case \"HANDLER\" /* WireValueType.HANDLER */:\n return transferHandlers.get(value.name).deserialize(value.value);\n case \"RAW\" /* WireValueType.RAW */:\n return value.value;\n }\n}\nfunction requestResponseMessage(ep, pendingListeners, msg, transfers) {\n return new Promise((resolve) => {\n const id = generateUUID();\n pendingListeners.set(id, resolve);\n if (ep.start) {\n ep.start();\n }\n ep.postMessage(Object.assign({ id }, msg), transfers);\n });\n}\nfunction generateUUID() {\n return new Array(4)\n .fill(0)\n .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))\n .join(\"-\");\n}\n\nexport { createEndpoint, expose, finalizer, proxy, proxyMarker, releaseProxy, transfer, transferHandlers, windowEndpoint, wrap };\n//# sourceMappingURL=comlink.mjs.map\n","import { Mutex } from 'async-mutex';\n\n// https://www.sqlite.org/lang_expr.html#castexpr\nvar ColumnType;\n(function (ColumnType) {\n ColumnType[\"TEXT\"] = \"TEXT\";\n ColumnType[\"INTEGER\"] = \"INTEGER\";\n ColumnType[\"REAL\"] = \"REAL\";\n})(ColumnType || (ColumnType = {}));\nconst text = {\n type: ColumnType.TEXT\n};\nconst integer = {\n type: ColumnType.INTEGER\n};\nconst real = {\n type: ColumnType.REAL\n};\n// powersync-sqlite-core limits the number of column per table to 1999, due to internal SQLite limits.\n// In earlier versions this was limited to 63.\nconst MAX_AMOUNT_OF_COLUMNS = 1999;\nconst column = {\n text,\n integer,\n real\n};\nclass Column {\n options;\n constructor(options) {\n this.options = options;\n }\n get name() {\n return this.options.name;\n }\n get type() {\n return this.options.type;\n }\n toJSON() {\n return {\n name: this.name,\n type: this.type\n };\n }\n}\n\nconst DEFAULT_INDEX_COLUMN_OPTIONS = {\n ascending: true\n};\nclass IndexedColumn {\n options;\n static createAscending(column) {\n return new IndexedColumn({\n name: column,\n ascending: true\n });\n }\n constructor(options) {\n this.options = { ...DEFAULT_INDEX_COLUMN_OPTIONS, ...options };\n }\n get name() {\n return this.options.name;\n }\n get ascending() {\n return this.options.ascending;\n }\n toJSON(table) {\n return {\n name: this.name,\n ascending: this.ascending,\n type: table.columns.find((column) => column.name === this.name)?.type ?? ColumnType.TEXT\n };\n }\n}\n\nconst DEFAULT_INDEX_OPTIONS = {\n columns: []\n};\nclass Index {\n options;\n static createAscending(options, columnNames) {\n return new Index({\n ...options,\n columns: columnNames.map((name) => IndexedColumn.createAscending(name))\n });\n }\n constructor(options) {\n this.options = options;\n this.options = { ...DEFAULT_INDEX_OPTIONS, ...options };\n }\n get name() {\n return this.options.name;\n }\n get columns() {\n return this.options.columns ?? [];\n }\n toJSON(table) {\n return {\n name: this.name,\n columns: this.columns.map((c) => c.toJSON(table))\n };\n }\n}\n\nconst DEFAULT_TABLE_OPTIONS = {\n indexes: [],\n insertOnly: false,\n localOnly: false,\n trackPrevious: false,\n trackMetadata: false,\n ignoreEmptyUpdates: false\n};\nconst InvalidSQLCharacters = /[\"'%,.#\\s[\\]]/;\nclass Table {\n options;\n _mappedColumns;\n static createLocalOnly(options) {\n return new Table({ ...options, localOnly: true, insertOnly: false });\n }\n static createInsertOnly(options) {\n return new Table({ ...options, localOnly: false, insertOnly: true });\n }\n /**\n * Create a table.\n * @deprecated This was only only included for TableV2 and is no longer necessary.\n * Prefer to use new Table() directly.\n *\n * TODO remove in the next major release.\n */\n static createTable(name, table) {\n return new Table({\n name,\n columns: table.columns,\n indexes: table.indexes,\n localOnly: table.options.localOnly,\n insertOnly: table.options.insertOnly,\n viewName: table.options.viewName\n });\n }\n constructor(optionsOrColumns, v2Options) {\n if (this.isTableV1(optionsOrColumns)) {\n this.initTableV1(optionsOrColumns);\n }\n else {\n this.initTableV2(optionsOrColumns, v2Options);\n }\n }\n copyWithName(name) {\n return new Table({\n ...this.options,\n name\n });\n }\n isTableV1(arg) {\n return 'columns' in arg && Array.isArray(arg.columns);\n }\n initTableV1(options) {\n this.options = {\n ...options,\n indexes: options.indexes || []\n };\n this.applyDefaultOptions();\n }\n initTableV2(columns, options) {\n const convertedColumns = Object.entries(columns).map(([name, columnInfo]) => new Column({ name, type: columnInfo.type }));\n const convertedIndexes = Object.entries(options?.indexes ?? {}).map(([name, columnNames]) => new Index({\n name,\n columns: columnNames.map((name) => new IndexedColumn({\n name: name.replace(/^-/, ''),\n ascending: !name.startsWith('-')\n }))\n }));\n this.options = {\n name: '',\n columns: convertedColumns,\n indexes: convertedIndexes,\n viewName: options?.viewName,\n insertOnly: options?.insertOnly,\n localOnly: options?.localOnly,\n trackPrevious: options?.trackPrevious,\n trackMetadata: options?.trackMetadata,\n ignoreEmptyUpdates: options?.ignoreEmptyUpdates\n };\n this.applyDefaultOptions();\n this._mappedColumns = columns;\n }\n applyDefaultOptions() {\n this.options.insertOnly ??= DEFAULT_TABLE_OPTIONS.insertOnly;\n this.options.localOnly ??= DEFAULT_TABLE_OPTIONS.localOnly;\n this.options.trackPrevious ??= DEFAULT_TABLE_OPTIONS.trackPrevious;\n this.options.trackMetadata ??= DEFAULT_TABLE_OPTIONS.trackMetadata;\n this.options.ignoreEmptyUpdates ??= DEFAULT_TABLE_OPTIONS.ignoreEmptyUpdates;\n }\n get name() {\n return this.options.name;\n }\n get viewNameOverride() {\n return this.options.viewName;\n }\n get viewName() {\n return this.viewNameOverride ?? this.name;\n }\n get columns() {\n return this.options.columns;\n }\n get columnMap() {\n return (this._mappedColumns ??\n this.columns.reduce((hash, column) => {\n hash[column.name] = { type: column.type ?? ColumnType.TEXT };\n return hash;\n }, {}));\n }\n get indexes() {\n return this.options.indexes ?? [];\n }\n get localOnly() {\n return this.options.localOnly;\n }\n get insertOnly() {\n return this.options.insertOnly;\n }\n get trackPrevious() {\n return this.options.trackPrevious;\n }\n get trackMetadata() {\n return this.options.trackMetadata;\n }\n get ignoreEmptyUpdates() {\n return this.options.ignoreEmptyUpdates;\n }\n get internalName() {\n if (this.options.localOnly) {\n return `ps_data_local__${this.name}`;\n }\n return `ps_data__${this.name}`;\n }\n get validName() {\n if (InvalidSQLCharacters.test(this.name)) {\n return false;\n }\n if (this.viewNameOverride != null && InvalidSQLCharacters.test(this.viewNameOverride)) {\n return false;\n }\n return true;\n }\n validate() {\n if (InvalidSQLCharacters.test(this.name)) {\n throw new Error(`Invalid characters in table name: ${this.name}`);\n }\n if (this.viewNameOverride && InvalidSQLCharacters.test(this.viewNameOverride)) {\n throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);\n }\n if (this.columns.length > MAX_AMOUNT_OF_COLUMNS) {\n throw new Error(`Table has too many columns. The maximum number of columns is ${MAX_AMOUNT_OF_COLUMNS}.`);\n }\n if (this.trackMetadata && this.localOnly) {\n throw new Error(`Can't include metadata for local-only tables.`);\n }\n if (this.trackPrevious != false && this.localOnly) {\n throw new Error(`Can't include old values for local-only tables.`);\n }\n const columnNames = new Set();\n columnNames.add('id');\n for (const column of this.columns) {\n const { name: columnName } = column;\n if (column.name === 'id') {\n throw new Error(`An id column is automatically added, custom id columns are not supported`);\n }\n if (columnNames.has(columnName)) {\n throw new Error(`Duplicate column ${columnName}`);\n }\n if (InvalidSQLCharacters.test(columnName)) {\n throw new Error(`Invalid characters in column name: ${column.name}`);\n }\n columnNames.add(columnName);\n }\n const indexNames = new Set();\n for (const index of this.indexes) {\n if (indexNames.has(index.name)) {\n throw new Error(`Duplicate index ${index.name}`);\n }\n if (InvalidSQLCharacters.test(index.name)) {\n throw new Error(`Invalid characters in index name: ${index.name}`);\n }\n for (const column of index.columns) {\n if (!columnNames.has(column.name)) {\n throw new Error(`Column ${column.name} not found for index ${index.name}`);\n }\n }\n indexNames.add(index.name);\n }\n }\n toJSON() {\n const trackPrevious = this.trackPrevious;\n return {\n name: this.name,\n view_name: this.viewName,\n local_only: this.localOnly,\n insert_only: this.insertOnly,\n include_old: trackPrevious && (trackPrevious.columns ?? true),\n include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,\n include_metadata: this.trackMetadata,\n ignore_empty_update: this.ignoreEmptyUpdates,\n columns: this.columns.map((c) => c.toJSON()),\n indexes: this.indexes.map((e) => e.toJSON(this))\n };\n }\n}\n\nconst ATTACHMENT_TABLE = 'attachments';\n/**\n * Maps a database row to an AttachmentRecord.\n *\n * @param row - The database row object\n * @returns The corresponding AttachmentRecord\n *\n * @experimental\n */\nfunction attachmentFromSql(row) {\n return {\n id: row.id,\n filename: row.filename,\n localUri: row.local_uri,\n size: row.size,\n mediaType: row.media_type,\n timestamp: row.timestamp,\n metaData: row.meta_data,\n hasSynced: row.has_synced === 1,\n state: row.state\n };\n}\n/**\n * AttachmentState represents the current synchronization state of an attachment.\n *\n * @experimental\n */\nvar AttachmentState;\n(function (AttachmentState) {\n AttachmentState[AttachmentState[\"QUEUED_UPLOAD\"] = 0] = \"QUEUED_UPLOAD\";\n AttachmentState[AttachmentState[\"QUEUED_DOWNLOAD\"] = 1] = \"QUEUED_DOWNLOAD\";\n AttachmentState[AttachmentState[\"QUEUED_DELETE\"] = 2] = \"QUEUED_DELETE\";\n AttachmentState[AttachmentState[\"SYNCED\"] = 3] = \"SYNCED\";\n AttachmentState[AttachmentState[\"ARCHIVED\"] = 4] = \"ARCHIVED\"; // Attachment has been orphaned, i.e. the associated record has been deleted\n})(AttachmentState || (AttachmentState = {}));\n/**\n * AttachmentTable defines the schema for the attachment queue table.\n *\n * @internal\n */\nclass AttachmentTable extends Table {\n constructor(options) {\n super({\n filename: column.text,\n local_uri: column.text,\n timestamp: column.integer,\n size: column.integer,\n media_type: column.text,\n state: column.integer, // Corresponds to AttachmentState\n has_synced: column.integer,\n meta_data: column.text\n }, {\n ...options,\n viewName: options?.viewName ?? ATTACHMENT_TABLE,\n localOnly: true,\n insertOnly: false\n });\n }\n}\n\n/**\n * AttachmentContext provides database operations for managing attachment records.\n *\n * Provides methods to query, insert, update, and delete attachment records with\n * proper transaction management through PowerSync.\n *\n * @internal\n */\nclass AttachmentContext {\n /** PowerSync database instance for executing queries */\n db;\n /** Name of the database table storing attachment records */\n tableName;\n /** Logger instance for diagnostic information */\n logger;\n /** Maximum number of archived attachments to keep before cleanup */\n archivedCacheLimit = 100;\n /**\n * Creates a new AttachmentContext instance.\n *\n * @param db - PowerSync database instance\n * @param tableName - Name of the table storing attachment records. Default: 'attachments'\n * @param logger - Logger instance for diagnostic output\n */\n constructor(db, tableName = 'attachments', logger, archivedCacheLimit) {\n this.db = db;\n this.tableName = tableName;\n this.logger = logger;\n this.archivedCacheLimit = archivedCacheLimit;\n }\n /**\n * Retrieves all active attachments that require synchronization.\n * Active attachments include those queued for upload, download, or delete.\n * Results are ordered by timestamp in ascending order.\n *\n * @returns Promise resolving to an array of active attachment records\n */\n async getActiveAttachments() {\n const attachments = await this.db.getAll(\n /* sql */\n `\n SELECT\n *\n FROM\n ${this.tableName}\n WHERE\n state = ?\n OR state = ?\n OR state = ?\n ORDER BY\n timestamp ASC\n `, [AttachmentState.QUEUED_UPLOAD, AttachmentState.QUEUED_DOWNLOAD, AttachmentState.QUEUED_DELETE]);\n return attachments.map(attachmentFromSql);\n }\n /**\n * Retrieves all archived attachments.\n *\n * Archived attachments are no longer referenced but haven't been permanently deleted.\n * These are candidates for cleanup operations to free up storage space.\n *\n * @returns Promise resolving to an array of archived attachment records\n */\n async getArchivedAttachments() {\n const attachments = await this.db.getAll(\n /* sql */\n `\n SELECT\n *\n FROM\n ${this.tableName}\n WHERE\n state = ?\n ORDER BY\n timestamp ASC\n `, [AttachmentState.ARCHIVED]);\n return attachments.map(attachmentFromSql);\n }\n /**\n * Retrieves all attachment records regardless of state.\n * Results are ordered by timestamp in ascending order.\n *\n * @returns Promise resolving to an array of all attachment records\n */\n async getAttachments() {\n const attachments = await this.db.getAll(\n /* sql */\n `\n SELECT\n *\n FROM\n ${this.tableName}\n ORDER BY\n timestamp ASC\n `, []);\n return attachments.map(attachmentFromSql);\n }\n /**\n * Inserts or updates an attachment record within an existing transaction.\n *\n * Performs an upsert operation (INSERT OR REPLACE). Must be called within\n * an active database transaction context.\n *\n * @param attachment - The attachment record to upsert\n * @param context - Active database transaction context\n */\n async upsertAttachment(attachment, context) {\n await context.execute(\n /* sql */\n `\n INSERT\n OR REPLACE INTO ${this.tableName} (\n id,\n filename,\n local_uri,\n size,\n media_type,\n timestamp,\n state,\n has_synced,\n meta_data\n )\n VALUES\n (?, ?, ?, ?, ?, ?, ?, ?, ?)\n `, [\n attachment.id,\n attachment.filename,\n attachment.localUri || null,\n attachment.size || null,\n attachment.mediaType || null,\n attachment.timestamp,\n attachment.state,\n attachment.hasSynced ? 1 : 0,\n attachment.metaData || null\n ]);\n }\n async getAttachment(id) {\n const attachment = await this.db.get(\n /* sql */\n `\n SELECT\n *\n FROM\n ${this.tableName}\n WHERE\n id = ?\n `, [id]);\n return attachment ? attachmentFromSql(attachment) : undefined;\n }\n /**\n * Permanently deletes an attachment record from the database.\n *\n * This operation removes the attachment record but does not delete\n * the associated local or remote files. File deletion should be handled\n * separately through the appropriate storage adapters.\n *\n * @param attachmentId - Unique identifier of the attachment to delete\n */\n async deleteAttachment(attachmentId) {\n await this.db.writeTransaction((tx) => tx.execute(\n /* sql */\n `\n DELETE FROM ${this.tableName}\n WHERE\n id = ?\n `, [attachmentId]));\n }\n async clearQueue() {\n await this.db.writeTransaction((tx) => tx.execute(/* sql */ ` DELETE FROM ${this.tableName} `));\n }\n async deleteArchivedAttachments(callback) {\n const limit = 1000;\n const results = await this.db.getAll(\n /* sql */\n `\n SELECT\n *\n FROM\n ${this.tableName}\n WHERE\n state = ?\n ORDER BY\n timestamp DESC\n LIMIT\n ?\n OFFSET\n ?\n `, [AttachmentState.ARCHIVED, limit, this.archivedCacheLimit]);\n const archivedAttachments = results.map(attachmentFromSql);\n if (archivedAttachments.length === 0)\n return false;\n await callback?.(archivedAttachments);\n this.logger.info(`Deleting ${archivedAttachments.length} archived attachments. Archived attachment exceeds cache archiveCacheLimit of ${this.archivedCacheLimit}.`);\n const ids = archivedAttachments.map((attachment) => attachment.id);\n await this.db.execute(\n /* sql */\n `\n DELETE FROM ${this.tableName}\n WHERE\n id IN (\n SELECT\n json_each.value\n FROM\n json_each (?)\n );\n `, [JSON.stringify(ids)]);\n this.logger.info(`Deleted ${archivedAttachments.length} archived attachments`);\n return archivedAttachments.length < limit;\n }\n /**\n * Saves multiple attachment records in a single transaction.\n *\n * All updates are saved in a single batch after processing.\n * If the attachments array is empty, no database operations are performed.\n *\n * @param attachments - Array of attachment records to save\n */\n async saveAttachments(attachments) {\n if (attachments.length === 0) {\n return;\n }\n await this.db.writeTransaction(async (tx) => {\n for (const attachment of attachments) {\n await this.upsertAttachment(attachment, tx);\n }\n });\n }\n}\n\nvar WatchedQueryListenerEvent;\n(function (WatchedQueryListenerEvent) {\n WatchedQueryListenerEvent[\"ON_DATA\"] = \"onData\";\n WatchedQueryListenerEvent[\"ON_ERROR\"] = \"onError\";\n WatchedQueryListenerEvent[\"ON_STATE_CHANGE\"] = \"onStateChange\";\n WatchedQueryListenerEvent[\"SETTINGS_WILL_UPDATE\"] = \"settingsWillUpdate\";\n WatchedQueryListenerEvent[\"CLOSED\"] = \"closed\";\n})(WatchedQueryListenerEvent || (WatchedQueryListenerEvent = {}));\nconst DEFAULT_WATCH_THROTTLE_MS = 30;\nconst DEFAULT_WATCH_QUERY_OPTIONS = {\n throttleMs: DEFAULT_WATCH_THROTTLE_MS,\n reportFetching: true\n};\n\n/**\n * Orchestrates attachment synchronization between local and remote storage.\n * Handles uploads, downloads, deletions, and state transitions.\n *\n * @internal\n */\nclass SyncingService {\n attachmentService;\n localStorage;\n remoteStorage;\n logger;\n errorHandler;\n constructor(attachmentService, localStorage, remoteStorage, logger, errorHandler) {\n this.attachmentService = attachmentService;\n this.localStorage = localStorage;\n this.remoteStorage = remoteStorage;\n this.logger = logger;\n this.errorHandler = errorHandler;\n }\n /**\n * Processes attachments based on their state (upload, download, or delete).\n * All updates are saved in a single batch after processing.\n *\n * @param attachments - Array of attachment records to process\n * @param context - Attachment context for database operations\n * @returns Promise that resolves when all attachments have been processed and saved\n */\n async processAttachments(attachments, context) {\n const updatedAttachments = [];\n for (const attachment of attachments) {\n switch (attachment.state) {\n case AttachmentState.QUEUED_UPLOAD:\n const uploaded = await this.uploadAttachment(attachment);\n updatedAttachments.push(uploaded);\n break;\n case AttachmentState.QUEUED_DOWNLOAD:\n const downloaded = await this.downloadAttachment(attachment);\n updatedAttachments.push(downloaded);\n break;\n case AttachmentState.QUEUED_DELETE:\n const deleted = await this.deleteAttachment(attachment);\n updatedAttachments.push(deleted);\n break;\n }\n }\n await context.saveAttachments(updatedAttachments);\n }\n /**\n * Uploads an attachment from local storage to remote storage.\n * On success, marks as SYNCED. On failure, defers to error handler or archives.\n *\n * @param attachment - The attachment record to upload\n * @returns Updated attachment record with new state\n * @throws Error if the attachment has no localUri\n */\n async uploadAttachment(attachment) {\n this.logger.info(`Uploading attachment ${attachment.filename}`);\n try {\n if (attachment.localUri == null) {\n throw new Error(`No localUri for attachment ${attachment.id}`);\n }\n const fileBlob = await this.localStorage.readFile(attachment.localUri);\n await this.remoteStorage.uploadFile(fileBlob, attachment);\n return {\n ...attachment,\n state: AttachmentState.SYNCED,\n hasSynced: true\n };\n }\n catch (error) {\n const shouldRetry = (await this.errorHandler?.onUploadError(attachment, error)) ?? true;\n if (!shouldRetry) {\n return {\n ...attachment,\n state: AttachmentState.ARCHIVED\n };\n }\n return attachment;\n }\n }\n /**\n * Downloads an attachment from remote storage to local storage.\n * Retrieves the file, converts to base64, and saves locally.\n * On success, marks as SYNCED. On failure, defers to error handler or archives.\n *\n * @param attachment - The attachment record to download\n * @returns Updated attachment record with local URI and new state\n */\n async downloadAttachment(attachment) {\n this.logger.info(`Downloading attachment ${attachment.filename}`);\n try {\n const fileData = await this.remoteStorage.downloadFile(attachment);\n const localUri = this.localStorage.getLocalUri(attachment.filename);\n await this.localStorage.saveFile(localUri, fileData);\n return {\n ...attachment,\n state: AttachmentState.SYNCED,\n localUri: localUri,\n hasSynced: true\n };\n }\n catch (error) {\n const shouldRetry = (await this.errorHandler?.onDownloadError(attachment, error)) ?? true;\n if (!shouldRetry) {\n return {\n ...attachment,\n state: AttachmentState.ARCHIVED\n };\n }\n return attachment;\n }\n }\n /**\n * Deletes an attachment from both remote and local storage.\n * Removes the remote file, local file (if exists), and the attachment record.\n * On failure, defers to error handler or archives.\n *\n * @param attachment - The attachment record to delete\n * @returns Updated attachment record\n */\n async deleteAttachment(attachment) {\n try {\n await this.remoteStorage.deleteFile(attachment);\n if (attachment.localUri) {\n await this.localStorage.deleteFile(attachment.localUri);\n }\n await this.attachmentService.withContext(async (ctx) => {\n await ctx.deleteAttachment(attachment.id);\n });\n return {\n ...attachment,\n state: AttachmentState.ARCHIVED\n };\n }\n catch (error) {\n const shouldRetry = (await this.errorHandler?.onDeleteError(attachment, error)) ?? true;\n if (!shouldRetry) {\n return {\n ...attachment,\n state: AttachmentState.ARCHIVED\n };\n }\n return attachment;\n }\n }\n /**\n * Performs cleanup of archived attachments by removing their local files and records.\n * Errors during local file deletion are logged but do not prevent record deletion.\n */\n async deleteArchivedAttachments(context) {\n return await context.deleteArchivedAttachments(async (archivedAttachments) => {\n for (const attachment of archivedAttachments) {\n if (attachment.localUri) {\n try {\n await this.localStorage.deleteFile(attachment.localUri);\n }\n catch (error) {\n this.logger.error('Error deleting local file for archived attachment', error);\n }\n }\n }\n });\n }\n}\n\n/**\n * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.\n */\nasync function mutexRunExclusive(mutex, callback, options) {\n return new Promise((resolve, reject) => {\n const timeout = options?.timeoutMs;\n let timedOut = false;\n const timeoutId = timeout\n ? setTimeout(() => {\n timedOut = true;\n reject(new Error('Timeout waiting for lock'));\n }, timeout)\n : undefined;\n mutex.runExclusive(async () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n if (timedOut)\n return;\n try {\n resolve(await callback());\n }\n catch (ex) {\n reject(ex);\n }\n });\n });\n}\n\n/**\n * Service for querying and watching attachment records in the database.\n *\n * @internal\n */\nclass AttachmentService {\n db;\n logger;\n tableName;\n mutex = new Mutex();\n context;\n constructor(db, logger, tableName = 'attachments', archivedCacheLimit = 100) {\n this.db = db;\n this.logger = logger;\n this.tableName = tableName;\n this.context = new AttachmentContext(db, tableName, logger, archivedCacheLimit);\n }\n /**\n * Creates a differential watch query for active attachments requiring synchronization.\n * @returns Watch query that emits changes for queued uploads, downloads, and deletes\n */\n watchActiveAttachments({ throttleMs } = {}) {\n this.logger.info('Watching active attachments...');\n const watch = this.db\n .query({\n sql: /* sql */ `\n SELECT\n *\n FROM\n ${this.tableName}\n WHERE\n state = ?\n OR state = ?\n OR state = ?\n ORDER BY\n timestamp ASC\n `,\n parameters: [AttachmentState.QUEUED_UPLOAD, AttachmentState.QUEUED_DOWNLOAD, AttachmentState.QUEUED_DELETE]\n })\n .differentialWatch({ throttleMs });\n return watch;\n }\n /**\n * Executes a callback with exclusive access to the attachment context.\n */\n async withContext(callback) {\n return mutexRunExclusive(this.mutex, async () => {\n return callback(this.context);\n });\n }\n}\n\n/**\n * AttachmentQueue manages the lifecycle and synchronization of attachments\n * between local and remote storage.\n * Provides automatic synchronization, upload/download queuing, attachment monitoring,\n * verification and repair of local files, and cleanup of archived attachments.\n *\n * @experimental\n * @alpha This is currently experimental and may change without a major version bump.\n */\nclass AttachmentQueue {\n /** Timer for periodic synchronization operations */\n periodicSyncTimer;\n /** Service for synchronizing attachments between local and remote storage */\n syncingService;\n /** Adapter for local file storage operations */\n localStorage;\n /** Adapter for remote file storage operations */\n remoteStorage;\n /**\n * Callback function to watch for changes in attachment references in your data model.\n *\n * This should be implemented by the user of AttachmentQueue to monitor changes in your application's\n * data that reference attachments. When attachments are added, removed, or modified,\n * this callback should trigger the onUpdate function with the current set of attachments.\n */\n watchAttachments;\n /** Name of the database table storing attachment records */\n tableName;\n /** Logger instance for diagnostic information */\n logger;\n /** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */\n syncIntervalMs = 30 * 1000;\n /** Duration in milliseconds to throttle sync operations */\n syncThrottleDuration;\n /** Whether to automatically download remote attachments. Default: true */\n downloadAttachments = true;\n /** Maximum number of archived attachments to keep before cleanup. Default: 100 */\n archivedCacheLimit;\n /** Service for managing attachment-related database operations */\n attachmentService;\n /** PowerSync database instance */\n db;\n /** Cleanup function for status change listener */\n statusListenerDispose;\n watchActiveAttachments;\n watchAttachmentsAbortController;\n /**\n * Creates a new AttachmentQueue instance.\n *\n * @param options - Configuration options\n * @param options.db - PowerSync database instance\n * @param options.remoteStorage - Remote storage adapter for upload/download operations\n * @param options.localStorage - Local storage adapter for file persistence\n * @param options.watchAttachments - Callback for monitoring attachment changes in your data model\n * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'\n * @param options.logger - Logger instance. Defaults to db.logger\n * @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000\n * @param options.syncThrottleDuration - Throttle duration for sync operations in milliseconds. Default: 1000\n * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true\n * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100\n */\n constructor({ db, localStorage, remoteStorage, watchAttachments, logger, tableName = ATTACHMENT_TABLE, syncIntervalMs = 30 * 1000, syncThrottleDuration = DEFAULT_WATCH_THROTTLE_MS, downloadAttachments = true, archivedCacheLimit = 100, errorHandler }) {\n this.db = db;\n this.remoteStorage = remoteStorage;\n this.localStorage = localStorage;\n this.watchAttachments = watchAttachments;\n this.tableName = tableName;\n this.syncIntervalMs = syncIntervalMs;\n this.syncThrottleDuration = syncThrottleDuration;\n this.archivedCacheLimit = archivedCacheLimit;\n this.downloadAttachments = downloadAttachments;\n this.logger = logger ?? db.logger;\n this.attachmentService = new AttachmentService(db, this.logger, tableName, archivedCacheLimit);\n this.syncingService = new SyncingService(this.attachmentService, localStorage, remoteStorage, this.logger, errorHandler);\n }\n /**\n * Generates a new attachment ID using a SQLite UUID function.\n *\n * @returns Promise resolving to the new attachment ID\n */\n async generateAttachmentId() {\n return this.db.get('SELECT uuid() as id').then((row) => row.id);\n }\n /**\n * Starts the attachment synchronization process.\n *\n * This method:\n * - Stops any existing sync operations\n * - Sets up periodic synchronization based on syncIntervalMs\n * - Registers listeners for active attachment changes\n * - Processes watched attachments to queue uploads/downloads\n * - Handles state transitions for archived and new attachments\n */\n async startSync() {\n await this.stopSync();\n this.watchActiveAttachments = this.attachmentService.watchActiveAttachments({\n throttleMs: this.syncThrottleDuration\n });\n // immediately invoke the sync storage to initialize local storage\n await this.localStorage.initialize();\n await this.verifyAttachments();\n // Sync storage periodically\n this.periodicSyncTimer = setInterval(async () => {\n await this.syncStorage();\n }, this.syncIntervalMs);\n // Sync storage when there is a change in active attachments\n this.watchActiveAttachments.registerListener({\n onDiff: async () => {\n await this.syncStorage();\n }\n });\n this.statusListenerDispose = this.db.registerListener({\n statusChanged: (status) => {\n if (status.connected) {\n // Device came online, process attachments immediately\n this.syncStorage().catch((error) => {\n this.logger.error('Error syncing storage on connection:', error);\n });\n }\n }\n });\n this.watchAttachmentsAbortController = new AbortController();\n const signal = this.watchAttachmentsAbortController.signal;\n // Process attachments when there is a change in watched attachments\n this.watchAttachments(async (watchedAttachments) => {\n // Skip processing if sync has been stopped\n if (signal.aborted) {\n return;\n }\n await this.attachmentService.withContext(async (ctx) => {\n // Need to get all the attachments which are tracked in the DB.\n // We might need to restore an archived attachment.\n const currentAttachments = await ctx.getAttachments();\n const attachmentUpdates = [];\n for (const watchedAttachment of watchedAttachments) {\n const existingQueueItem = currentAttachments.find((a) => a.id === watchedAttachment.id);\n if (!existingQueueItem) {\n // Item is watched but not in the queue yet. Need to add it.\n if (!this.downloadAttachments) {\n continue;\n }\n const filename = watchedAttachment.filename ?? `${watchedAttachment.id}.${watchedAttachment.fileExtension}`;\n attachmentUpdates.push({\n id: watchedAttachment.id,\n filename,\n state: AttachmentState.QUEUED_DOWNLOAD,\n hasSynced: false,\n metaData: watchedAttachment.metaData,\n timestamp: new Date().getTime()\n });\n continue;\n }\n if (existingQueueItem.state === AttachmentState.ARCHIVED) {\n // The attachment is present again. Need to queue it for sync.\n // We might be able to optimize this in future\n if (existingQueueItem.hasSynced === true) {\n // No remote action required, we can restore the record (avoids deletion)\n attachmentUpdates.push({\n ...existingQueueItem,\n state: AttachmentState.SYNCED\n });\n }\n else {\n // The localURI should be set if the record was meant to be uploaded\n // and hasSynced is false then\n // it must be an upload operation\n const newState = existingQueueItem.localUri == null ? AttachmentState.QUEUED_DOWNLOAD : AttachmentState.QUEUED_UPLOAD;\n attachmentUpdates.push({\n ...existingQueueItem,\n state: newState\n });\n }\n }\n }\n for (const attachment of currentAttachments) {\n const notInWatchedItems = watchedAttachments.find((i) => i.id === attachment.id) == null;\n if (notInWatchedItems) {\n switch (attachment.state) {\n case AttachmentState.QUEUED_DELETE:\n case AttachmentState.QUEUED_UPLOAD:\n // Only archive if it has synced\n if (attachment.hasSynced === true) {\n attachmentUpdates.push({\n ...attachment,\n state: AttachmentState.ARCHIVED\n });\n }\n break;\n default:\n // Archive other states such as QUEUED_DOWNLOAD\n attachmentUpdates.push({\n ...attachment,\n state: AttachmentState.ARCHIVED\n });\n }\n }\n }\n if (attachmentUpdates.length > 0) {\n await ctx.saveAttachments(attachmentUpdates);\n }\n });\n }, signal);\n }\n /**\n * Synchronizes all active attachments between local and remote storage.\n *\n * This is called automatically at regular intervals when sync is started,\n * but can also be called manually to trigger an immediate sync.\n */\n async syncStorage() {\n await this.attachmentService.withContext(async (ctx) => {\n const activeAttachments = await ctx.getActiveAttachments();\n await this.localStorage.initialize();\n await this.syncingService.processAttachments(activeAttachments, ctx);\n await this.syncingService.deleteArchivedAttachments(ctx);\n });\n }\n /**\n * Stops the attachment synchronization process.\n *\n * Clears the periodic sync timer and closes all active attachment watchers.\n */\n async stopSync() {\n clearInterval(this.periodicSyncTimer);\n this.periodicSyncTimer = undefined;\n if (this.watchActiveAttachments)\n await this.watchActiveAttachments.close();\n if (this.watchAttachmentsAbortController) {\n this.watchAttachmentsAbortController.abort();\n }\n if (this.statusListenerDispose) {\n this.statusListenerDispose();\n this.statusListenerDispose = undefined;\n }\n }\n /**\n * Saves a file to local storage and queues it for upload to remote storage.\n *\n * @param options - File save options\n * @param options.data - The file data as ArrayBuffer, Blob, or base64 string\n * @param options.fileExtension - File extension (e.g., 'jpg', 'pdf')\n * @param options.mediaType - MIME type of the file (e.g., 'image/jpeg')\n * @param options.metaData - Optional metadata to associate with the attachment\n * @param options.id - Optional custom ID. If not provided, a UUID will be generated\n * @param options.updateHook - Optional callback to execute additional database operations\n * within the same transaction as the attachment creation\n * @returns Promise resolving to the created attachment record\n */\n async saveFile({ data, fileExtension, mediaType, metaData, id, updateHook }) {\n const resolvedId = id ?? (await this.generateAttachmentId());\n const filename = `${resolvedId}.${fileExtension}`;\n const localUri = this.localStorage.getLocalUri(filename);\n const size = await this.localStorage.saveFile(localUri, data);\n const attachment = {\n id: resolvedId,\n filename,\n mediaType,\n localUri,\n state: AttachmentState.QUEUED_UPLOAD,\n hasSynced: false,\n size,\n timestamp: new Date().getTime(),\n metaData\n };\n await this.attachmentService.withContext(async (ctx) => {\n await ctx.db.writeTransaction(async (tx) => {\n await updateHook?.(tx, attachment);\n await ctx.upsertAttachment(attachment, tx);\n });\n });\n return attachment;\n }\n async deleteFile({ id, updateHook }) {\n await this.attachmentService.withContext(async (ctx) => {\n const attachment = await ctx.getAttachment(id);\n if (!attachment) {\n throw new Error(`Attachment with id ${id} not found`);\n }\n await ctx.db.writeTransaction(async (tx) => {\n await updateHook?.(tx, attachment);\n await ctx.upsertAttachment({\n ...attachment,\n state: AttachmentState.QUEUED_DELETE,\n hasSynced: false\n }, tx);\n });\n });\n }\n async expireCache() {\n let isDone = false;\n while (!isDone) {\n await this.attachmentService.withContext(async (ctx) => {\n isDone = await this.syncingService.deleteArchivedAttachments(ctx);\n });\n }\n }\n async clearQueue() {\n await this.attachmentService.withContext(async (ctx) => {\n await ctx.clearQueue();\n });\n await this.localStorage.clear();\n }\n /**\n * Verifies the integrity of all attachment records and repairs inconsistencies.\n *\n * This method checks each attachment record against the local filesystem and:\n * - Updates localUri if the file exists at a different path\n * - Archives attachments with missing local files that haven't been uploaded\n * - Requeues synced attachments for download if their local files are missing\n */\n async verifyAttachments() {\n await this.attachmentService.withContext(async (ctx) => {\n const attachments = await ctx.getAttachments();\n const updates = [];\n for (const attachment of attachments) {\n if (attachment.localUri == null) {\n continue;\n }\n const exists = await this.localStorage.fileExists(attachment.localUri);\n if (exists) {\n // The file exists, this is correct\n continue;\n }\n const newLocalUri = this.localStorage.getLocalUri(attachment.filename);\n const newExists = await this.localStorage.fileExists(newLocalUri);\n if (newExists) {\n // The file exists locally but the localUri is broken, we update it.\n updates.push({\n ...attachment,\n localUri: newLocalUri\n });\n }\n else {\n // the file doesn't exist locally.\n if (attachment.state === AttachmentState.SYNCED) {\n // the file has been successfully synced to remote storage but is missing\n // we download it again\n updates.push({\n ...attachment,\n state: AttachmentState.QUEUED_DOWNLOAD,\n localUri: undefined\n });\n }\n else {\n // the file wasn't successfully synced to remote storage, we archive it\n updates.push({\n ...attachment,\n state: AttachmentState.ARCHIVED,\n localUri: undefined // Clears the value\n });\n }\n }\n }\n await ctx.saveAttachments(updates);\n });\n }\n}\n\nvar EncodingType;\n(function (EncodingType) {\n EncodingType[\"UTF8\"] = \"utf8\";\n EncodingType[\"Base64\"] = \"base64\";\n})(EncodingType || (EncodingType = {}));\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar dom = {};\n\nvar eventIterator = {};\n\nvar hasRequiredEventIterator;\n\nfunction requireEventIterator () {\n\tif (hasRequiredEventIterator) return eventIterator;\n\thasRequiredEventIterator = 1;\n\tObject.defineProperty(eventIterator, \"__esModule\", { value: true });\n\tclass EventQueue {\n\t constructor() {\n\t this.pullQueue = [];\n\t this.pushQueue = [];\n\t this.eventHandlers = {};\n\t this.isPaused = false;\n\t this.isStopped = false;\n\t }\n\t push(value) {\n\t if (this.isStopped)\n\t return;\n\t const resolution = { value, done: false };\n\t if (this.pullQueue.length) {\n\t const placeholder = this.pullQueue.shift();\n\t if (placeholder)\n\t placeholder.resolve(resolution);\n\t }\n\t else {\n\t this.pushQueue.push(Promise.resolve(resolution));\n\t if (this.highWaterMark !== undefined &&\n\t this.pushQueue.length >= this.highWaterMark &&\n\t !this.isPaused) {\n\t this.isPaused = true;\n\t if (this.eventHandlers.highWater) {\n\t this.eventHandlers.highWater();\n\t }\n\t else if (console) {\n\t console.warn(`EventIterator queue reached ${this.pushQueue.length} items`);\n\t }\n\t }\n\t }\n\t }\n\t stop() {\n\t if (this.isStopped)\n\t return;\n\t this.isStopped = true;\n\t this.remove();\n\t for (const placeholder of this.pullQueue) {\n\t placeholder.resolve({ value: undefined, done: true });\n\t }\n\t this.pullQueue.length = 0;\n\t }\n\t fail(error) {\n\t if (this.isStopped)\n\t return;\n\t this.isStopped = true;\n\t this.remove();\n\t if (this.pullQueue.length) {\n\t for (const placeholder of this.pullQueue) {\n\t placeholder.reject(error);\n\t }\n\t this.pullQueue.length = 0;\n\t }\n\t else {\n\t const rejection = Promise.reject(error);\n\t /* Attach error handler to avoid leaking an unhandled promise rejection. */\n\t rejection.catch(() => { });\n\t this.pushQueue.push(rejection);\n\t }\n\t }\n\t remove() {\n\t Promise.resolve().then(() => {\n\t if (this.removeCallback)\n\t this.removeCallback();\n\t });\n\t }\n\t [Symbol.asyncIterator]() {\n\t return {\n\t next: (value) => {\n\t const result = this.pushQueue.shift();\n\t if (result) {\n\t if (this.lowWaterMark !== undefined &&\n\t this.pushQueue.length <= this.lowWaterMark &&\n\t this.isPaused) {\n\t this.isPaused = false;\n\t if (this.eventHandlers.lowWater) {\n\t this.eventHandlers.lowWater();\n\t }\n\t }\n\t return result;\n\t }\n\t else if (this.isStopped) {\n\t return Promise.resolve({ value: undefined, done: true });\n\t }\n\t else {\n\t return new Promise((resolve, reject) => {\n\t this.pullQueue.push({ resolve, reject });\n\t });\n\t }\n\t },\n\t return: () => {\n\t this.isStopped = true;\n\t this.pushQueue.length = 0;\n\t this.remove();\n\t return Promise.resolve({ value: undefined, done: true });\n\t },\n\t };\n\t }\n\t}\n\tclass EventIterator {\n\t constructor(listen, { highWaterMark = 100, lowWaterMark = 1 } = {}) {\n\t const queue = new EventQueue();\n\t queue.highWaterMark = highWaterMark;\n\t queue.lowWaterMark = lowWaterMark;\n\t queue.removeCallback =\n\t listen({\n\t push: value => queue.push(value),\n\t stop: () => queue.stop(),\n\t fail: error => queue.fail(error),\n\t on: (event, fn) => {\n\t queue.eventHandlers[event] = fn;\n\t },\n\t }) || (() => { });\n\t this[Symbol.asyncIterator] = () => queue[Symbol.asyncIterator]();\n\t Object.freeze(this);\n\t }\n\t}\n\teventIterator.EventIterator = EventIterator;\n\teventIterator.default = EventIterator;\n\treturn eventIterator;\n}\n\nvar hasRequiredDom;\n\nfunction requireDom () {\n\tif (hasRequiredDom) return dom;\n\thasRequiredDom = 1;\n\tObject.defineProperty(dom, \"__esModule\", { value: true });\n\tconst event_iterator_1 = requireEventIterator();\n\tdom.EventIterator = event_iterator_1.EventIterator;\n\tfunction subscribe(event, options, evOptions) {\n\t return new event_iterator_1.EventIterator(({ push }) => {\n\t this.addEventListener(event, push, options);\n\t return () => this.removeEventListener(event, push, options);\n\t }, evOptions);\n\t}\n\tdom.subscribe = subscribe;\n\tdom.default = event_iterator_1.EventIterator;\n\treturn dom;\n}\n\nvar domExports = requireDom();\n\nvar logger$1 = {exports: {}};\n\n/*!\r\n * js-logger - http://github.com/jonnyreeves/js-logger\r\n * Jonny Reeves, http://jonnyreeves.co.uk/\r\n * js-logger may be freely distributed under the MIT license.\r\n */\nvar logger = logger$1.exports;\n\nvar hasRequiredLogger;\n\nfunction requireLogger () {\n\tif (hasRequiredLogger) return logger$1.exports;\n\thasRequiredLogger = 1;\n\t(function (module) {\n\t\t(function (global) {\r\n\r\n\t\t\t// Top level module for the global, static logger instance.\r\n\t\t\tvar Logger = { };\r\n\r\n\t\t\t// For those that are at home that are keeping score.\r\n\t\t\tLogger.VERSION = \"1.6.1\";\r\n\r\n\t\t\t// Function which handles all incoming log messages.\r\n\t\t\tvar logHandler;\r\n\r\n\t\t\t// Map of ContextualLogger instances by name; used by Logger.get() to return the same named instance.\r\n\t\t\tvar contextualLoggersByNameMap = {};\r\n\r\n\t\t\t// Polyfill for ES5's Function.bind.\r\n\t\t\tvar bind = function(scope, func) {\r\n\t\t\t\treturn function() {\r\n\t\t\t\t\treturn func.apply(scope, arguments);\r\n\t\t\t\t};\r\n\t\t\t};\r\n\r\n\t\t\t// Super exciting object merger-matron 9000 adding another 100 bytes to your download.\r\n\t\t\tvar merge = function () {\r\n\t\t\t\tvar args = arguments, target = args[0], key, i;\r\n\t\t\t\tfor (i = 1; i < args.length; i++) {\r\n\t\t\t\t\tfor (key in args[i]) {\r\n\t\t\t\t\t\tif (!(key in target) && args[i].hasOwnProperty(key)) {\r\n\t\t\t\t\t\t\ttarget[key] = args[i][key];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn target;\r\n\t\t\t};\r\n\r\n\t\t\t// Helper to define a logging level object; helps with optimisation.\r\n\t\t\tvar defineLogLevel = function(value, name) {\r\n\t\t\t\treturn { value: value, name: name };\r\n\t\t\t};\r\n\r\n\t\t\t// Predefined logging levels.\r\n\t\t\tLogger.TRACE = defineLogLevel(1, 'TRACE');\r\n\t\t\tLogger.DEBUG = defineLogLevel(2, 'DEBUG');\r\n\t\t\tLogger.INFO = defineLogLevel(3, 'INFO');\r\n\t\t\tLogger.TIME = defineLogLevel(4, 'TIME');\r\n\t\t\tLogger.WARN = defineLogLevel(5, 'WARN');\r\n\t\t\tLogger.ERROR = defineLogLevel(8, 'ERROR');\r\n\t\t\tLogger.OFF = defineLogLevel(99, 'OFF');\r\n\r\n\t\t\t// Inner class which performs the bulk of the work; ContextualLogger instances can be configured independently\r\n\t\t\t// of each other.\r\n\t\t\tvar ContextualLogger = function(defaultContext) {\r\n\t\t\t\tthis.context = defaultContext;\r\n\t\t\t\tthis.setLevel(defaultContext.filterLevel);\r\n\t\t\t\tthis.log = this.info; // Convenience alias.\r\n\t\t\t};\r\n\r\n\t\t\tContextualLogger.prototype = {\r\n\t\t\t\t// Changes the current logging level for the logging instance.\r\n\t\t\t\tsetLevel: function (newLevel) {\r\n\t\t\t\t\t// Ensure the supplied Level object looks valid.\r\n\t\t\t\t\tif (newLevel && \"value\" in newLevel) {\r\n\t\t\t\t\t\tthis.context.filterLevel = newLevel;\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\t\r\n\t\t\t\t// Gets the current logging level for the logging instance\r\n\t\t\t\tgetLevel: function () {\r\n\t\t\t\t\treturn this.context.filterLevel;\r\n\t\t\t\t},\r\n\r\n\t\t\t\t// Is the logger configured to output messages at the supplied level?\r\n\t\t\t\tenabledFor: function (lvl) {\r\n\t\t\t\t\tvar filterLevel = this.context.filterLevel;\r\n\t\t\t\t\treturn lvl.value >= filterLevel.value;\r\n\t\t\t\t},\r\n\r\n\t\t\t\ttrace: function () {\r\n\t\t\t\t\tthis.invoke(Logger.TRACE, arguments);\r\n\t\t\t\t},\r\n\r\n\t\t\t\tdebug: function () {\r\n\t\t\t\t\tthis.invoke(Logger.DEBUG, arguments);\r\n\t\t\t\t},\r\n\r\n\t\t\t\tinfo: function () {\r\n\t\t\t\t\tthis.invoke(Logger.INFO, arguments);\r\n\t\t\t\t},\r\n\r\n\t\t\t\twarn: function () {\r\n\t\t\t\t\tthis.invoke(Logger.WARN, arguments);\r\n\t\t\t\t},\r\n\r\n\t\t\t\terror: function () {\r\n\t\t\t\t\tthis.invoke(Logger.ERROR, arguments);\r\n\t\t\t\t},\r\n\r\n\t\t\t\ttime: function (label) {\r\n\t\t\t\t\tif (typeof label === 'string' && label.length > 0) {\r\n\t\t\t\t\t\tthis.invoke(Logger.TIME, [ label, 'start' ]);\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\r\n\t\t\t\ttimeEnd: function (label) {\r\n\t\t\t\t\tif (typeof label === 'string' && label.length > 0) {\r\n\t\t\t\t\t\tthis.invoke(Logger.TIME, [ label, 'end' ]);\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\r\n\t\t\t\t// Invokes the logger callback if it's not being filtered.\r\n\t\t\t\tinvoke: function (level, msgArgs) {\r\n\t\t\t\t\tif (logHandler && this.enabledFor(level)) {\r\n\t\t\t\t\t\tlogHandler(msgArgs, merge({ level: level }, this.context));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\r\n\t\t\t// Protected instance which all calls to the to level `Logger` module will be routed through.\r\n\t\t\tvar globalLogger = new ContextualLogger({ filterLevel: Logger.OFF });\r\n\r\n\t\t\t// Configure the global Logger instance.\r\n\t\t\t(function() {\r\n\t\t\t\t// Shortcut for optimisers.\r\n\t\t\t\tvar L = Logger;\r\n\r\n\t\t\t\tL.enabledFor = bind(globalLogger, globalLogger.enabledFor);\r\n\t\t\t\tL.trace = bind(globalLogger, globalLogger.trace);\r\n\t\t\t\tL.debug = bind(globalLogger, globalLogger.debug);\r\n\t\t\t\tL.time = bind(globalLogger, globalLogger.time);\r\n\t\t\t\tL.timeEnd = bind(globalLogger, globalLogger.timeEnd);\r\n\t\t\t\tL.info = bind(globalLogger, globalLogger.info);\r\n\t\t\t\tL.warn = bind(globalLogger, globalLogger.warn);\r\n\t\t\t\tL.error = bind(globalLogger, globalLogger.error);\r\n\r\n\t\t\t\t// Don't forget the convenience alias!\r\n\t\t\t\tL.log = L.info;\r\n\t\t\t}());\r\n\r\n\t\t\t// Set the global logging handler. The supplied function should expect two arguments, the first being an arguments\r\n\t\t\t// object with the supplied log messages and the second being a context object which contains a hash of stateful\r\n\t\t\t// parameters which the logging function can consume.\r\n\t\t\tLogger.setHandler = function (func) {\r\n\t\t\t\tlogHandler = func;\r\n\t\t\t};\r\n\r\n\t\t\t// Sets the global logging filter level which applies to *all* previously registered, and future Logger instances.\r\n\t\t\t// (note that named loggers (retrieved via `Logger.get`) can be configured independently if required).\r\n\t\t\tLogger.setLevel = function(level) {\r\n\t\t\t\t// Set the globalLogger's level.\r\n\t\t\t\tglobalLogger.setLevel(level);\r\n\r\n\t\t\t\t// Apply this level to all registered contextual loggers.\r\n\t\t\t\tfor (var key in contextualLoggersByNameMap) {\r\n\t\t\t\t\tif (contextualLoggersByNameMap.hasOwnProperty(key)) {\r\n\t\t\t\t\t\tcontextualLoggersByNameMap[key].setLevel(level);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\r\n\t\t\t// Gets the global logging filter level\r\n\t\t\tLogger.getLevel = function() {\r\n\t\t\t\treturn globalLogger.getLevel();\r\n\t\t\t};\r\n\r\n\t\t\t// Retrieve a ContextualLogger instance. Note that named loggers automatically inherit the global logger's level,\r\n\t\t\t// default context and log handler.\r\n\t\t\tLogger.get = function (name) {\r\n\t\t\t\t// All logger instances are cached so they can be configured ahead of use.\r\n\t\t\t\treturn contextualLoggersByNameMap[name] ||\r\n\t\t\t\t\t(contextualLoggersByNameMap[name] = new ContextualLogger(merge({ name: name }, globalLogger.context)));\r\n\t\t\t};\r\n\r\n\t\t\t// CreateDefaultHandler returns a handler function which can be passed to `Logger.setHandler()` which will\r\n\t\t\t// write to the window's console object (if present); the optional options object can be used to customise the\r\n\t\t\t// formatter used to format each log message.\r\n\t\t\tLogger.createDefaultHandler = function (options) {\r\n\t\t\t\toptions = options || {};\r\n\r\n\t\t\t\toptions.formatter = options.formatter || function defaultMessageFormatter(messages, context) {\r\n\t\t\t\t\t// Prepend the logger's name to the log message for easy identification.\r\n\t\t\t\t\tif (context.name) {\r\n\t\t\t\t\t\tmessages.unshift(\"[\" + context.name + \"]\");\r\n\t\t\t\t\t}\r\n\t\t\t\t};\r\n\r\n\t\t\t\t// Map of timestamps by timer labels used to track `#time` and `#timeEnd()` invocations in environments\r\n\t\t\t\t// that don't offer a native console method.\r\n\t\t\t\tvar timerStartTimeByLabelMap = {};\r\n\r\n\t\t\t\t// Support for IE8+ (and other, slightly more sane environments)\r\n\t\t\t\tvar invokeConsoleMethod = function (hdlr, messages) {\r\n\t\t\t\t\tFunction.prototype.apply.call(hdlr, console, messages);\r\n\t\t\t\t};\r\n\r\n\t\t\t\t// Check for the presence of a logger.\r\n\t\t\t\tif (typeof console === \"undefined\") {\r\n\t\t\t\t\treturn function () { /* no console */ };\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn function(messages, context) {\r\n\t\t\t\t\t// Convert arguments object to Array.\r\n\t\t\t\t\tmessages = Array.prototype.slice.call(messages);\r\n\r\n\t\t\t\t\tvar hdlr = console.log;\r\n\t\t\t\t\tvar timerLabel;\r\n\r\n\t\t\t\t\tif (context.level === Logger.TIME) {\r\n\t\t\t\t\t\ttimerLabel = (context.name ? '[' + context.name + '] ' : '') + messages[0];\r\n\r\n\t\t\t\t\t\tif (messages[1] === 'start') {\r\n\t\t\t\t\t\t\tif (console.time) {\r\n\t\t\t\t\t\t\t\tconsole.time(timerLabel);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\ttimerStartTimeByLabelMap[timerLabel] = new Date().getTime();\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tif (console.timeEnd) {\r\n\t\t\t\t\t\t\t\tconsole.timeEnd(timerLabel);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\tinvokeConsoleMethod(hdlr, [ timerLabel + ': ' +\r\n\t\t\t\t\t\t\t\t\t(new Date().getTime() - timerStartTimeByLabelMap[timerLabel]) + 'ms' ]);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\t// Delegate through to custom warn/error loggers if present on the console.\r\n\t\t\t\t\t\tif (context.level === Logger.WARN && console.warn) {\r\n\t\t\t\t\t\t\thdlr = console.warn;\r\n\t\t\t\t\t\t} else if (context.level === Logger.ERROR && console.error) {\r\n\t\t\t\t\t\t\thdlr = console.error;\r\n\t\t\t\t\t\t} else if (context.level === Logger.INFO && console.info) {\r\n\t\t\t\t\t\t\thdlr = console.info;\r\n\t\t\t\t\t\t} else if (context.level === Logger.DEBUG && console.debug) {\r\n\t\t\t\t\t\t\thdlr = console.debug;\r\n\t\t\t\t\t\t} else if (context.level === Logger.TRACE && console.trace) {\r\n\t\t\t\t\t\t\thdlr = console.trace;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\toptions.formatter(messages, context);\r\n\t\t\t\t\t\tinvokeConsoleMethod(hdlr, messages);\r\n\t\t\t\t\t}\r\n\t\t\t\t};\r\n\t\t\t};\r\n\r\n\t\t\t// Configure and example a Default implementation which writes to the `window.console` (if present). The\r\n\t\t\t// `options` hash can be used to configure the default logLevel and provide a custom message formatter.\r\n\t\t\tLogger.useDefaults = function(options) {\r\n\t\t\t\tLogger.setLevel(options && options.defaultLevel || Logger.DEBUG);\r\n\t\t\t\tLogger.setHandler(Logger.createDefaultHandler(options));\r\n\t\t\t};\r\n\r\n\t\t\t// Createa an alias to useDefaults to avoid reaking a react-hooks rule.\r\n\t\t\tLogger.setDefaults = Logger.useDefaults;\r\n\r\n\t\t\t// Export to popular environments boilerplate.\r\n\t\t\tif (module.exports) {\r\n\t\t\t\tmodule.exports = Logger;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tLogger._prevLogger = global.Logger;\r\n\r\n\t\t\t\tLogger.noConflict = function () {\r\n\t\t\t\t\tglobal.Logger = Logger._prevLogger;\r\n\t\t\t\t\treturn Logger;\r\n\t\t\t\t};\r\n\r\n\t\t\t\tglobal.Logger = Logger;\r\n\t\t\t}\r\n\t\t}(logger)); \n\t} (logger$1));\n\treturn logger$1.exports;\n}\n\nvar loggerExports = requireLogger();\nvar Logger = /*@__PURE__*/getDefaultExportFromCjs(loggerExports);\n\n/**\n * Set of generic interfaces to allow PowerSync compatibility with\n * different SQLite DB implementations.\n */\n/**\n * Update table operation numbers from SQLite\n */\nvar RowUpdateType;\n(function (RowUpdateType) {\n RowUpdateType[RowUpdateType[\"SQLITE_INSERT\"] = 18] = \"SQLITE_INSERT\";\n RowUpdateType[RowUpdateType[\"SQLITE_DELETE\"] = 9] = \"SQLITE_DELETE\";\n RowUpdateType[RowUpdateType[\"SQLITE_UPDATE\"] = 23] = \"SQLITE_UPDATE\";\n})(RowUpdateType || (RowUpdateType = {}));\nfunction isBatchedUpdateNotification(update) {\n return 'tables' in update;\n}\nfunction extractTableUpdates(update) {\n return isBatchedUpdateNotification(update) ? update.tables : [update.table];\n}\n\n/**\n * @internal The priority used by the core extension to indicate that a full sync was completed.\n */\nconst FULL_SYNC_PRIORITY = 2147483647;\n/**\n * Provides realtime progress on how PowerSync is downloading rows.\n *\n * The progress until the next complete sync is available through the fields on {@link ProgressWithOperations},\n * which this class implements.\n * Additionally, the {@link SyncProgress.untilPriority} method can be used to otbain progress towards\n * a specific priority (instead of the progress for the entire download).\n *\n * The reported progress always reflects the status towards the end of a sync iteration (after\n * which a consistent snapshot of all buckets is available locally).\n *\n * In rare cases (in particular, when a [compacting](https://docs.powersync.com/usage/lifecycle-maintenance/compacting-buckets)\n * operation takes place between syncs), it's possible for the returned numbers to be slightly\n * inaccurate. For this reason, {@link SyncProgress} should be seen as an approximation of progress.\n * The information returned is good enough to build progress bars, but not exact enough to track\n * individual download counts.\n *\n * Also note that data is downloaded in bulk, which means that individual counters are unlikely\n * to be updated one-by-one.\n */\nclass SyncProgress {\n internal;\n totalOperations;\n downloadedOperations;\n downloadedFraction;\n constructor(internal) {\n this.internal = internal;\n const untilCompletion = this.untilPriority(FULL_SYNC_PRIORITY);\n this.totalOperations = untilCompletion.totalOperations;\n this.downloadedOperations = untilCompletion.downloadedOperations;\n this.downloadedFraction = untilCompletion.downloadedFraction;\n }\n /**\n * Returns download progress towards all data up until the specified priority being received.\n *\n * The returned {@link ProgressWithOperations} tracks the target amount of operations that need\n * to be downloaded in total and how many of them have already been received.\n */\n untilPriority(priority) {\n let total = 0;\n let downloaded = 0;\n for (const progress of Object.values(this.internal)) {\n // Include higher-priority buckets, which are represented by lower numbers.\n if (progress.priority <= priority) {\n downloaded += progress.since_last;\n total += progress.target_count - progress.at_last;\n }\n }\n let progress = total == 0 ? 0.0 : downloaded / total;\n return {\n totalOperations: total,\n downloadedOperations: downloaded,\n downloadedFraction: progress\n };\n }\n}\n\nclass SyncStatus {\n options;\n constructor(options) {\n this.options = options;\n }\n /**\n * Returns the used sync client implementation (either the one implemented in JavaScript or the newer Rust-based\n * implementation).\n *\n * This information is only available after a connection has been requested.\n */\n get clientImplementation() {\n return this.options.clientImplementation;\n }\n /**\n * Indicates if the client is currently connected to the PowerSync service.\n *\n * @returns {boolean} True if connected, false otherwise. Defaults to false if not specified.\n */\n get connected() {\n return this.options.connected ?? false;\n }\n /**\n * Indicates if the client is in the process of establishing a connection to the PowerSync service.\n *\n * @returns {boolean} True if connecting, false otherwise. Defaults to false if not specified.\n */\n get connecting() {\n return this.options.connecting ?? false;\n }\n /**\n * Time that a last sync has fully completed, if any.\n * This timestamp is reset to null after a restart of the PowerSync service.\n *\n * @returns {Date | undefined} The timestamp of the last successful sync, or undefined if no sync has completed.\n */\n get lastSyncedAt() {\n return this.options.lastSyncedAt;\n }\n /**\n * Indicates whether there has been at least one full sync completed since initialization.\n *\n * @returns {boolean | undefined} True if at least one sync has completed, false if no sync has completed,\n * or undefined when the state is still being loaded from the database.\n */\n get hasSynced() {\n return this.options.hasSynced;\n }\n /**\n * Provides the current data flow status regarding uploads and downloads.\n *\n * @returns {SyncDataFlowStatus} An object containing:\n * - downloading: True if actively downloading changes (only when connected is also true)\n * - uploading: True if actively uploading changes\n * Defaults to {downloading: false, uploading: false} if not specified.\n */\n get dataFlowStatus() {\n return (this.options.dataFlow ?? {\n /**\n * true if actively downloading changes.\n * This is only true when {@link connected} is also true.\n */\n downloading: false,\n /**\n * true if uploading changes.\n */\n uploading: false\n });\n }\n /**\n * All sync streams currently being tracked in teh database.\n *\n * This returns null when the database is currently being opened and we don't have reliable information about all\n * included streams yet.\n *\n * @experimental Sync streams are currently in alpha.\n */\n get syncStreams() {\n return this.options.dataFlow?.internalStreamSubscriptions?.map((core) => new SyncStreamStatusView(this, core));\n }\n /**\n * If the `stream` appears in {@link syncStreams}, returns the current status for that stream.\n *\n * @experimental Sync streams are currently in alpha.\n */\n forStream(stream) {\n const asJson = JSON.stringify(stream.parameters);\n const raw = this.options.dataFlow?.internalStreamSubscriptions?.find((r) => r.name == stream.name && asJson == JSON.stringify(r.parameters));\n return raw && new SyncStreamStatusView(this, raw);\n }\n /**\n * Provides sync status information for all bucket priorities, sorted by priority (highest first).\n *\n * @returns {SyncPriorityStatus[]} An array of status entries for different sync priority levels,\n * sorted with highest priorities (lower numbers) first.\n */\n get priorityStatusEntries() {\n return (this.options.priorityStatusEntries ?? []).slice().sort(SyncStatus.comparePriorities);\n }\n /**\n * A realtime progress report on how many operations have been downloaded and\n * how many are necessary in total to complete the next sync iteration.\n *\n * This field is only set when {@link SyncDataFlowStatus#downloading} is also true.\n */\n get downloadProgress() {\n const internalProgress = this.options.dataFlow?.downloadProgress;\n if (internalProgress == null) {\n return null;\n }\n return new SyncProgress(internalProgress);\n }\n /**\n * Reports the sync status (a pair of {@link SyncStatus#hasSynced} and {@link SyncStatus#lastSyncedAt} fields)\n * for a specific bucket priority level.\n *\n * When buckets with different priorities are declared, PowerSync may choose to synchronize higher-priority\n * buckets first. When a consistent view over all buckets for all priorities up until the given priority is\n * reached, PowerSync makes data from those buckets available before lower-priority buckets have finished\n * syncing.\n *\n * This method returns the status for the requested priority or the next higher priority level that has\n * status information available. This is because when PowerSync makes data for a given priority available,\n * all buckets in higher-priorities are guaranteed to be consistent with that checkpoint.\n *\n * For example, if PowerSync just finished synchronizing buckets in priority level 3, calling this method\n * with a priority of 1 may return information for priority level 3.\n *\n * @param {number} priority The bucket priority for which the status should be reported\n * @returns {SyncPriorityStatus} Status information for the requested priority level or the next higher level with available status\n */\n statusForPriority(priority) {\n // priorityStatusEntries are sorted by ascending priorities (so higher numbers to lower numbers).\n for (const known of this.priorityStatusEntries) {\n // We look for the first entry that doesn't have a higher priority.\n if (known.priority >= priority) {\n return known;\n }\n }\n // If we have a complete sync, that necessarily includes all priorities.\n return {\n priority,\n lastSyncedAt: this.lastSyncedAt,\n hasSynced: this.hasSynced\n };\n }\n /**\n * Compares this SyncStatus instance with another to determine if they are equal.\n * Equality is determined by comparing the serialized JSON representation of both instances.\n *\n * @param {SyncStatus} status The SyncStatus instance to compare against\n * @returns {boolean} True if the instances are considered equal, false otherwise\n */\n isEqual(status) {\n /**\n * By default Error object are serialized to an empty object.\n * This replaces Errors with more useful information before serialization.\n */\n const replacer = (_, value) => {\n if (value instanceof Error) {\n return {\n name: value.name,\n message: value.message,\n stack: value.stack\n };\n }\n return value;\n };\n return JSON.stringify(this.options, replacer) == JSON.stringify(status.options, replacer);\n }\n /**\n * Creates a human-readable string representation of the current sync status.\n * Includes information about connection state, sync completion, and data flow.\n *\n * @returns {string} A string representation of the sync status\n */\n getMessage() {\n const dataFlow = this.dataFlowStatus;\n return `SyncStatus<connected: ${this.connected} connecting: ${this.connecting} lastSyncedAt: ${this.lastSyncedAt} hasSynced: ${this.hasSynced}. Downloading: ${dataFlow.downloading}. Uploading: ${dataFlow.uploading}. UploadError: ${dataFlow.uploadError}, DownloadError?: ${dataFlow.downloadError}>`;\n }\n /**\n * Serializes the SyncStatus instance to a plain object.\n *\n * @returns {SyncStatusOptions} A plain object representation of the sync status\n */\n toJSON() {\n return {\n connected: this.connected,\n connecting: this.connecting,\n dataFlow: {\n ...this.dataFlowStatus,\n uploadError: this.serializeError(this.dataFlowStatus.uploadError),\n downloadError: this.serializeError(this.dataFlowStatus.downloadError)\n },\n lastSyncedAt: this.lastSyncedAt,\n hasSynced: this.hasSynced,\n priorityStatusEntries: this.priorityStatusEntries\n };\n }\n /**\n * Not all errors are serializable over a MessagePort. E.g. some `DomExceptions` fail to be passed across workers.\n * This explicitly serializes errors in the SyncStatus.\n */\n serializeError(error) {\n if (typeof error == 'undefined') {\n return undefined;\n }\n return {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n }\n static comparePriorities(a, b) {\n return b.priority - a.priority; // Reverse because higher priorities have lower numbers\n }\n}\nclass SyncStreamStatusView {\n status;\n core;\n subscription;\n constructor(status, core) {\n this.status = status;\n this.core = core;\n this.subscription = {\n name: core.name,\n parameters: core.parameters,\n active: core.active,\n isDefault: core.is_default,\n hasExplicitSubscription: core.has_explicit_subscription,\n expiresAt: core.expires_at != null ? new Date(core.expires_at * 1000) : null,\n hasSynced: core.last_synced_at != null,\n lastSyncedAt: core.last_synced_at != null ? new Date(core.last_synced_at * 1000) : null\n };\n }\n get progress() {\n if (this.status.dataFlowStatus.downloadProgress == null) {\n // Don't make download progress public if we're not currently downloading.\n return null;\n }\n const { total, downloaded } = this.core.progress;\n const progress = total == 0 ? 0.0 : downloaded / total;\n return { totalOperations: total, downloadedOperations: downloaded, downloadedFraction: progress };\n }\n get priority() {\n return this.core.priority;\n }\n}\n\nclass UploadQueueStats {\n count;\n size;\n constructor(\n /**\n * Number of records in the upload queue.\n */\n count, \n /**\n * Size of the upload queue in bytes.\n */\n size = null) {\n this.count = count;\n this.size = size;\n }\n toString() {\n if (this.size == null) {\n return `UploadQueueStats<count:${this.count}>`;\n }\n else {\n return `UploadQueueStats<count: $count size: ${this.size / 1024}kB>`;\n }\n }\n}\n\nclass BaseObserver {\n listeners = new Set();\n constructor() { }\n dispose() {\n this.listeners.clear();\n }\n /**\n * Register a listener for updates to the PowerSync client.\n */\n registerListener(listener) {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n iterateListeners(cb) {\n for (const listener of this.listeners) {\n cb(listener);\n }\n }\n async iterateAsyncListeners(cb) {\n for (let i of Array.from(this.listeners.values())) {\n await cb(i);\n }\n }\n}\n\nclass ControlledExecutor {\n task;\n /**\n * Represents the currently running task, which could be a Promise or undefined if no task is running.\n */\n runningTask;\n pendingTaskParam;\n /**\n * Flag to determine if throttling is enabled, which controls whether tasks are queued or run immediately.\n */\n isThrottling;\n closed;\n constructor(task, options) {\n this.task = task;\n const { throttleEnabled = true } = options ?? {};\n this.isThrottling = throttleEnabled;\n this.closed = false;\n }\n schedule(param) {\n if (this.closed) {\n return;\n }\n if (!this.isThrottling) {\n this.task(param);\n return;\n }\n if (this.runningTask) {\n // set or replace the pending task param with latest one\n this.pendingTaskParam = param;\n return;\n }\n this.execute(param);\n }\n dispose() {\n this.closed = true;\n if (this.runningTask) {\n this.runningTask = undefined;\n }\n }\n async execute(param) {\n this.runningTask = this.task(param);\n await this.runningTask;\n this.runningTask = undefined;\n if (this.pendingTaskParam) {\n const pendingParam = this.pendingTaskParam;\n this.pendingTaskParam = undefined;\n this.execute(pendingParam);\n }\n }\n}\n\n/**\n * A ponyfill for `Symbol.asyncIterator` that is compatible with the\n * [recommended polyfill](https://github.com/Azure/azure-sdk-for-js/blob/%40azure/core-asynciterator-polyfill_1.0.2/sdk/core/core-asynciterator-polyfill/src/index.ts#L4-L6)\n * we recommend for React Native.\n *\n * As long as we use this symbol (instead of `for await` and `async *`) in this package, we can be compatible with async\n * iterators without requiring them.\n */\nconst symbolAsyncIterator = Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');\n/**\n * Throttle a function to be called at most once every \"wait\" milliseconds,\n * on the trailing edge.\n *\n * Roughly equivalent to lodash/throttle with {leading: false, trailing: true}\n */\nfunction throttleTrailing(func, wait) {\n let timeoutId = null;\n const later = () => {\n func();\n timeoutId = null;\n };\n return function () {\n if (timeoutId == null) {\n timeoutId = setTimeout(later, wait);\n }\n };\n}\n/**\n * Throttle a function to be called at most once every \"wait\" milliseconds,\n * on the leading and trailing edge.\n *\n * Roughly equivalent to lodash/throttle with {leading: true, trailing: true}\n */\nfunction throttleLeadingTrailing(func, wait) {\n let timeoutId = null;\n let lastCallTime = 0;\n const invokeFunction = () => {\n func();\n lastCallTime = Date.now();\n timeoutId = null;\n };\n return function () {\n const now = Date.now();\n const timeToWait = wait - (now - lastCallTime);\n if (timeToWait <= 0) {\n // Leading edge: Call the function immediately if enough time has passed\n invokeFunction();\n }\n else if (!timeoutId) {\n // Set a timeout for the trailing edge if not already set\n timeoutId = setTimeout(invokeFunction, timeToWait);\n }\n };\n}\n\n/**\n * @internal\n */\nclass ConnectionManager extends BaseObserver {\n options;\n /**\n * Tracks active connection attempts\n */\n connectingPromise;\n /**\n * Tracks actively instantiating a streaming sync implementation.\n */\n syncStreamInitPromise;\n /**\n * Active disconnect operation. Calling disconnect multiple times\n * will resolve to the same operation.\n */\n disconnectingPromise;\n /**\n * Tracks the last parameters supplied to `connect` calls.\n * Calling `connect` multiple times in succession will result in:\n * - 1 pending connection operation which will be aborted.\n * - updating the last set of parameters while waiting for the pending\n * attempt to be aborted\n * - internally connecting with the last set of parameters\n */\n pendingConnectionOptions;\n syncStreamImplementation;\n /**\n * Additional cleanup function which is called after the sync stream implementation\n * is disposed.\n */\n syncDisposer;\n /**\n * Subscriptions managed in this connection manager.\n *\n * On the web, these local subscriptions are merged across tabs by a shared worker.\n */\n locallyActiveSubscriptions = new Map();\n constructor(options) {\n super();\n this.options = options;\n this.connectingPromise = null;\n this.syncStreamInitPromise = null;\n this.disconnectingPromise = null;\n this.pendingConnectionOptions = null;\n this.syncStreamImplementation = null;\n this.syncDisposer = null;\n }\n get connector() {\n return this.pendingConnectionOptions?.connector ?? null;\n }\n get connectionOptions() {\n return this.pendingConnectionOptions?.options ?? null;\n }\n get logger() {\n return this.options.logger;\n }\n async close() {\n await this.syncStreamImplementation?.dispose();\n await this.syncDisposer?.();\n }\n async connect(connector, options) {\n // Keep track if there were pending operations before this call\n const hadPendingOptions = !!this.pendingConnectionOptions;\n // Update pending options to the latest values\n this.pendingConnectionOptions = {\n connector,\n options\n };\n // Disconnecting here provides aborting in progress connection attempts.\n // The connectInternal method will clear pending options once it starts connecting (with the options).\n // We only need to trigger a disconnect here if we have already reached the point of connecting.\n // If we do already have pending options, a disconnect has already been performed.\n // The connectInternal method also does a sanity disconnect to prevent straggler connections.\n // We should also disconnect if we have already completed a connection attempt.\n if (!hadPendingOptions || this.syncStreamImplementation) {\n await this.disconnectInternal();\n }\n // Triggers a connect which checks if pending options are available after the connect completes.\n // The completion can be for a successful, unsuccessful or aborted connection attempt.\n // If pending options are available another connection will be triggered.\n const checkConnection = async () => {\n if (this.pendingConnectionOptions) {\n // Pending options have been placed while connecting.\n // Need to reconnect.\n this.connectingPromise = this.connectInternal()\n .catch(() => { })\n .finally(checkConnection);\n return this.connectingPromise;\n }\n else {\n // Clear the connecting promise, done.\n this.connectingPromise = null;\n return;\n }\n };\n this.connectingPromise ??= this.connectInternal()\n .catch(() => { })\n .finally(checkConnection);\n return this.connectingPromise;\n }\n async connectInternal() {\n let appliedOptions = null;\n // This method ensures a disconnect before any connection attempt\n await this.disconnectInternal();\n /**\n * This portion creates a sync implementation which can be racy when disconnecting or\n * if multiple tabs on web are in use.\n * This is protected in an exclusive lock.\n * The promise tracks the creation which is used to synchronize disconnect attempts.\n */\n this.syncStreamInitPromise = new Promise(async (resolve, reject) => {\n try {\n if (!this.pendingConnectionOptions) {\n this.logger.debug('No pending connection options found, not creating sync stream implementation');\n // A disconnect could have cleared this.\n resolve();\n return;\n }\n if (this.disconnectingPromise) {\n resolve();\n return;\n }\n const { connector, options } = this.pendingConnectionOptions;\n appliedOptions = options;\n this.pendingConnectionOptions = null;\n const { sync, onDispose } = await this.options.createSyncImplementation(connector, {\n subscriptions: this.activeStreams,\n ...options\n });\n this.iterateListeners((l) => l.syncStreamCreated?.(sync));\n this.syncStreamImplementation = sync;\n this.syncDisposer = onDispose;\n await this.syncStreamImplementation.waitForReady();\n resolve();\n }\n catch (error) {\n reject(error);\n }\n });\n await this.syncStreamInitPromise;\n this.syncStreamInitPromise = null;\n if (!appliedOptions) {\n // A disconnect could have cleared the options which did not create a syncStreamImplementation\n return;\n }\n // It might be possible that a disconnect triggered between the last check\n // and this point. Awaiting here allows the sync stream to be cleared if disconnected.\n await this.disconnectingPromise;\n this.logger.debug('Attempting to connect to PowerSync instance');\n await this.syncStreamImplementation?.connect(appliedOptions);\n }\n /**\n * Close the sync connection.\n *\n * Use {@link connect} to connect again.\n */\n async disconnect() {\n // This will help abort pending connects\n this.pendingConnectionOptions = null;\n await this.disconnectInternal();\n }\n async disconnectInternal() {\n if (this.disconnectingPromise) {\n // A disconnect is already in progress\n return this.disconnectingPromise;\n }\n this.disconnectingPromise = this.performDisconnect();\n await this.disconnectingPromise;\n this.disconnectingPromise = null;\n }\n async performDisconnect() {\n // Wait if a sync stream implementation is being created before closing it\n // (syncStreamImplementation must be assigned before we can properly dispose it)\n await this.syncStreamInitPromise;\n // Keep reference to the sync stream implementation and disposer\n // The class members will be cleared before we trigger the disconnect\n // to prevent any further calls to the sync stream implementation.\n const sync = this.syncStreamImplementation;\n this.syncStreamImplementation = null;\n const disposer = this.syncDisposer;\n this.syncDisposer = null;\n await sync?.disconnect();\n await sync?.dispose();\n await disposer?.();\n }\n stream(adapter, name, parameters) {\n const desc = { name, parameters };\n const waitForFirstSync = (abort) => {\n return adapter.firstStatusMatching((s) => s.forStream(desc)?.subscription.hasSynced, abort);\n };\n return {\n ...desc,\n subscribe: async (options) => {\n // NOTE: We also run this command if a subscription already exists, because this increases the expiry date\n // (relevant if the app is closed before connecting again, where the last subscribe call determines the ttl).\n await adapter.rustSubscriptionsCommand({\n subscribe: {\n stream: {\n name,\n params: parameters\n },\n ttl: options?.ttl,\n priority: options?.priority\n }\n });\n if (!this.syncStreamImplementation) {\n // We're not connected. So, update the offline sync status to reflect the new subscription.\n // (With an active iteration, the sync client would include it in its state).\n await adapter.resolveOfflineSyncStatus();\n }\n const key = `${name}|${JSON.stringify(parameters)}`;\n let subscription = this.locallyActiveSubscriptions.get(key);\n if (subscription == null) {\n const clearSubscription = () => {\n this.locallyActiveSubscriptions.delete(key);\n this.subscriptionsMayHaveChanged();\n };\n subscription = new ActiveSubscription(name, parameters, this.logger, waitForFirstSync, clearSubscription);\n this.locallyActiveSubscriptions.set(key, subscription);\n this.subscriptionsMayHaveChanged();\n }\n return new SyncStreamSubscriptionHandle(subscription);\n },\n unsubscribeAll: async () => {\n await adapter.rustSubscriptionsCommand({ unsubscribe: { name, params: parameters } });\n this.subscriptionsMayHaveChanged();\n }\n };\n }\n /**\n * @internal exposed for testing\n */\n get activeStreams() {\n return [...this.locallyActiveSubscriptions.values()].map((a) => ({ name: a.name, params: a.parameters }));\n }\n subscriptionsMayHaveChanged() {\n this.syncStreamImplementation?.updateSubscriptions(this.activeStreams);\n }\n}\nclass ActiveSubscription {\n name;\n parameters;\n logger;\n waitForFirstSync;\n clearSubscription;\n refcount = 0;\n constructor(name, parameters, logger, waitForFirstSync, clearSubscription) {\n this.name = name;\n this.parameters = parameters;\n this.logger = logger;\n this.waitForFirstSync = waitForFirstSync;\n this.clearSubscription = clearSubscription;\n }\n decrementRefCount() {\n this.refcount--;\n if (this.refcount == 0) {\n this.clearSubscription();\n }\n }\n}\nclass SyncStreamSubscriptionHandle {\n subscription;\n active = true;\n constructor(subscription) {\n this.subscription = subscription;\n subscription.refcount++;\n _finalizer?.register(this, subscription);\n }\n get name() {\n return this.subscription.name;\n }\n get parameters() {\n return this.subscription.parameters;\n }\n waitForFirstSync(abort) {\n return this.subscription.waitForFirstSync(abort);\n }\n unsubscribe() {\n if (this.active) {\n this.active = false;\n _finalizer?.unregister(this);\n this.subscription.decrementRefCount();\n }\n }\n}\nconst _finalizer = 'FinalizationRegistry' in globalThis\n ? new FinalizationRegistry((sub) => {\n sub.logger.warn(`A subscription to ${sub.name} with params ${JSON.stringify(sub.parameters)} leaked! Please ensure calling unsubscribe() when you don't need a subscription anymore. For global subscriptions, consider storing them in global fields to avoid this warning.`);\n })\n : null;\n\n/**\n * An efficient comparator for {@link WatchedQuery} created with {@link Query#watch}. This has the ability to determine if a query\n * result has changes without necessarily processing all items in the result.\n */\nclass ArrayComparator {\n options;\n constructor(options) {\n this.options = options;\n }\n checkEquality(current, previous) {\n if (current.length === 0 && previous.length === 0) {\n return true;\n }\n if (current.length !== previous.length) {\n return false;\n }\n const { compareBy } = this.options;\n // At this point the lengths are equal\n for (let i = 0; i < current.length; i++) {\n const currentItem = compareBy(current[i]);\n const previousItem = compareBy(previous[i]);\n if (currentItem !== previousItem) {\n return false;\n }\n }\n return true;\n }\n}\n/**\n * Watched query comparator that always reports changed result sets.\n */\nconst FalsyComparator = {\n checkEquality: () => false // Default comparator that always returns false\n};\n\n/**\n * A BaseObserver that tracks the counts of listeners for each event type.\n */\nclass MetaBaseObserver extends BaseObserver {\n get listenerCounts() {\n const counts = {};\n let total = 0;\n for (const listener of this.listeners) {\n for (const key in listener) {\n if (listener[key]) {\n counts[key] = (counts[key] ?? 0) + 1;\n total++;\n }\n }\n }\n return {\n ...counts,\n total\n };\n }\n get listenerMeta() {\n return {\n counts: this.listenerCounts,\n // Allows registering a meta listener that will be notified of changes in listener counts\n registerListener: (listener) => {\n return this.metaListener.registerListener(listener);\n }\n };\n }\n metaListener;\n constructor() {\n super();\n this.metaListener = new BaseObserver();\n }\n registerListener(listener) {\n const dispose = super.registerListener(listener);\n const updatedCount = this.listenerCounts;\n this.metaListener.iterateListeners((l) => {\n l.listenersChanged?.(updatedCount);\n });\n return () => {\n dispose();\n const updatedCount = this.listenerCounts;\n this.metaListener.iterateListeners((l) => {\n l.listenersChanged?.(updatedCount);\n });\n };\n }\n}\n\n/**\n * Performs underlying watching and yields a stream of results.\n * @internal\n */\nclass AbstractQueryProcessor extends MetaBaseObserver {\n options;\n state;\n abortController;\n initialized;\n _closed;\n disposeListeners;\n get closed() {\n return this._closed;\n }\n constructor(options) {\n super();\n this.options = options;\n this.abortController = new AbortController();\n this._closed = false;\n this.state = this.constructInitialState();\n this.disposeListeners = null;\n this.initialized = this.init(this.abortController.signal);\n }\n constructInitialState() {\n return {\n isLoading: true,\n isFetching: this.reportFetching, // Only set to true if we will report updates in future\n error: null,\n lastUpdated: null,\n data: this.options.placeholderData\n };\n }\n get reportFetching() {\n return this.options.watchOptions.reportFetching ?? true;\n }\n async updateSettingsInternal(settings, signal) {\n // This may have been aborted while awaiting or if multiple calls to `updateSettings` were made\n if (this._closed || signal.aborted) {\n return;\n }\n this.options.watchOptions = settings;\n this.iterateListeners((l) => l[WatchedQueryListenerEvent.SETTINGS_WILL_UPDATE]?.());\n if (!this.state.isFetching && this.reportFetching) {\n await this.updateState({\n isFetching: true\n });\n }\n await this.runWithReporting(() => this.linkQuery({\n abortSignal: signal,\n settings\n }));\n }\n /**\n * Updates the underlying query.\n */\n async updateSettings(settings) {\n // Abort the previous request\n this.abortController.abort();\n // Keep track of this controller's abort status\n const abortController = new AbortController();\n // Allow this to be aborted externally\n this.abortController = abortController;\n await this.initialized;\n return this.updateSettingsInternal(settings, abortController.signal);\n }\n async updateState(update) {\n if (this._closed) {\n return;\n }\n if (typeof update.error !== 'undefined') {\n await this.iterateAsyncListenersWithError(async (l) => l.onError?.(update.error));\n // An error always stops for the current fetching state\n update.isFetching = false;\n update.isLoading = false;\n }\n Object.assign(this.state, { lastUpdated: new Date() }, update);\n if (typeof update.data !== 'undefined') {\n await this.iterateAsyncListenersWithError(async (l) => l.onData?.(this.state.data));\n }\n await this.iterateAsyncListenersWithError(async (l) => l.onStateChange?.(this.state));\n }\n /**\n * Configures base DB listeners and links the query to listeners.\n */\n async init(signal) {\n const { db } = this.options;\n const disposeCloseListener = db.registerListener({\n closing: async () => {\n await this.close();\n }\n });\n // Wait for the schema to be set before listening to changes\n await db.waitForReady();\n const disposeSchemaListener = db.registerListener({\n schemaChanged: async () => {\n await this.runWithReporting(async () => {\n await this.updateSettings(this.options.watchOptions);\n });\n }\n });\n this.disposeListeners = () => {\n disposeCloseListener();\n disposeSchemaListener();\n };\n // Initial setup\n await this.runWithReporting(async () => {\n await this.updateSettingsInternal(this.options.watchOptions, signal);\n });\n }\n async close() {\n this._closed = true;\n this.abortController.abort();\n this.disposeListeners?.();\n this.disposeListeners = null;\n this.iterateListeners((l) => l.closed?.());\n this.listeners.clear();\n }\n /**\n * Runs a callback and reports errors to the error listeners.\n */\n async runWithReporting(callback) {\n try {\n await callback();\n }\n catch (error) {\n // This will update the error on the state and iterate error listeners\n await this.updateState({ error });\n }\n }\n /**\n * Iterate listeners and reports errors to onError handlers.\n */\n async iterateAsyncListenersWithError(callback) {\n try {\n await this.iterateAsyncListeners(async (l) => callback(l));\n }\n catch (error) {\n try {\n await this.iterateAsyncListeners(async (l) => l.onError?.(error));\n }\n catch (error) {\n // Errors here are ignored\n // since we are already in an error state\n this.options.db.logger.error('Watched query error handler threw an Error', error);\n }\n }\n }\n}\n\n/**\n * An empty differential result set.\n * This is used as the initial state for differential incrementally watched queries.\n */\nconst EMPTY_DIFFERENTIAL = {\n added: [],\n all: [],\n removed: [],\n updated: [],\n unchanged: []\n};\n/**\n * Default implementation of the {@link DifferentialWatchedQueryComparator} for watched queries.\n * It keys items by their `id` property if available, alternatively it uses JSON stringification\n * of the entire item for the key and comparison.\n */\nconst DEFAULT_ROW_COMPARATOR = {\n keyBy: (item) => {\n if (item && typeof item == 'object' && typeof item['id'] == 'string') {\n return item['id'];\n }\n return JSON.stringify(item);\n },\n compareBy: (item) => JSON.stringify(item)\n};\n/**\n * Uses the PowerSync onChange event to trigger watched queries.\n * Results are emitted on every change of the relevant tables.\n * @internal\n */\nclass DifferentialQueryProcessor extends AbstractQueryProcessor {\n options;\n comparator;\n constructor(options) {\n super(options);\n this.options = options;\n this.comparator = options.rowComparator ?? DEFAULT_ROW_COMPARATOR;\n }\n /*\n * @returns If the sets are equal\n */\n differentiate(current, previousMap) {\n const { keyBy, compareBy } = this.comparator;\n let hasChanged = false;\n const currentMap = new Map();\n const removedTracker = new Set(previousMap.keys());\n // Allow mutating to populate the data temporarily.\n const diff = {\n all: [],\n added: [],\n removed: [],\n updated: [],\n unchanged: []\n };\n /**\n * Looping over the current result set array is important to preserve\n * the ordering of the result set.\n * We can replace items in the current array with previous object references if they are equal.\n */\n for (const item of current) {\n const key = keyBy(item);\n const hash = compareBy(item);\n currentMap.set(key, { hash, item });\n const previousItem = previousMap.get(key);\n if (!previousItem) {\n // New item\n hasChanged = true;\n diff.added.push(item);\n diff.all.push(item);\n }\n else {\n // Existing item\n if (hash == previousItem.hash) {\n diff.unchanged.push(previousItem.item);\n // Use the previous object reference\n diff.all.push(previousItem.item);\n // update the map to preserve the reference\n currentMap.set(key, previousItem);\n }\n else {\n hasChanged = true;\n diff.updated.push({ current: item, previous: previousItem.item });\n // Use the new reference\n diff.all.push(item);\n }\n }\n // The item is present, we don't consider it removed\n removedTracker.delete(key);\n }\n diff.removed = Array.from(removedTracker).map((key) => previousMap.get(key).item);\n hasChanged = hasChanged || diff.removed.length > 0;\n return {\n diff,\n hasChanged,\n map: currentMap\n };\n }\n async linkQuery(options) {\n const { db, watchOptions } = this.options;\n const { abortSignal } = options;\n const compiledQuery = watchOptions.query.compile();\n const tables = await db.resolveTables(compiledQuery.sql, compiledQuery.parameters, {\n tables: options.settings.triggerOnTables\n });\n let currentMap = new Map();\n // populate the currentMap from the placeholder data\n this.state.data.forEach((item) => {\n currentMap.set(this.comparator.keyBy(item), {\n hash: this.comparator.compareBy(item),\n item\n });\n });\n db.onChangeWithCallback({\n onChange: async () => {\n if (this.closed || abortSignal.aborted) {\n return;\n }\n // This fires for each change of the relevant tables\n try {\n if (this.reportFetching && !this.state.isFetching) {\n await this.updateState({ isFetching: true });\n }\n const partialStateUpdate = {};\n // Always run the query if an underlying table has changed\n const result = await watchOptions.query.execute({\n sql: compiledQuery.sql,\n // Allows casting from ReadOnlyArray[unknown] to Array<unknown>\n // This allows simpler compatibility with PowerSync queries\n parameters: [...compiledQuery.parameters],\n db: this.options.db\n });\n if (abortSignal.aborted) {\n return;\n }\n if (this.reportFetching) {\n partialStateUpdate.isFetching = false;\n }\n if (this.state.isLoading) {\n partialStateUpdate.isLoading = false;\n }\n const { diff, hasChanged, map } = this.differentiate(result, currentMap);\n // Update for future comparisons\n currentMap = map;\n if (hasChanged) {\n await this.iterateAsyncListenersWithError((l) => l.onDiff?.(diff));\n Object.assign(partialStateUpdate, {\n data: diff.all\n });\n }\n if (this.state.error) {\n partialStateUpdate.error = null;\n }\n if (Object.keys(partialStateUpdate).length > 0) {\n await this.updateState(partialStateUpdate);\n }\n }\n catch (error) {\n await this.updateState({ error });\n }\n },\n onError: async (error) => {\n await this.updateState({ error });\n }\n }, {\n signal: abortSignal,\n tables,\n throttleMs: watchOptions.throttleMs,\n triggerImmediate: true // used to emit the initial state\n });\n }\n}\n\n/**\n * Uses the PowerSync onChange event to trigger watched queries.\n * Results are emitted on every change of the relevant tables.\n * @internal\n */\nclass OnChangeQueryProcessor extends AbstractQueryProcessor {\n options;\n constructor(options) {\n super(options);\n this.options = options;\n }\n /**\n * @returns If the sets are equal\n */\n checkEquality(current, previous) {\n // Use the provided comparator if available. Assume values are unique if not available.\n return this.options.comparator?.checkEquality?.(current, previous) ?? false;\n }\n async linkQuery(options) {\n const { db, watchOptions } = this.options;\n const { abortSignal } = options;\n const compiledQuery = watchOptions.query.compile();\n const tables = await db.resolveTables(compiledQuery.sql, compiledQuery.parameters, {\n tables: options.settings.triggerOnTables\n });\n db.onChangeWithCallback({\n onChange: async () => {\n if (this.closed || abortSignal.aborted) {\n return;\n }\n // This fires for each change of the relevant tables\n try {\n if (this.reportFetching && !this.state.isFetching) {\n await this.updateState({ isFetching: true });\n }\n const partialStateUpdate = {};\n // Always run the query if an underlying table has changed\n const result = await watchOptions.query.execute({\n sql: compiledQuery.sql,\n // Allows casting from ReadOnlyArray[unknown] to Array<unknown>\n // This allows simpler compatibility with PowerSync queries\n parameters: [...compiledQuery.parameters],\n db: this.options.db\n });\n if (abortSignal.aborted) {\n return;\n }\n if (this.reportFetching) {\n partialStateUpdate.isFetching = false;\n }\n if (this.state.isLoading) {\n partialStateUpdate.isLoading = false;\n }\n // Check if the result has changed\n if (!this.checkEquality(result, this.state.data)) {\n Object.assign(partialStateUpdate, {\n data: result\n });\n }\n if (this.state.error) {\n partialStateUpdate.error = null;\n }\n if (Object.keys(partialStateUpdate).length > 0) {\n await this.updateState(partialStateUpdate);\n }\n }\n catch (error) {\n await this.updateState({ error });\n }\n },\n onError: async (error) => {\n await this.updateState({ error });\n }\n }, {\n signal: abortSignal,\n tables,\n throttleMs: watchOptions.throttleMs,\n triggerImmediate: true // used to emit the initial state\n });\n }\n}\n\n/**\n * @internal\n */\nclass CustomQuery {\n options;\n constructor(options) {\n this.options = options;\n }\n resolveOptions(options) {\n return {\n reportFetching: options?.reportFetching ?? DEFAULT_WATCH_QUERY_OPTIONS.reportFetching,\n throttleMs: options?.throttleMs ?? DEFAULT_WATCH_QUERY_OPTIONS.throttleMs,\n triggerOnTables: options?.triggerOnTables\n };\n }\n watch(watchOptions) {\n return new OnChangeQueryProcessor({\n db: this.options.db,\n comparator: watchOptions?.comparator ?? FalsyComparator,\n placeholderData: watchOptions?.placeholderData ?? [],\n watchOptions: {\n ...this.resolveOptions(watchOptions),\n query: this.options.query\n }\n });\n }\n differentialWatch(differentialWatchOptions) {\n return new DifferentialQueryProcessor({\n db: this.options.db,\n rowComparator: differentialWatchOptions?.rowComparator,\n placeholderData: differentialWatchOptions?.placeholderData ?? [],\n watchOptions: {\n ...this.resolveOptions(differentialWatchOptions),\n query: this.options.query\n }\n });\n }\n}\n\n/**\n * Tests if the input is a {@link SQLOpenOptions}\n */\nconst isSQLOpenOptions = (test) => {\n // typeof null is `object`, but you cannot use the `in` operator on `null.\n return test && typeof test == 'object' && 'dbFilename' in test;\n};\n/**\n * Tests if input is a {@link SQLOpenFactory}\n */\nconst isSQLOpenFactory = (test) => {\n return typeof test?.openDB == 'function';\n};\n/**\n * Tests if input is a {@link DBAdapter}\n */\nconst isDBAdapter = (test) => {\n return typeof test?.writeTransaction == 'function';\n};\n\nvar PSInternalTable;\n(function (PSInternalTable) {\n PSInternalTable[\"DATA\"] = \"ps_data\";\n PSInternalTable[\"CRUD\"] = \"ps_crud\";\n PSInternalTable[\"BUCKETS\"] = \"ps_buckets\";\n PSInternalTable[\"OPLOG\"] = \"ps_oplog\";\n PSInternalTable[\"UNTYPED\"] = \"ps_untyped\";\n})(PSInternalTable || (PSInternalTable = {}));\nvar PowerSyncControlCommand;\n(function (PowerSyncControlCommand) {\n PowerSyncControlCommand[\"PROCESS_TEXT_LINE\"] = \"line_text\";\n PowerSyncControlCommand[\"PROCESS_BSON_LINE\"] = \"line_binary\";\n PowerSyncControlCommand[\"STOP\"] = \"stop\";\n PowerSyncControlCommand[\"START\"] = \"start\";\n PowerSyncControlCommand[\"NOTIFY_TOKEN_REFRESHED\"] = \"refreshed_token\";\n PowerSyncControlCommand[\"NOTIFY_CRUD_UPLOAD_COMPLETED\"] = \"completed_upload\";\n PowerSyncControlCommand[\"UPDATE_SUBSCRIPTIONS\"] = \"update_subscriptions\";\n})(PowerSyncControlCommand || (PowerSyncControlCommand = {}));\n\n/**\n * A batch of client-side changes.\n */\nclass CrudBatch {\n crud;\n haveMore;\n complete;\n constructor(\n /**\n * List of client-side changes.\n */\n crud, \n /**\n * true if there are more changes in the local queue.\n */\n haveMore, \n /**\n * Call to remove the changes from the local queue, once successfully uploaded.\n */\n complete) {\n this.crud = crud;\n this.haveMore = haveMore;\n this.complete = complete;\n }\n}\n\n/**\n * Type of local change.\n */\nvar UpdateType;\n(function (UpdateType) {\n /** Insert or replace existing row. All non-null columns are included in the data. Generated by INSERT statements. */\n UpdateType[\"PUT\"] = \"PUT\";\n /** Update existing row. Contains the id, and value of each changed column. Generated by UPDATE statements. */\n UpdateType[\"PATCH\"] = \"PATCH\";\n /** Delete existing row. Contains the id. Generated by DELETE statements. */\n UpdateType[\"DELETE\"] = \"DELETE\";\n})(UpdateType || (UpdateType = {}));\n/**\n * A single client-side change.\n */\nclass CrudEntry {\n /**\n * Auto-incrementing client-side id.\n */\n clientId;\n /**\n * ID of the changed row.\n */\n id;\n /**\n * Type of change.\n */\n op;\n /**\n * Data associated with the change.\n */\n opData;\n /**\n * For tables where the `trackPreviousValues` option has been enabled, this tracks previous values for\n * `UPDATE` and `DELETE` statements.\n */\n previousValues;\n /**\n * Table that contained the change.\n */\n table;\n /**\n * Auto-incrementing transaction id. This is the same for all operations within the same transaction.\n */\n transactionId;\n /**\n * Client-side metadata attached with this write.\n *\n * This field is only available when the `trackMetadata` option was set to `true` when creating a table\n * and the insert or update statement set the `_metadata` column.\n */\n metadata;\n static fromRow(dbRow) {\n const data = JSON.parse(dbRow.data);\n return new CrudEntry(parseInt(dbRow.id), data.op, data.type, data.id, dbRow.tx_id, data.data, data.old, data.metadata);\n }\n constructor(clientId, op, table, id, transactionId, opData, previousValues, metadata) {\n this.clientId = clientId;\n this.id = id;\n this.op = op;\n this.opData = opData;\n this.table = table;\n this.transactionId = transactionId;\n this.previousValues = previousValues;\n this.metadata = metadata;\n }\n /**\n * Converts the change to JSON format.\n */\n toJSON() {\n return {\n op_id: this.clientId,\n op: this.op,\n type: this.table,\n id: this.id,\n tx_id: this.transactionId,\n data: this.opData,\n old: this.previousValues,\n metadata: this.metadata\n };\n }\n equals(entry) {\n return JSON.stringify(this.toComparisonArray()) == JSON.stringify(entry.toComparisonArray());\n }\n /**\n * The hash code for this object.\n * @deprecated This should not be necessary in the JS SDK.\n * Use the @see CrudEntry#equals method instead.\n * TODO remove in the next major release.\n */\n hashCode() {\n return JSON.stringify(this.toComparisonArray());\n }\n /**\n * Generates an array for use in deep comparison operations\n */\n toComparisonArray() {\n return [\n this.transactionId,\n this.clientId,\n this.op,\n this.table,\n this.id,\n this.opData,\n this.previousValues,\n this.metadata\n ];\n }\n}\n\nclass CrudTransaction extends CrudBatch {\n crud;\n complete;\n transactionId;\n constructor(\n /**\n * List of client-side changes.\n */\n crud, \n /**\n * Call to remove the changes from the local queue, once successfully uploaded.\n */\n complete, \n /**\n * If null, this contains a list of changes recorded without an explicit transaction associated.\n */\n transactionId) {\n super(crud, false, complete);\n this.crud = crud;\n this.complete = complete;\n this.transactionId = transactionId;\n }\n}\n\n/**\n * Calls to Abortcontroller.abort(reason: any) will result in the\n * `reason` being thrown. This is not necessarily an error,\n * but extends error for better logging purposes.\n */\nclass AbortOperation extends Error {\n reason;\n constructor(reason) {\n super(reason);\n this.reason = reason;\n // Set the prototype explicitly\n Object.setPrototypeOf(this, AbortOperation.prototype);\n // Capture stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, AbortOperation);\n }\n }\n}\n\nvar OpTypeEnum;\n(function (OpTypeEnum) {\n OpTypeEnum[OpTypeEnum[\"CLEAR\"] = 1] = \"CLEAR\";\n OpTypeEnum[OpTypeEnum[\"MOVE\"] = 2] = \"MOVE\";\n OpTypeEnum[OpTypeEnum[\"PUT\"] = 3] = \"PUT\";\n OpTypeEnum[OpTypeEnum[\"REMOVE\"] = 4] = \"REMOVE\";\n})(OpTypeEnum || (OpTypeEnum = {}));\n/**\n * Used internally for sync buckets.\n */\nclass OpType {\n value;\n static fromJSON(jsonValue) {\n return new OpType(OpTypeEnum[jsonValue]);\n }\n constructor(value) {\n this.value = value;\n }\n toJSON() {\n return Object.entries(OpTypeEnum).find(([, value]) => value === this.value)[0];\n }\n}\n\nclass OplogEntry {\n op_id;\n op;\n checksum;\n subkey;\n object_type;\n object_id;\n data;\n static fromRow(row) {\n return new OplogEntry(row.op_id, OpType.fromJSON(row.op), row.checksum, row.subkey, row.object_type, row.object_id, row.data);\n }\n constructor(op_id, op, checksum, subkey, object_type, object_id, data) {\n this.op_id = op_id;\n this.op = op;\n this.checksum = checksum;\n this.subkey = subkey;\n this.object_type = object_type;\n this.object_id = object_id;\n this.data = data;\n }\n toJSON(fixedKeyEncoding = false) {\n return {\n op_id: this.op_id,\n op: this.op.toJSON(),\n object_type: this.object_type,\n object_id: this.object_id,\n checksum: this.checksum,\n data: this.data,\n // Older versions of the JS SDK used to always JSON.stringify here. That has always been wrong,\n // but we need to migrate gradually to not break existing databases.\n subkey: fixedKeyEncoding ? this.subkey : JSON.stringify(this.subkey)\n };\n }\n}\n\nclass SyncDataBucket {\n bucket;\n data;\n has_more;\n after;\n next_after;\n static fromRow(row) {\n return new SyncDataBucket(row.bucket, row.data.map((entry) => OplogEntry.fromRow(entry)), row.has_more ?? false, row.after, row.next_after);\n }\n constructor(bucket, data, \n /**\n * True if the response does not contain all the data for this bucket, and another request must be made.\n */\n has_more, \n /**\n * The `after` specified in the request.\n */\n after, \n /**\n * Use this for the next request.\n */\n next_after) {\n this.bucket = bucket;\n this.data = data;\n this.has_more = has_more;\n this.after = after;\n this.next_after = next_after;\n }\n toJSON(fixedKeyEncoding = false) {\n return {\n bucket: this.bucket,\n has_more: this.has_more,\n after: this.after,\n next_after: this.next_after,\n data: this.data.map((entry) => entry.toJSON(fixedKeyEncoding))\n };\n }\n}\n\nvar buffer = {};\n\nvar base64Js = {};\n\nvar hasRequiredBase64Js;\n\nfunction requireBase64Js () {\n\tif (hasRequiredBase64Js) return base64Js;\n\thasRequiredBase64Js = 1;\n\n\tbase64Js.byteLength = byteLength;\n\tbase64Js.toByteArray = toByteArray;\n\tbase64Js.fromByteArray = fromByteArray;\n\n\tvar lookup = [];\n\tvar revLookup = [];\n\tvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;\n\n\tvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\tfor (var i = 0, len = code.length; i < len; ++i) {\n\t lookup[i] = code[i];\n\t revLookup[code.charCodeAt(i)] = i;\n\t}\n\n\t// Support decoding URL-safe base64 strings, as Node.js does.\n\t// See: https://en.wikipedia.org/wiki/Base64#URL_applications\n\trevLookup['-'.charCodeAt(0)] = 62;\n\trevLookup['_'.charCodeAt(0)] = 63;\n\n\tfunction getLens (b64) {\n\t var len = b64.length;\n\n\t if (len % 4 > 0) {\n\t throw new Error('Invalid string. Length must be a multiple of 4')\n\t }\n\n\t // Trim off extra bytes after placeholder bytes are found\n\t // See: https://github.com/beatgammit/base64-js/issues/42\n\t var validLen = b64.indexOf('=');\n\t if (validLen === -1) validLen = len;\n\n\t var placeHoldersLen = validLen === len\n\t ? 0\n\t : 4 - (validLen % 4);\n\n\t return [validLen, placeHoldersLen]\n\t}\n\n\t// base64 is 4/3 + up to two characters of the original data\n\tfunction byteLength (b64) {\n\t var lens = getLens(b64);\n\t var validLen = lens[0];\n\t var placeHoldersLen = lens[1];\n\t return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n\t}\n\n\tfunction _byteLength (b64, validLen, placeHoldersLen) {\n\t return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n\t}\n\n\tfunction toByteArray (b64) {\n\t var tmp;\n\t var lens = getLens(b64);\n\t var validLen = lens[0];\n\t var placeHoldersLen = lens[1];\n\n\t var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));\n\n\t var curByte = 0;\n\n\t // if there are placeholders, only get up to the last complete 4 chars\n\t var len = placeHoldersLen > 0\n\t ? validLen - 4\n\t : validLen;\n\n\t var i;\n\t for (i = 0; i < len; i += 4) {\n\t tmp =\n\t (revLookup[b64.charCodeAt(i)] << 18) |\n\t (revLookup[b64.charCodeAt(i + 1)] << 12) |\n\t (revLookup[b64.charCodeAt(i + 2)] << 6) |\n\t revLookup[b64.charCodeAt(i + 3)];\n\t arr[curByte++] = (tmp >> 16) & 0xFF;\n\t arr[curByte++] = (tmp >> 8) & 0xFF;\n\t arr[curByte++] = tmp & 0xFF;\n\t }\n\n\t if (placeHoldersLen === 2) {\n\t tmp =\n\t (revLookup[b64.charCodeAt(i)] << 2) |\n\t (revLookup[b64.charCodeAt(i + 1)] >> 4);\n\t arr[curByte++] = tmp & 0xFF;\n\t }\n\n\t if (placeHoldersLen === 1) {\n\t tmp =\n\t (revLookup[b64.charCodeAt(i)] << 10) |\n\t (revLookup[b64.charCodeAt(i + 1)] << 4) |\n\t (revLookup[b64.charCodeAt(i + 2)] >> 2);\n\t arr[curByte++] = (tmp >> 8) & 0xFF;\n\t arr[curByte++] = tmp & 0xFF;\n\t }\n\n\t return arr\n\t}\n\n\tfunction tripletToBase64 (num) {\n\t return lookup[num >> 18 & 0x3F] +\n\t lookup[num >> 12 & 0x3F] +\n\t lookup[num >> 6 & 0x3F] +\n\t lookup[num & 0x3F]\n\t}\n\n\tfunction encodeChunk (uint8, start, end) {\n\t var tmp;\n\t var output = [];\n\t for (var i = start; i < end; i += 3) {\n\t tmp =\n\t ((uint8[i] << 16) & 0xFF0000) +\n\t ((uint8[i + 1] << 8) & 0xFF00) +\n\t (uint8[i + 2] & 0xFF);\n\t output.push(tripletToBase64(tmp));\n\t }\n\t return output.join('')\n\t}\n\n\tfunction fromByteArray (uint8) {\n\t var tmp;\n\t var len = uint8.length;\n\t var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes\n\t var parts = [];\n\t var maxChunkLength = 16383; // must be multiple of 3\n\n\t // go through the array every three bytes, we'll deal with trailing stuff later\n\t for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n\t parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));\n\t }\n\n\t // pad the end with zeros, but make sure to not forget the extra bytes\n\t if (extraBytes === 1) {\n\t tmp = uint8[len - 1];\n\t parts.push(\n\t lookup[tmp >> 2] +\n\t lookup[(tmp << 4) & 0x3F] +\n\t '=='\n\t );\n\t } else if (extraBytes === 2) {\n\t tmp = (uint8[len - 2] << 8) + uint8[len - 1];\n\t parts.push(\n\t lookup[tmp >> 10] +\n\t lookup[(tmp >> 4) & 0x3F] +\n\t lookup[(tmp << 2) & 0x3F] +\n\t '='\n\t );\n\t }\n\n\t return parts.join('')\n\t}\n\treturn base64Js;\n}\n\nvar ieee754 = {};\n\n/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */\n\nvar hasRequiredIeee754;\n\nfunction requireIeee754 () {\n\tif (hasRequiredIeee754) return ieee754;\n\thasRequiredIeee754 = 1;\n\tieee754.read = function (buffer, offset, isLE, mLen, nBytes) {\n\t var e, m;\n\t var eLen = (nBytes * 8) - mLen - 1;\n\t var eMax = (1 << eLen) - 1;\n\t var eBias = eMax >> 1;\n\t var nBits = -7;\n\t var i = isLE ? (nBytes - 1) : 0;\n\t var d = isLE ? -1 : 1;\n\t var s = buffer[offset + i];\n\n\t i += d;\n\n\t e = s & ((1 << (-nBits)) - 1);\n\t s >>= (-nBits);\n\t nBits += eLen;\n\t for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n\t m = e & ((1 << (-nBits)) - 1);\n\t e >>= (-nBits);\n\t nBits += mLen;\n\t for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n\t if (e === 0) {\n\t e = 1 - eBias;\n\t } else if (e === eMax) {\n\t return m ? NaN : ((s ? -1 : 1) * Infinity)\n\t } else {\n\t m = m + Math.pow(2, mLen);\n\t e = e - eBias;\n\t }\n\t return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n\t};\n\n\tieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n\t var e, m, c;\n\t var eLen = (nBytes * 8) - mLen - 1;\n\t var eMax = (1 << eLen) - 1;\n\t var eBias = eMax >> 1;\n\t var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);\n\t var i = isLE ? 0 : (nBytes - 1);\n\t var d = isLE ? 1 : -1;\n\t var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;\n\n\t value = Math.abs(value);\n\n\t if (isNaN(value) || value === Infinity) {\n\t m = isNaN(value) ? 1 : 0;\n\t e = eMax;\n\t } else {\n\t e = Math.floor(Math.log(value) / Math.LN2);\n\t if (value * (c = Math.pow(2, -e)) < 1) {\n\t e--;\n\t c *= 2;\n\t }\n\t if (e + eBias >= 1) {\n\t value += rt / c;\n\t } else {\n\t value += rt * Math.pow(2, 1 - eBias);\n\t }\n\t if (value * c >= 2) {\n\t e++;\n\t c /= 2;\n\t }\n\n\t if (e + eBias >= eMax) {\n\t m = 0;\n\t e = eMax;\n\t } else if (e + eBias >= 1) {\n\t m = ((value * c) - 1) * Math.pow(2, mLen);\n\t e = e + eBias;\n\t } else {\n\t m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);\n\t e = 0;\n\t }\n\t }\n\n\t for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n\t e = (e << mLen) | m;\n\t eLen += mLen;\n\t for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n\t buffer[offset + i - d] |= s * 128;\n\t};\n\treturn ieee754;\n}\n\n/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh <https://feross.org>\n * @license MIT\n */\n\nvar hasRequiredBuffer;\n\nfunction requireBuffer () {\n\tif (hasRequiredBuffer) return buffer;\n\thasRequiredBuffer = 1;\n\t(function (exports$1) {\n\n\t\tconst base64 = requireBase64Js();\n\t\tconst ieee754 = requireIeee754();\n\t\tconst customInspectSymbol =\n\t\t (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n\t\t ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n\t\t : null;\n\n\t\texports$1.Buffer = Buffer;\n\t\texports$1.SlowBuffer = SlowBuffer;\n\t\texports$1.INSPECT_MAX_BYTES = 50;\n\n\t\tconst K_MAX_LENGTH = 0x7fffffff;\n\t\texports$1.kMaxLength = K_MAX_LENGTH;\n\n\t\t/**\n\t\t * If `Buffer.TYPED_ARRAY_SUPPORT`:\n\t\t * === true Use Uint8Array implementation (fastest)\n\t\t * === false Print warning and recommend using `buffer` v4.x which has an Object\n\t\t * implementation (most compatible, even IE6)\n\t\t *\n\t\t * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n\t\t * Opera 11.6+, iOS 4.2+.\n\t\t *\n\t\t * We report that the browser does not support typed arrays if the are not subclassable\n\t\t * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n\t\t * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n\t\t * for __proto__ and has a buggy typed array implementation.\n\t\t */\n\t\tBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport();\n\n\t\tif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n\t\t typeof console.error === 'function') {\n\t\t console.error(\n\t\t 'This browser lacks typed array (Uint8Array) support which is required by ' +\n\t\t '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n\t\t );\n\t\t}\n\n\t\tfunction typedArraySupport () {\n\t\t // Can typed array instances can be augmented?\n\t\t try {\n\t\t const arr = new Uint8Array(1);\n\t\t const proto = { foo: function () { return 42 } };\n\t\t Object.setPrototypeOf(proto, Uint8Array.prototype);\n\t\t Object.setPrototypeOf(arr, proto);\n\t\t return arr.foo() === 42\n\t\t } catch (e) {\n\t\t return false\n\t\t }\n\t\t}\n\n\t\tObject.defineProperty(Buffer.prototype, 'parent', {\n\t\t enumerable: true,\n\t\t get: function () {\n\t\t if (!Buffer.isBuffer(this)) return undefined\n\t\t return this.buffer\n\t\t }\n\t\t});\n\n\t\tObject.defineProperty(Buffer.prototype, 'offset', {\n\t\t enumerable: true,\n\t\t get: function () {\n\t\t if (!Buffer.isBuffer(this)) return undefined\n\t\t return this.byteOffset\n\t\t }\n\t\t});\n\n\t\tfunction createBuffer (length) {\n\t\t if (length > K_MAX_LENGTH) {\n\t\t throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n\t\t }\n\t\t // Return an augmented `Uint8Array` instance\n\t\t const buf = new Uint8Array(length);\n\t\t Object.setPrototypeOf(buf, Buffer.prototype);\n\t\t return buf\n\t\t}\n\n\t\t/**\n\t\t * The Buffer constructor returns instances of `Uint8Array` that have their\n\t\t * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n\t\t * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n\t\t * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n\t\t * returns a single octet.\n\t\t *\n\t\t * The `Uint8Array` prototype remains unmodified.\n\t\t */\n\n\t\tfunction Buffer (arg, encodingOrOffset, length) {\n\t\t // Common case.\n\t\t if (typeof arg === 'number') {\n\t\t if (typeof encodingOrOffset === 'string') {\n\t\t throw new TypeError(\n\t\t 'The \"string\" argument must be of type string. Received type number'\n\t\t )\n\t\t }\n\t\t return allocUnsafe(arg)\n\t\t }\n\t\t return from(arg, encodingOrOffset, length)\n\t\t}\n\n\t\tBuffer.poolSize = 8192; // not used by this implementation\n\n\t\tfunction from (value, encodingOrOffset, length) {\n\t\t if (typeof value === 'string') {\n\t\t return fromString(value, encodingOrOffset)\n\t\t }\n\n\t\t if (ArrayBuffer.isView(value)) {\n\t\t return fromArrayView(value)\n\t\t }\n\n\t\t if (value == null) {\n\t\t throw new TypeError(\n\t\t 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n\t\t 'or Array-like Object. Received type ' + (typeof value)\n\t\t )\n\t\t }\n\n\t\t if (isInstance(value, ArrayBuffer) ||\n\t\t (value && isInstance(value.buffer, ArrayBuffer))) {\n\t\t return fromArrayBuffer(value, encodingOrOffset, length)\n\t\t }\n\n\t\t if (typeof SharedArrayBuffer !== 'undefined' &&\n\t\t (isInstance(value, SharedArrayBuffer) ||\n\t\t (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n\t\t return fromArrayBuffer(value, encodingOrOffset, length)\n\t\t }\n\n\t\t if (typeof value === 'number') {\n\t\t throw new TypeError(\n\t\t 'The \"value\" argument must not be of type number. Received type number'\n\t\t )\n\t\t }\n\n\t\t const valueOf = value.valueOf && value.valueOf();\n\t\t if (valueOf != null && valueOf !== value) {\n\t\t return Buffer.from(valueOf, encodingOrOffset, length)\n\t\t }\n\n\t\t const b = fromObject(value);\n\t\t if (b) return b\n\n\t\t if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n\t\t typeof value[Symbol.toPrimitive] === 'function') {\n\t\t return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n\t\t }\n\n\t\t throw new TypeError(\n\t\t 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n\t\t 'or Array-like Object. Received type ' + (typeof value)\n\t\t )\n\t\t}\n\n\t\t/**\n\t\t * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n\t\t * if value is a number.\n\t\t * Buffer.from(str[, encoding])\n\t\t * Buffer.from(array)\n\t\t * Buffer.from(buffer)\n\t\t * Buffer.from(arrayBuffer[, byteOffset[, length]])\n\t\t **/\n\t\tBuffer.from = function (value, encodingOrOffset, length) {\n\t\t return from(value, encodingOrOffset, length)\n\t\t};\n\n\t\t// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n\t\t// https://github.com/feross/buffer/pull/148\n\t\tObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);\n\t\tObject.setPrototypeOf(Buffer, Uint8Array);\n\n\t\tfunction assertSize (size) {\n\t\t if (typeof size !== 'number') {\n\t\t throw new TypeError('\"size\" argument must be of type number')\n\t\t } else if (size < 0) {\n\t\t throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n\t\t }\n\t\t}\n\n\t\tfunction alloc (size, fill, encoding) {\n\t\t assertSize(size);\n\t\t if (size <= 0) {\n\t\t return createBuffer(size)\n\t\t }\n\t\t if (fill !== undefined) {\n\t\t // Only pay attention to encoding if it's a string. This\n\t\t // prevents accidentally sending in a number that would\n\t\t // be interpreted as a start offset.\n\t\t return typeof encoding === 'string'\n\t\t ? createBuffer(size).fill(fill, encoding)\n\t\t : createBuffer(size).fill(fill)\n\t\t }\n\t\t return createBuffer(size)\n\t\t}\n\n\t\t/**\n\t\t * Creates a new filled Buffer instance.\n\t\t * alloc(size[, fill[, encoding]])\n\t\t **/\n\t\tBuffer.alloc = function (size, fill, encoding) {\n\t\t return alloc(size, fill, encoding)\n\t\t};\n\n\t\tfunction allocUnsafe (size) {\n\t\t assertSize(size);\n\t\t return createBuffer(size < 0 ? 0 : checked(size) | 0)\n\t\t}\n\n\t\t/**\n\t\t * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n\t\t * */\n\t\tBuffer.allocUnsafe = function (size) {\n\t\t return allocUnsafe(size)\n\t\t};\n\t\t/**\n\t\t * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n\t\t */\n\t\tBuffer.allocUnsafeSlow = function (size) {\n\t\t return allocUnsafe(size)\n\t\t};\n\n\t\tfunction fromString (string, encoding) {\n\t\t if (typeof encoding !== 'string' || encoding === '') {\n\t\t encoding = 'utf8';\n\t\t }\n\n\t\t if (!Buffer.isEncoding(encoding)) {\n\t\t throw new TypeError('Unknown encoding: ' + encoding)\n\t\t }\n\n\t\t const length = byteLength(string, encoding) | 0;\n\t\t let buf = createBuffer(length);\n\n\t\t const actual = buf.write(string, encoding);\n\n\t\t if (actual !== length) {\n\t\t // Writing a hex string, for example, that contains invalid characters will\n\t\t // cause everything after the first invalid character to be ignored. (e.g.\n\t\t // 'abxxcd' will be treated as 'ab')\n\t\t buf = buf.slice(0, actual);\n\t\t }\n\n\t\t return buf\n\t\t}\n\n\t\tfunction fromArrayLike (array) {\n\t\t const length = array.length < 0 ? 0 : checked(array.length) | 0;\n\t\t const buf = createBuffer(length);\n\t\t for (let i = 0; i < length; i += 1) {\n\t\t buf[i] = array[i] & 255;\n\t\t }\n\t\t return buf\n\t\t}\n\n\t\tfunction fromArrayView (arrayView) {\n\t\t if (isInstance(arrayView, Uint8Array)) {\n\t\t const copy = new Uint8Array(arrayView);\n\t\t return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n\t\t }\n\t\t return fromArrayLike(arrayView)\n\t\t}\n\n\t\tfunction fromArrayBuffer (array, byteOffset, length) {\n\t\t if (byteOffset < 0 || array.byteLength < byteOffset) {\n\t\t throw new RangeError('\"offset\" is outside of buffer bounds')\n\t\t }\n\n\t\t if (array.byteLength < byteOffset + (length || 0)) {\n\t\t throw new RangeError('\"length\" is outside of buffer bounds')\n\t\t }\n\n\t\t let buf;\n\t\t if (byteOffset === undefined && length === undefined) {\n\t\t buf = new Uint8Array(array);\n\t\t } else if (length === undefined) {\n\t\t buf = new Uint8Array(array, byteOffset);\n\t\t } else {\n\t\t buf = new Uint8Array(array, byteOffset, length);\n\t\t }\n\n\t\t // Return an augmented `Uint8Array` instance\n\t\t Object.setPrototypeOf(buf, Buffer.prototype);\n\n\t\t return buf\n\t\t}\n\n\t\tfunction fromObject (obj) {\n\t\t if (Buffer.isBuffer(obj)) {\n\t\t const len = checked(obj.length) | 0;\n\t\t const buf = createBuffer(len);\n\n\t\t if (buf.length === 0) {\n\t\t return buf\n\t\t }\n\n\t\t obj.copy(buf, 0, 0, len);\n\t\t return buf\n\t\t }\n\n\t\t if (obj.length !== undefined) {\n\t\t if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n\t\t return createBuffer(0)\n\t\t }\n\t\t return fromArrayLike(obj)\n\t\t }\n\n\t\t if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n\t\t return fromArrayLike(obj.data)\n\t\t }\n\t\t}\n\n\t\tfunction checked (length) {\n\t\t // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n\t\t // length is NaN (which is otherwise coerced to zero.)\n\t\t if (length >= K_MAX_LENGTH) {\n\t\t throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n\t\t 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n\t\t }\n\t\t return length | 0\n\t\t}\n\n\t\tfunction SlowBuffer (length) {\n\t\t if (+length != length) { // eslint-disable-line eqeqeq\n\t\t length = 0;\n\t\t }\n\t\t return Buffer.alloc(+length)\n\t\t}\n\n\t\tBuffer.isBuffer = function isBuffer (b) {\n\t\t return b != null && b._isBuffer === true &&\n\t\t b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n\t\t};\n\n\t\tBuffer.compare = function compare (a, b) {\n\t\t if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);\n\t\t if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);\n\t\t if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n\t\t throw new TypeError(\n\t\t 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n\t\t )\n\t\t }\n\n\t\t if (a === b) return 0\n\n\t\t let x = a.length;\n\t\t let y = b.length;\n\n\t\t for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n\t\t if (a[i] !== b[i]) {\n\t\t x = a[i];\n\t\t y = b[i];\n\t\t break\n\t\t }\n\t\t }\n\n\t\t if (x < y) return -1\n\t\t if (y < x) return 1\n\t\t return 0\n\t\t};\n\n\t\tBuffer.isEncoding = function isEncoding (encoding) {\n\t\t switch (String(encoding).toLowerCase()) {\n\t\t case 'hex':\n\t\t case 'utf8':\n\t\t case 'utf-8':\n\t\t case 'ascii':\n\t\t case 'latin1':\n\t\t case 'binary':\n\t\t case 'base64':\n\t\t case 'ucs2':\n\t\t case 'ucs-2':\n\t\t case 'utf16le':\n\t\t case 'utf-16le':\n\t\t return true\n\t\t default:\n\t\t return false\n\t\t }\n\t\t};\n\n\t\tBuffer.concat = function concat (list, length) {\n\t\t if (!Array.isArray(list)) {\n\t\t throw new TypeError('\"list\" argument must be an Array of Buffers')\n\t\t }\n\n\t\t if (list.length === 0) {\n\t\t return Buffer.alloc(0)\n\t\t }\n\n\t\t let i;\n\t\t if (length === undefined) {\n\t\t length = 0;\n\t\t for (i = 0; i < list.length; ++i) {\n\t\t length += list[i].length;\n\t\t }\n\t\t }\n\n\t\t const buffer = Buffer.allocUnsafe(length);\n\t\t let pos = 0;\n\t\t for (i = 0; i < list.length; ++i) {\n\t\t let buf = list[i];\n\t\t if (isInstance(buf, Uint8Array)) {\n\t\t if (pos + buf.length > buffer.length) {\n\t\t if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf);\n\t\t buf.copy(buffer, pos);\n\t\t } else {\n\t\t Uint8Array.prototype.set.call(\n\t\t buffer,\n\t\t buf,\n\t\t pos\n\t\t );\n\t\t }\n\t\t } else if (!Buffer.isBuffer(buf)) {\n\t\t throw new TypeError('\"list\" argument must be an Array of Buffers')\n\t\t } else {\n\t\t buf.copy(buffer, pos);\n\t\t }\n\t\t pos += buf.length;\n\t\t }\n\t\t return buffer\n\t\t};\n\n\t\tfunction byteLength (string, encoding) {\n\t\t if (Buffer.isBuffer(string)) {\n\t\t return string.length\n\t\t }\n\t\t if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n\t\t return string.byteLength\n\t\t }\n\t\t if (typeof string !== 'string') {\n\t\t throw new TypeError(\n\t\t 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n\t\t 'Received type ' + typeof string\n\t\t )\n\t\t }\n\n\t\t const len = string.length;\n\t\t const mustMatch = (arguments.length > 2 && arguments[2] === true);\n\t\t if (!mustMatch && len === 0) return 0\n\n\t\t // Use a for loop to avoid recursion\n\t\t let loweredCase = false;\n\t\t for (;;) {\n\t\t switch (encoding) {\n\t\t case 'ascii':\n\t\t case 'latin1':\n\t\t case 'binary':\n\t\t return len\n\t\t case 'utf8':\n\t\t case 'utf-8':\n\t\t return utf8ToBytes(string).length\n\t\t case 'ucs2':\n\t\t case 'ucs-2':\n\t\t case 'utf16le':\n\t\t case 'utf-16le':\n\t\t return len * 2\n\t\t case 'hex':\n\t\t return len >>> 1\n\t\t case 'base64':\n\t\t return base64ToBytes(string).length\n\t\t default:\n\t\t if (loweredCase) {\n\t\t return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n\t\t }\n\t\t encoding = ('' + encoding).toLowerCase();\n\t\t loweredCase = true;\n\t\t }\n\t\t }\n\t\t}\n\t\tBuffer.byteLength = byteLength;\n\n\t\tfunction slowToString (encoding, start, end) {\n\t\t let loweredCase = false;\n\n\t\t // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n\t\t // property of a typed array.\n\n\t\t // This behaves neither like String nor Uint8Array in that we set start/end\n\t\t // to their upper/lower bounds if the value passed is out of range.\n\t\t // undefined is handled specially as per ECMA-262 6th Edition,\n\t\t // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n\t\t if (start === undefined || start < 0) {\n\t\t start = 0;\n\t\t }\n\t\t // Return early if start > this.length. Done here to prevent potential uint32\n\t\t // coercion fail below.\n\t\t if (start > this.length) {\n\t\t return ''\n\t\t }\n\n\t\t if (end === undefined || end > this.length) {\n\t\t end = this.length;\n\t\t }\n\n\t\t if (end <= 0) {\n\t\t return ''\n\t\t }\n\n\t\t // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n\t\t end >>>= 0;\n\t\t start >>>= 0;\n\n\t\t if (end <= start) {\n\t\t return ''\n\t\t }\n\n\t\t if (!encoding) encoding = 'utf8';\n\n\t\t while (true) {\n\t\t switch (encoding) {\n\t\t case 'hex':\n\t\t return hexSlice(this, start, end)\n\n\t\t case 'utf8':\n\t\t case 'utf-8':\n\t\t return utf8Slice(this, start, end)\n\n\t\t case 'ascii':\n\t\t return asciiSlice(this, start, end)\n\n\t\t case 'latin1':\n\t\t case 'binary':\n\t\t return latin1Slice(this, start, end)\n\n\t\t case 'base64':\n\t\t return base64Slice(this, start, end)\n\n\t\t case 'ucs2':\n\t\t case 'ucs-2':\n\t\t case 'utf16le':\n\t\t case 'utf-16le':\n\t\t return utf16leSlice(this, start, end)\n\n\t\t default:\n\t\t if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n\t\t encoding = (encoding + '').toLowerCase();\n\t\t loweredCase = true;\n\t\t }\n\t\t }\n\t\t}\n\n\t\t// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n\t\t// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n\t\t// reliably in a browserify context because there could be multiple different\n\t\t// copies of the 'buffer' package in use. This method works even for Buffer\n\t\t// instances that were created from another copy of the `buffer` package.\n\t\t// See: https://github.com/feross/buffer/issues/154\n\t\tBuffer.prototype._isBuffer = true;\n\n\t\tfunction swap (b, n, m) {\n\t\t const i = b[n];\n\t\t b[n] = b[m];\n\t\t b[m] = i;\n\t\t}\n\n\t\tBuffer.prototype.swap16 = function swap16 () {\n\t\t const len = this.length;\n\t\t if (len % 2 !== 0) {\n\t\t throw new RangeError('Buffer size must be a multiple of 16-bits')\n\t\t }\n\t\t for (let i = 0; i < len; i += 2) {\n\t\t swap(this, i, i + 1);\n\t\t }\n\t\t return this\n\t\t};\n\n\t\tBuffer.prototype.swap32 = function swap32 () {\n\t\t const len = this.length;\n\t\t if (len % 4 !== 0) {\n\t\t throw new RangeError('Buffer size must be a multiple of 32-bits')\n\t\t }\n\t\t for (let i = 0; i < len; i += 4) {\n\t\t swap(this, i, i + 3);\n\t\t swap(this, i + 1, i + 2);\n\t\t }\n\t\t return this\n\t\t};\n\n\t\tBuffer.prototype.swap64 = function swap64 () {\n\t\t const len = this.length;\n\t\t if (len % 8 !== 0) {\n\t\t throw new RangeError('Buffer size must be a multiple of 64-bits')\n\t\t }\n\t\t for (let i = 0; i < len; i += 8) {\n\t\t swap(this, i, i + 7);\n\t\t swap(this, i + 1, i + 6);\n\t\t swap(this, i + 2, i + 5);\n\t\t swap(this, i + 3, i + 4);\n\t\t }\n\t\t return this\n\t\t};\n\n\t\tBuffer.prototype.toString = function toString () {\n\t\t const length = this.length;\n\t\t if (length === 0) return ''\n\t\t if (arguments.length === 0) return utf8Slice(this, 0, length)\n\t\t return slowToString.apply(this, arguments)\n\t\t};\n\n\t\tBuffer.prototype.toLocaleString = Buffer.prototype.toString;\n\n\t\tBuffer.prototype.equals = function equals (b) {\n\t\t if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n\t\t if (this === b) return true\n\t\t return Buffer.compare(this, b) === 0\n\t\t};\n\n\t\tBuffer.prototype.inspect = function inspect () {\n\t\t let str = '';\n\t\t const max = exports$1.INSPECT_MAX_BYTES;\n\t\t str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();\n\t\t if (this.length > max) str += ' ... ';\n\t\t return '<Buffer ' + str + '>'\n\t\t};\n\t\tif (customInspectSymbol) {\n\t\t Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;\n\t\t}\n\n\t\tBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n\t\t if (isInstance(target, Uint8Array)) {\n\t\t target = Buffer.from(target, target.offset, target.byteLength);\n\t\t }\n\t\t if (!Buffer.isBuffer(target)) {\n\t\t throw new TypeError(\n\t\t 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n\t\t 'Received type ' + (typeof target)\n\t\t )\n\t\t }\n\n\t\t if (start === undefined) {\n\t\t start = 0;\n\t\t }\n\t\t if (end === undefined) {\n\t\t end = target ? target.length : 0;\n\t\t }\n\t\t if (thisStart === undefined) {\n\t\t thisStart = 0;\n\t\t }\n\t\t if (thisEnd === undefined) {\n\t\t thisEnd = this.length;\n\t\t }\n\n\t\t if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n\t\t throw new RangeError('out of range index')\n\t\t }\n\n\t\t if (thisStart >= thisEnd && start >= end) {\n\t\t return 0\n\t\t }\n\t\t if (thisStart >= thisEnd) {\n\t\t return -1\n\t\t }\n\t\t if (start >= end) {\n\t\t return 1\n\t\t }\n\n\t\t start >>>= 0;\n\t\t end >>>= 0;\n\t\t thisStart >>>= 0;\n\t\t thisEnd >>>= 0;\n\n\t\t if (this === target) return 0\n\n\t\t let x = thisEnd - thisStart;\n\t\t let y = end - start;\n\t\t const len = Math.min(x, y);\n\n\t\t const thisCopy = this.slice(thisStart, thisEnd);\n\t\t const targetCopy = target.slice(start, end);\n\n\t\t for (let i = 0; i < len; ++i) {\n\t\t if (thisCopy[i] !== targetCopy[i]) {\n\t\t x = thisCopy[i];\n\t\t y = targetCopy[i];\n\t\t break\n\t\t }\n\t\t }\n\n\t\t if (x < y) return -1\n\t\t if (y < x) return 1\n\t\t return 0\n\t\t};\n\n\t\t// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n\t\t// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n\t\t//\n\t\t// Arguments:\n\t\t// - buffer - a Buffer to search\n\t\t// - val - a string, Buffer, or number\n\t\t// - byteOffset - an index into `buffer`; will be clamped to an int32\n\t\t// - encoding - an optional encoding, relevant is val is a string\n\t\t// - dir - true for indexOf, false for lastIndexOf\n\t\tfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n\t\t // Empty buffer means no match\n\t\t if (buffer.length === 0) return -1\n\n\t\t // Normalize byteOffset\n\t\t if (typeof byteOffset === 'string') {\n\t\t encoding = byteOffset;\n\t\t byteOffset = 0;\n\t\t } else if (byteOffset > 0x7fffffff) {\n\t\t byteOffset = 0x7fffffff;\n\t\t } else if (byteOffset < -2147483648) {\n\t\t byteOffset = -2147483648;\n\t\t }\n\t\t byteOffset = +byteOffset; // Coerce to Number.\n\t\t if (numberIsNaN(byteOffset)) {\n\t\t // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n\t\t byteOffset = dir ? 0 : (buffer.length - 1);\n\t\t }\n\n\t\t // Normalize byteOffset: negative offsets start from the end of the buffer\n\t\t if (byteOffset < 0) byteOffset = buffer.length + byteOffset;\n\t\t if (byteOffset >= buffer.length) {\n\t\t if (dir) return -1\n\t\t else byteOffset = buffer.length - 1;\n\t\t } else if (byteOffset < 0) {\n\t\t if (dir) byteOffset = 0;\n\t\t else return -1\n\t\t }\n\n\t\t // Normalize val\n\t\t if (typeof val === 'string') {\n\t\t val = Buffer.from(val, encoding);\n\t\t }\n\n\t\t // Finally, search either indexOf (if dir is true) or lastIndexOf\n\t\t if (Buffer.isBuffer(val)) {\n\t\t // Special case: looking for empty string/buffer always fails\n\t\t if (val.length === 0) {\n\t\t return -1\n\t\t }\n\t\t return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n\t\t } else if (typeof val === 'number') {\n\t\t val = val & 0xFF; // Search for a byte value [0-255]\n\t\t if (typeof Uint8Array.prototype.indexOf === 'function') {\n\t\t if (dir) {\n\t\t return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n\t\t } else {\n\t\t return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n\t\t }\n\t\t }\n\t\t return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n\t\t }\n\n\t\t throw new TypeError('val must be string, number or Buffer')\n\t\t}\n\n\t\tfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n\t\t let indexSize = 1;\n\t\t let arrLength = arr.length;\n\t\t let valLength = val.length;\n\n\t\t if (encoding !== undefined) {\n\t\t encoding = String(encoding).toLowerCase();\n\t\t if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n\t\t encoding === 'utf16le' || encoding === 'utf-16le') {\n\t\t if (arr.length < 2 || val.length < 2) {\n\t\t return -1\n\t\t }\n\t\t indexSize = 2;\n\t\t arrLength /= 2;\n\t\t valLength /= 2;\n\t\t byteOffset /= 2;\n\t\t }\n\t\t }\n\n\t\t function read (buf, i) {\n\t\t if (indexSize === 1) {\n\t\t return buf[i]\n\t\t } else {\n\t\t return buf.readUInt16BE(i * indexSize)\n\t\t }\n\t\t }\n\n\t\t let i;\n\t\t if (dir) {\n\t\t let foundIndex = -1;\n\t\t for (i = byteOffset; i < arrLength; i++) {\n\t\t if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n\t\t if (foundIndex === -1) foundIndex = i;\n\t\t if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n\t\t } else {\n\t\t if (foundIndex !== -1) i -= i - foundIndex;\n\t\t foundIndex = -1;\n\t\t }\n\t\t }\n\t\t } else {\n\t\t if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;\n\t\t for (i = byteOffset; i >= 0; i--) {\n\t\t let found = true;\n\t\t for (let j = 0; j < valLength; j++) {\n\t\t if (read(arr, i + j) !== read(val, j)) {\n\t\t found = false;\n\t\t break\n\t\t }\n\t\t }\n\t\t if (found) return i\n\t\t }\n\t\t }\n\n\t\t return -1\n\t\t}\n\n\t\tBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n\t\t return this.indexOf(val, byteOffset, encoding) !== -1\n\t\t};\n\n\t\tBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n\t\t return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n\t\t};\n\n\t\tBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n\t\t return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n\t\t};\n\n\t\tfunction hexWrite (buf, string, offset, length) {\n\t\t offset = Number(offset) || 0;\n\t\t const remaining = buf.length - offset;\n\t\t if (!length) {\n\t\t length = remaining;\n\t\t } else {\n\t\t length = Number(length);\n\t\t if (length > remaining) {\n\t\t length = remaining;\n\t\t }\n\t\t }\n\n\t\t const strLen = string.length;\n\n\t\t if (length > strLen / 2) {\n\t\t length = strLen / 2;\n\t\t }\n\t\t let i;\n\t\t for (i = 0; i < length; ++i) {\n\t\t const parsed = parseInt(string.substr(i * 2, 2), 16);\n\t\t if (numberIsNaN(parsed)) return i\n\t\t buf[offset + i] = parsed;\n\t\t }\n\t\t return i\n\t\t}\n\n\t\tfunction utf8Write (buf, string, offset, length) {\n\t\t return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n\t\t}\n\n\t\tfunction asciiWrite (buf, string, offset, length) {\n\t\t return blitBuffer(asciiToBytes(string), buf, offset, length)\n\t\t}\n\n\t\tfunction base64Write (buf, string, offset, length) {\n\t\t return blitBuffer(base64ToBytes(string), buf, offset, length)\n\t\t}\n\n\t\tfunction ucs2Write (buf, string, offset, length) {\n\t\t return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n\t\t}\n\n\t\tBuffer.prototype.write = function write (string, offset, length, encoding) {\n\t\t // Buffer#write(string)\n\t\t if (offset === undefined) {\n\t\t encoding = 'utf8';\n\t\t length = this.length;\n\t\t offset = 0;\n\t\t // Buffer#write(string, encoding)\n\t\t } else if (length === undefined && typeof offset === 'string') {\n\t\t encoding = offset;\n\t\t length = this.length;\n\t\t offset = 0;\n\t\t // Buffer#write(string, offset[, length][, encoding])\n\t\t } else if (isFinite(offset)) {\n\t\t offset = offset >>> 0;\n\t\t if (isFinite(length)) {\n\t\t length = length >>> 0;\n\t\t if (encoding === undefined) encoding = 'utf8';\n\t\t } else {\n\t\t encoding = length;\n\t\t length = undefined;\n\t\t }\n\t\t } else {\n\t\t throw new Error(\n\t\t 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n\t\t )\n\t\t }\n\n\t\t const remaining = this.length - offset;\n\t\t if (length === undefined || length > remaining) length = remaining;\n\n\t\t if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n\t\t throw new RangeError('Attempt to write outside buffer bounds')\n\t\t }\n\n\t\t if (!encoding) encoding = 'utf8';\n\n\t\t let loweredCase = false;\n\t\t for (;;) {\n\t\t switch (encoding) {\n\t\t case 'hex':\n\t\t return hexWrite(this, string, offset, length)\n\n\t\t case 'utf8':\n\t\t case 'utf-8':\n\t\t return utf8Write(this, string, offset, length)\n\n\t\t case 'ascii':\n\t\t case 'latin1':\n\t\t case 'binary':\n\t\t return asciiWrite(this, string, offset, length)\n\n\t\t case 'base64':\n\t\t // Warning: maxLength not taken into account in base64Write\n\t\t return base64Write(this, string, offset, length)\n\n\t\t case 'ucs2':\n\t\t case 'ucs-2':\n\t\t case 'utf16le':\n\t\t case 'utf-16le':\n\t\t return ucs2Write(this, string, offset, length)\n\n\t\t default:\n\t\t if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n\t\t encoding = ('' + encoding).toLowerCase();\n\t\t loweredCase = true;\n\t\t }\n\t\t }\n\t\t};\n\n\t\tBuffer.prototype.toJSON = function toJSON () {\n\t\t return {\n\t\t type: 'Buffer',\n\t\t data: Array.prototype.slice.call(this._arr || this, 0)\n\t\t }\n\t\t};\n\n\t\tfunction base64Slice (buf, start, end) {\n\t\t if (start === 0 && end === buf.length) {\n\t\t return base64.fromByteArray(buf)\n\t\t } else {\n\t\t return base64.fromByteArray(buf.slice(start, end))\n\t\t }\n\t\t}\n\n\t\tfunction utf8Slice (buf, start, end) {\n\t\t end = Math.min(buf.length, end);\n\t\t const res = [];\n\n\t\t let i = start;\n\t\t while (i < end) {\n\t\t const firstByte = buf[i];\n\t\t let codePoint = null;\n\t\t let bytesPerSequence = (firstByte > 0xEF)\n\t\t ? 4\n\t\t : (firstByte > 0xDF)\n\t\t ? 3\n\t\t : (firstByte > 0xBF)\n\t\t ? 2\n\t\t : 1;\n\n\t\t if (i + bytesPerSequence <= end) {\n\t\t let secondByte, thirdByte, fourthByte, tempCodePoint;\n\n\t\t switch (bytesPerSequence) {\n\t\t case 1:\n\t\t if (firstByte < 0x80) {\n\t\t codePoint = firstByte;\n\t\t }\n\t\t break\n\t\t case 2:\n\t\t secondByte = buf[i + 1];\n\t\t if ((secondByte & 0xC0) === 0x80) {\n\t\t tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);\n\t\t if (tempCodePoint > 0x7F) {\n\t\t codePoint = tempCodePoint;\n\t\t }\n\t\t }\n\t\t break\n\t\t case 3:\n\t\t secondByte = buf[i + 1];\n\t\t thirdByte = buf[i + 2];\n\t\t if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n\t\t tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);\n\t\t if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n\t\t codePoint = tempCodePoint;\n\t\t }\n\t\t }\n\t\t break\n\t\t case 4:\n\t\t secondByte = buf[i + 1];\n\t\t thirdByte = buf[i + 2];\n\t\t fourthByte = buf[i + 3];\n\t\t if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n\t\t tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);\n\t\t if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n\t\t codePoint = tempCodePoint;\n\t\t }\n\t\t }\n\t\t }\n\t\t }\n\n\t\t if (codePoint === null) {\n\t\t // we did not generate a valid codePoint so insert a\n\t\t // replacement char (U+FFFD) and advance only 1 byte\n\t\t codePoint = 0xFFFD;\n\t\t bytesPerSequence = 1;\n\t\t } else if (codePoint > 0xFFFF) {\n\t\t // encode to utf16 (surrogate pair dance)\n\t\t codePoint -= 0x10000;\n\t\t res.push(codePoint >>> 10 & 0x3FF | 0xD800);\n\t\t codePoint = 0xDC00 | codePoint & 0x3FF;\n\t\t }\n\n\t\t res.push(codePoint);\n\t\t i += bytesPerSequence;\n\t\t }\n\n\t\t return decodeCodePointsArray(res)\n\t\t}\n\n\t\t// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n\t\t// the lowest limit is Chrome, with 0x10000 args.\n\t\t// We go 1 magnitude less, for safety\n\t\tconst MAX_ARGUMENTS_LENGTH = 0x1000;\n\n\t\tfunction decodeCodePointsArray (codePoints) {\n\t\t const len = codePoints.length;\n\t\t if (len <= MAX_ARGUMENTS_LENGTH) {\n\t\t return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n\t\t }\n\n\t\t // Decode in chunks to avoid \"call stack size exceeded\".\n\t\t let res = '';\n\t\t let i = 0;\n\t\t while (i < len) {\n\t\t res += String.fromCharCode.apply(\n\t\t String,\n\t\t codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n\t\t );\n\t\t }\n\t\t return res\n\t\t}\n\n\t\tfunction asciiSlice (buf, start, end) {\n\t\t let ret = '';\n\t\t end = Math.min(buf.length, end);\n\n\t\t for (let i = start; i < end; ++i) {\n\t\t ret += String.fromCharCode(buf[i] & 0x7F);\n\t\t }\n\t\t return ret\n\t\t}\n\n\t\tfunction latin1Slice (buf, start, end) {\n\t\t let ret = '';\n\t\t end = Math.min(buf.length, end);\n\n\t\t for (let i = start; i < end; ++i) {\n\t\t ret += String.fromCharCode(buf[i]);\n\t\t }\n\t\t return ret\n\t\t}\n\n\t\tfunction hexSlice (buf, start, end) {\n\t\t const len = buf.length;\n\n\t\t if (!start || start < 0) start = 0;\n\t\t if (!end || end < 0 || end > len) end = len;\n\n\t\t let out = '';\n\t\t for (let i = start; i < end; ++i) {\n\t\t out += hexSliceLookupTable[buf[i]];\n\t\t }\n\t\t return out\n\t\t}\n\n\t\tfunction utf16leSlice (buf, start, end) {\n\t\t const bytes = buf.slice(start, end);\n\t\t let res = '';\n\t\t // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n\t\t for (let i = 0; i < bytes.length - 1; i += 2) {\n\t\t res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256));\n\t\t }\n\t\t return res\n\t\t}\n\n\t\tBuffer.prototype.slice = function slice (start, end) {\n\t\t const len = this.length;\n\t\t start = ~~start;\n\t\t end = end === undefined ? len : ~~end;\n\n\t\t if (start < 0) {\n\t\t start += len;\n\t\t if (start < 0) start = 0;\n\t\t } else if (start > len) {\n\t\t start = len;\n\t\t }\n\n\t\t if (end < 0) {\n\t\t end += len;\n\t\t if (end < 0) end = 0;\n\t\t } else if (end > len) {\n\t\t end = len;\n\t\t }\n\n\t\t if (end < start) end = start;\n\n\t\t const newBuf = this.subarray(start, end);\n\t\t // Return an augmented `Uint8Array` instance\n\t\t Object.setPrototypeOf(newBuf, Buffer.prototype);\n\n\t\t return newBuf\n\t\t};\n\n\t\t/*\n\t\t * Need to make sure that buffer isn't trying to write out of bounds.\n\t\t */\n\t\tfunction checkOffset (offset, ext, length) {\n\t\t if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n\t\t if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n\t\t}\n\n\t\tBuffer.prototype.readUintLE =\n\t\tBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t byteLength = byteLength >>> 0;\n\t\t if (!noAssert) checkOffset(offset, byteLength, this.length);\n\n\t\t let val = this[offset];\n\t\t let mul = 1;\n\t\t let i = 0;\n\t\t while (++i < byteLength && (mul *= 0x100)) {\n\t\t val += this[offset + i] * mul;\n\t\t }\n\n\t\t return val\n\t\t};\n\n\t\tBuffer.prototype.readUintBE =\n\t\tBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t byteLength = byteLength >>> 0;\n\t\t if (!noAssert) {\n\t\t checkOffset(offset, byteLength, this.length);\n\t\t }\n\n\t\t let val = this[offset + --byteLength];\n\t\t let mul = 1;\n\t\t while (byteLength > 0 && (mul *= 0x100)) {\n\t\t val += this[offset + --byteLength] * mul;\n\t\t }\n\n\t\t return val\n\t\t};\n\n\t\tBuffer.prototype.readUint8 =\n\t\tBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 1, this.length);\n\t\t return this[offset]\n\t\t};\n\n\t\tBuffer.prototype.readUint16LE =\n\t\tBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 2, this.length);\n\t\t return this[offset] | (this[offset + 1] << 8)\n\t\t};\n\n\t\tBuffer.prototype.readUint16BE =\n\t\tBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 2, this.length);\n\t\t return (this[offset] << 8) | this[offset + 1]\n\t\t};\n\n\t\tBuffer.prototype.readUint32LE =\n\t\tBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 4, this.length);\n\n\t\t return ((this[offset]) |\n\t\t (this[offset + 1] << 8) |\n\t\t (this[offset + 2] << 16)) +\n\t\t (this[offset + 3] * 0x1000000)\n\t\t};\n\n\t\tBuffer.prototype.readUint32BE =\n\t\tBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 4, this.length);\n\n\t\t return (this[offset] * 0x1000000) +\n\t\t ((this[offset + 1] << 16) |\n\t\t (this[offset + 2] << 8) |\n\t\t this[offset + 3])\n\t\t};\n\n\t\tBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n\t\t offset = offset >>> 0;\n\t\t validateNumber(offset, 'offset');\n\t\t const first = this[offset];\n\t\t const last = this[offset + 7];\n\t\t if (first === undefined || last === undefined) {\n\t\t boundsError(offset, this.length - 8);\n\t\t }\n\n\t\t const lo = first +\n\t\t this[++offset] * 2 ** 8 +\n\t\t this[++offset] * 2 ** 16 +\n\t\t this[++offset] * 2 ** 24;\n\n\t\t const hi = this[++offset] +\n\t\t this[++offset] * 2 ** 8 +\n\t\t this[++offset] * 2 ** 16 +\n\t\t last * 2 ** 24;\n\n\t\t return BigInt(lo) + (BigInt(hi) << BigInt(32))\n\t\t});\n\n\t\tBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n\t\t offset = offset >>> 0;\n\t\t validateNumber(offset, 'offset');\n\t\t const first = this[offset];\n\t\t const last = this[offset + 7];\n\t\t if (first === undefined || last === undefined) {\n\t\t boundsError(offset, this.length - 8);\n\t\t }\n\n\t\t const hi = first * 2 ** 24 +\n\t\t this[++offset] * 2 ** 16 +\n\t\t this[++offset] * 2 ** 8 +\n\t\t this[++offset];\n\n\t\t const lo = this[++offset] * 2 ** 24 +\n\t\t this[++offset] * 2 ** 16 +\n\t\t this[++offset] * 2 ** 8 +\n\t\t last;\n\n\t\t return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n\t\t});\n\n\t\tBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t byteLength = byteLength >>> 0;\n\t\t if (!noAssert) checkOffset(offset, byteLength, this.length);\n\n\t\t let val = this[offset];\n\t\t let mul = 1;\n\t\t let i = 0;\n\t\t while (++i < byteLength && (mul *= 0x100)) {\n\t\t val += this[offset + i] * mul;\n\t\t }\n\t\t mul *= 0x80;\n\n\t\t if (val >= mul) val -= Math.pow(2, 8 * byteLength);\n\n\t\t return val\n\t\t};\n\n\t\tBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t byteLength = byteLength >>> 0;\n\t\t if (!noAssert) checkOffset(offset, byteLength, this.length);\n\n\t\t let i = byteLength;\n\t\t let mul = 1;\n\t\t let val = this[offset + --i];\n\t\t while (i > 0 && (mul *= 0x100)) {\n\t\t val += this[offset + --i] * mul;\n\t\t }\n\t\t mul *= 0x80;\n\n\t\t if (val >= mul) val -= Math.pow(2, 8 * byteLength);\n\n\t\t return val\n\t\t};\n\n\t\tBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 1, this.length);\n\t\t if (!(this[offset] & 0x80)) return (this[offset])\n\t\t return ((0xff - this[offset] + 1) * -1)\n\t\t};\n\n\t\tBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 2, this.length);\n\t\t const val = this[offset] | (this[offset + 1] << 8);\n\t\t return (val & 0x8000) ? val | 0xFFFF0000 : val\n\t\t};\n\n\t\tBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 2, this.length);\n\t\t const val = this[offset + 1] | (this[offset] << 8);\n\t\t return (val & 0x8000) ? val | 0xFFFF0000 : val\n\t\t};\n\n\t\tBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 4, this.length);\n\n\t\t return (this[offset]) |\n\t\t (this[offset + 1] << 8) |\n\t\t (this[offset + 2] << 16) |\n\t\t (this[offset + 3] << 24)\n\t\t};\n\n\t\tBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 4, this.length);\n\n\t\t return (this[offset] << 24) |\n\t\t (this[offset + 1] << 16) |\n\t\t (this[offset + 2] << 8) |\n\t\t (this[offset + 3])\n\t\t};\n\n\t\tBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n\t\t offset = offset >>> 0;\n\t\t validateNumber(offset, 'offset');\n\t\t const first = this[offset];\n\t\t const last = this[offset + 7];\n\t\t if (first === undefined || last === undefined) {\n\t\t boundsError(offset, this.length - 8);\n\t\t }\n\n\t\t const val = this[offset + 4] +\n\t\t this[offset + 5] * 2 ** 8 +\n\t\t this[offset + 6] * 2 ** 16 +\n\t\t (last << 24); // Overflow\n\n\t\t return (BigInt(val) << BigInt(32)) +\n\t\t BigInt(first +\n\t\t this[++offset] * 2 ** 8 +\n\t\t this[++offset] * 2 ** 16 +\n\t\t this[++offset] * 2 ** 24)\n\t\t});\n\n\t\tBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n\t\t offset = offset >>> 0;\n\t\t validateNumber(offset, 'offset');\n\t\t const first = this[offset];\n\t\t const last = this[offset + 7];\n\t\t if (first === undefined || last === undefined) {\n\t\t boundsError(offset, this.length - 8);\n\t\t }\n\n\t\t const val = (first << 24) + // Overflow\n\t\t this[++offset] * 2 ** 16 +\n\t\t this[++offset] * 2 ** 8 +\n\t\t this[++offset];\n\n\t\t return (BigInt(val) << BigInt(32)) +\n\t\t BigInt(this[++offset] * 2 ** 24 +\n\t\t this[++offset] * 2 ** 16 +\n\t\t this[++offset] * 2 ** 8 +\n\t\t last)\n\t\t});\n\n\t\tBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 4, this.length);\n\t\t return ieee754.read(this, offset, true, 23, 4)\n\t\t};\n\n\t\tBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 4, this.length);\n\t\t return ieee754.read(this, offset, false, 23, 4)\n\t\t};\n\n\t\tBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 8, this.length);\n\t\t return ieee754.read(this, offset, true, 52, 8)\n\t\t};\n\n\t\tBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 8, this.length);\n\t\t return ieee754.read(this, offset, false, 52, 8)\n\t\t};\n\n\t\tfunction checkInt (buf, value, offset, ext, max, min) {\n\t\t if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n\t\t if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n\t\t if (offset + ext > buf.length) throw new RangeError('Index out of range')\n\t\t}\n\n\t\tBuffer.prototype.writeUintLE =\n\t\tBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t byteLength = byteLength >>> 0;\n\t\t if (!noAssert) {\n\t\t const maxBytes = Math.pow(2, 8 * byteLength) - 1;\n\t\t checkInt(this, value, offset, byteLength, maxBytes, 0);\n\t\t }\n\n\t\t let mul = 1;\n\t\t let i = 0;\n\t\t this[offset] = value & 0xFF;\n\t\t while (++i < byteLength && (mul *= 0x100)) {\n\t\t this[offset + i] = (value / mul) & 0xFF;\n\t\t }\n\n\t\t return offset + byteLength\n\t\t};\n\n\t\tBuffer.prototype.writeUintBE =\n\t\tBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t byteLength = byteLength >>> 0;\n\t\t if (!noAssert) {\n\t\t const maxBytes = Math.pow(2, 8 * byteLength) - 1;\n\t\t checkInt(this, value, offset, byteLength, maxBytes, 0);\n\t\t }\n\n\t\t let i = byteLength - 1;\n\t\t let mul = 1;\n\t\t this[offset + i] = value & 0xFF;\n\t\t while (--i >= 0 && (mul *= 0x100)) {\n\t\t this[offset + i] = (value / mul) & 0xFF;\n\t\t }\n\n\t\t return offset + byteLength\n\t\t};\n\n\t\tBuffer.prototype.writeUint8 =\n\t\tBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);\n\t\t this[offset] = (value & 0xff);\n\t\t return offset + 1\n\t\t};\n\n\t\tBuffer.prototype.writeUint16LE =\n\t\tBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);\n\t\t this[offset] = (value & 0xff);\n\t\t this[offset + 1] = (value >>> 8);\n\t\t return offset + 2\n\t\t};\n\n\t\tBuffer.prototype.writeUint16BE =\n\t\tBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);\n\t\t this[offset] = (value >>> 8);\n\t\t this[offset + 1] = (value & 0xff);\n\t\t return offset + 2\n\t\t};\n\n\t\tBuffer.prototype.writeUint32LE =\n\t\tBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);\n\t\t this[offset + 3] = (value >>> 24);\n\t\t this[offset + 2] = (value >>> 16);\n\t\t this[offset + 1] = (value >>> 8);\n\t\t this[offset] = (value & 0xff);\n\t\t return offset + 4\n\t\t};\n\n\t\tBuffer.prototype.writeUint32BE =\n\t\tBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);\n\t\t this[offset] = (value >>> 24);\n\t\t this[offset + 1] = (value >>> 16);\n\t\t this[offset + 2] = (value >>> 8);\n\t\t this[offset + 3] = (value & 0xff);\n\t\t return offset + 4\n\t\t};\n\n\t\tfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n\t\t checkIntBI(value, min, max, buf, offset, 7);\n\n\t\t let lo = Number(value & BigInt(0xffffffff));\n\t\t buf[offset++] = lo;\n\t\t lo = lo >> 8;\n\t\t buf[offset++] = lo;\n\t\t lo = lo >> 8;\n\t\t buf[offset++] = lo;\n\t\t lo = lo >> 8;\n\t\t buf[offset++] = lo;\n\t\t let hi = Number(value >> BigInt(32) & BigInt(0xffffffff));\n\t\t buf[offset++] = hi;\n\t\t hi = hi >> 8;\n\t\t buf[offset++] = hi;\n\t\t hi = hi >> 8;\n\t\t buf[offset++] = hi;\n\t\t hi = hi >> 8;\n\t\t buf[offset++] = hi;\n\t\t return offset\n\t\t}\n\n\t\tfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n\t\t checkIntBI(value, min, max, buf, offset, 7);\n\n\t\t let lo = Number(value & BigInt(0xffffffff));\n\t\t buf[offset + 7] = lo;\n\t\t lo = lo >> 8;\n\t\t buf[offset + 6] = lo;\n\t\t lo = lo >> 8;\n\t\t buf[offset + 5] = lo;\n\t\t lo = lo >> 8;\n\t\t buf[offset + 4] = lo;\n\t\t let hi = Number(value >> BigInt(32) & BigInt(0xffffffff));\n\t\t buf[offset + 3] = hi;\n\t\t hi = hi >> 8;\n\t\t buf[offset + 2] = hi;\n\t\t hi = hi >> 8;\n\t\t buf[offset + 1] = hi;\n\t\t hi = hi >> 8;\n\t\t buf[offset] = hi;\n\t\t return offset + 8\n\t\t}\n\n\t\tBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n\t\t return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n\t\t});\n\n\t\tBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n\t\t return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n\t\t});\n\n\t\tBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) {\n\t\t const limit = Math.pow(2, (8 * byteLength) - 1);\n\n\t\t checkInt(this, value, offset, byteLength, limit - 1, -limit);\n\t\t }\n\n\t\t let i = 0;\n\t\t let mul = 1;\n\t\t let sub = 0;\n\t\t this[offset] = value & 0xFF;\n\t\t while (++i < byteLength && (mul *= 0x100)) {\n\t\t if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n\t\t sub = 1;\n\t\t }\n\t\t this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;\n\t\t }\n\n\t\t return offset + byteLength\n\t\t};\n\n\t\tBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) {\n\t\t const limit = Math.pow(2, (8 * byteLength) - 1);\n\n\t\t checkInt(this, value, offset, byteLength, limit - 1, -limit);\n\t\t }\n\n\t\t let i = byteLength - 1;\n\t\t let mul = 1;\n\t\t let sub = 0;\n\t\t this[offset + i] = value & 0xFF;\n\t\t while (--i >= 0 && (mul *= 0x100)) {\n\t\t if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n\t\t sub = 1;\n\t\t }\n\t\t this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;\n\t\t }\n\n\t\t return offset + byteLength\n\t\t};\n\n\t\tBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -128);\n\t\t if (value < 0) value = 0xff + value + 1;\n\t\t this[offset] = (value & 0xff);\n\t\t return offset + 1\n\t\t};\n\n\t\tBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);\n\t\t this[offset] = (value & 0xff);\n\t\t this[offset + 1] = (value >>> 8);\n\t\t return offset + 2\n\t\t};\n\n\t\tBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);\n\t\t this[offset] = (value >>> 8);\n\t\t this[offset + 1] = (value & 0xff);\n\t\t return offset + 2\n\t\t};\n\n\t\tBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);\n\t\t this[offset] = (value & 0xff);\n\t\t this[offset + 1] = (value >>> 8);\n\t\t this[offset + 2] = (value >>> 16);\n\t\t this[offset + 3] = (value >>> 24);\n\t\t return offset + 4\n\t\t};\n\n\t\tBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);\n\t\t if (value < 0) value = 0xffffffff + value + 1;\n\t\t this[offset] = (value >>> 24);\n\t\t this[offset + 1] = (value >>> 16);\n\t\t this[offset + 2] = (value >>> 8);\n\t\t this[offset + 3] = (value & 0xff);\n\t\t return offset + 4\n\t\t};\n\n\t\tBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n\t\t return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n\t\t});\n\n\t\tBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n\t\t return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n\t\t});\n\n\t\tfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n\t\t if (offset + ext > buf.length) throw new RangeError('Index out of range')\n\t\t if (offset < 0) throw new RangeError('Index out of range')\n\t\t}\n\n\t\tfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) {\n\t\t checkIEEE754(buf, value, offset, 4);\n\t\t }\n\t\t ieee754.write(buf, value, offset, littleEndian, 23, 4);\n\t\t return offset + 4\n\t\t}\n\n\t\tBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n\t\t return writeFloat(this, value, offset, true, noAssert)\n\t\t};\n\n\t\tBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n\t\t return writeFloat(this, value, offset, false, noAssert)\n\t\t};\n\n\t\tfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) {\n\t\t checkIEEE754(buf, value, offset, 8);\n\t\t }\n\t\t ieee754.write(buf, value, offset, littleEndian, 52, 8);\n\t\t return offset + 8\n\t\t}\n\n\t\tBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n\t\t return writeDouble(this, value, offset, true, noAssert)\n\t\t};\n\n\t\tBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n\t\t return writeDouble(this, value, offset, false, noAssert)\n\t\t};\n\n\t\t// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\n\t\tBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n\t\t if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n\t\t if (!start) start = 0;\n\t\t if (!end && end !== 0) end = this.length;\n\t\t if (targetStart >= target.length) targetStart = target.length;\n\t\t if (!targetStart) targetStart = 0;\n\t\t if (end > 0 && end < start) end = start;\n\n\t\t // Copy 0 bytes; we're done\n\t\t if (end === start) return 0\n\t\t if (target.length === 0 || this.length === 0) return 0\n\n\t\t // Fatal error conditions\n\t\t if (targetStart < 0) {\n\t\t throw new RangeError('targetStart out of bounds')\n\t\t }\n\t\t if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n\t\t if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n\t\t // Are we oob?\n\t\t if (end > this.length) end = this.length;\n\t\t if (target.length - targetStart < end - start) {\n\t\t end = target.length - targetStart + start;\n\t\t }\n\n\t\t const len = end - start;\n\n\t\t if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n\t\t // Use built-in when available, missing from IE11\n\t\t this.copyWithin(targetStart, start, end);\n\t\t } else {\n\t\t Uint8Array.prototype.set.call(\n\t\t target,\n\t\t this.subarray(start, end),\n\t\t targetStart\n\t\t );\n\t\t }\n\n\t\t return len\n\t\t};\n\n\t\t// Usage:\n\t\t// buffer.fill(number[, offset[, end]])\n\t\t// buffer.fill(buffer[, offset[, end]])\n\t\t// buffer.fill(string[, offset[, end]][, encoding])\n\t\tBuffer.prototype.fill = function fill (val, start, end, encoding) {\n\t\t // Handle string cases:\n\t\t if (typeof val === 'string') {\n\t\t if (typeof start === 'string') {\n\t\t encoding = start;\n\t\t start = 0;\n\t\t end = this.length;\n\t\t } else if (typeof end === 'string') {\n\t\t encoding = end;\n\t\t end = this.length;\n\t\t }\n\t\t if (encoding !== undefined && typeof encoding !== 'string') {\n\t\t throw new TypeError('encoding must be a string')\n\t\t }\n\t\t if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n\t\t throw new TypeError('Unknown encoding: ' + encoding)\n\t\t }\n\t\t if (val.length === 1) {\n\t\t const code = val.charCodeAt(0);\n\t\t if ((encoding === 'utf8' && code < 128) ||\n\t\t encoding === 'latin1') {\n\t\t // Fast path: If `val` fits into a single byte, use that numeric value.\n\t\t val = code;\n\t\t }\n\t\t }\n\t\t } else if (typeof val === 'number') {\n\t\t val = val & 255;\n\t\t } else if (typeof val === 'boolean') {\n\t\t val = Number(val);\n\t\t }\n\n\t\t // Invalid ranges are not set to a default, so can range check early.\n\t\t if (start < 0 || this.length < start || this.length < end) {\n\t\t throw new RangeError('Out of range index')\n\t\t }\n\n\t\t if (end <= start) {\n\t\t return this\n\t\t }\n\n\t\t start = start >>> 0;\n\t\t end = end === undefined ? this.length : end >>> 0;\n\n\t\t if (!val) val = 0;\n\n\t\t let i;\n\t\t if (typeof val === 'number') {\n\t\t for (i = start; i < end; ++i) {\n\t\t this[i] = val;\n\t\t }\n\t\t } else {\n\t\t const bytes = Buffer.isBuffer(val)\n\t\t ? val\n\t\t : Buffer.from(val, encoding);\n\t\t const len = bytes.length;\n\t\t if (len === 0) {\n\t\t throw new TypeError('The value \"' + val +\n\t\t '\" is invalid for argument \"value\"')\n\t\t }\n\t\t for (i = 0; i < end - start; ++i) {\n\t\t this[i + start] = bytes[i % len];\n\t\t }\n\t\t }\n\n\t\t return this\n\t\t};\n\n\t\t// CUSTOM ERRORS\n\t\t// =============\n\n\t\t// Simplified versions from Node, changed for Buffer-only usage\n\t\tconst errors = {};\n\t\tfunction E (sym, getMessage, Base) {\n\t\t errors[sym] = class NodeError extends Base {\n\t\t constructor () {\n\t\t super();\n\n\t\t Object.defineProperty(this, 'message', {\n\t\t value: getMessage.apply(this, arguments),\n\t\t writable: true,\n\t\t configurable: true\n\t\t });\n\n\t\t // Add the error code to the name to include it in the stack trace.\n\t\t this.name = `${this.name} [${sym}]`;\n\t\t // Access the stack to generate the error message including the error code\n\t\t // from the name.\n\t\t this.stack; // eslint-disable-line no-unused-expressions\n\t\t // Reset the name to the actual name.\n\t\t delete this.name;\n\t\t }\n\n\t\t get code () {\n\t\t return sym\n\t\t }\n\n\t\t set code (value) {\n\t\t Object.defineProperty(this, 'code', {\n\t\t configurable: true,\n\t\t enumerable: true,\n\t\t value,\n\t\t writable: true\n\t\t });\n\t\t }\n\n\t\t toString () {\n\t\t return `${this.name} [${sym}]: ${this.message}`\n\t\t }\n\t\t };\n\t\t}\n\n\t\tE('ERR_BUFFER_OUT_OF_BOUNDS',\n\t\t function (name) {\n\t\t if (name) {\n\t\t return `${name} is outside of buffer bounds`\n\t\t }\n\n\t\t return 'Attempt to access memory outside buffer bounds'\n\t\t }, RangeError);\n\t\tE('ERR_INVALID_ARG_TYPE',\n\t\t function (name, actual) {\n\t\t return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n\t\t }, TypeError);\n\t\tE('ERR_OUT_OF_RANGE',\n\t\t function (str, range, input) {\n\t\t let msg = `The value of \"${str}\" is out of range.`;\n\t\t let received = input;\n\t\t if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n\t\t received = addNumericalSeparator(String(input));\n\t\t } else if (typeof input === 'bigint') {\n\t\t received = String(input);\n\t\t if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n\t\t received = addNumericalSeparator(received);\n\t\t }\n\t\t received += 'n';\n\t\t }\n\t\t msg += ` It must be ${range}. Received ${received}`;\n\t\t return msg\n\t\t }, RangeError);\n\n\t\tfunction addNumericalSeparator (val) {\n\t\t let res = '';\n\t\t let i = val.length;\n\t\t const start = val[0] === '-' ? 1 : 0;\n\t\t for (; i >= start + 4; i -= 3) {\n\t\t res = `_${val.slice(i - 3, i)}${res}`;\n\t\t }\n\t\t return `${val.slice(0, i)}${res}`\n\t\t}\n\n\t\t// CHECK FUNCTIONS\n\t\t// ===============\n\n\t\tfunction checkBounds (buf, offset, byteLength) {\n\t\t validateNumber(offset, 'offset');\n\t\t if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n\t\t boundsError(offset, buf.length - (byteLength + 1));\n\t\t }\n\t\t}\n\n\t\tfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n\t\t if (value > max || value < min) {\n\t\t const n = typeof min === 'bigint' ? 'n' : '';\n\t\t let range;\n\t\t {\n\t\t if (min === 0 || min === BigInt(0)) {\n\t\t range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`;\n\t\t } else {\n\t\t range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n\t\t `${(byteLength + 1) * 8 - 1}${n}`;\n\t\t }\n\t\t }\n\t\t throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n\t\t }\n\t\t checkBounds(buf, offset, byteLength);\n\t\t}\n\n\t\tfunction validateNumber (value, name) {\n\t\t if (typeof value !== 'number') {\n\t\t throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n\t\t }\n\t\t}\n\n\t\tfunction boundsError (value, length, type) {\n\t\t if (Math.floor(value) !== value) {\n\t\t validateNumber(value, type);\n\t\t throw new errors.ERR_OUT_OF_RANGE('offset', 'an integer', value)\n\t\t }\n\n\t\t if (length < 0) {\n\t\t throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n\t\t }\n\n\t\t throw new errors.ERR_OUT_OF_RANGE('offset',\n\t\t `>= ${0} and <= ${length}`,\n\t\t value)\n\t\t}\n\n\t\t// HELPER FUNCTIONS\n\t\t// ================\n\n\t\tconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;\n\n\t\tfunction base64clean (str) {\n\t\t // Node takes equal signs as end of the Base64 encoding\n\t\t str = str.split('=')[0];\n\t\t // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n\t\t str = str.trim().replace(INVALID_BASE64_RE, '');\n\t\t // Node converts strings with length < 2 to ''\n\t\t if (str.length < 2) return ''\n\t\t // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n\t\t while (str.length % 4 !== 0) {\n\t\t str = str + '=';\n\t\t }\n\t\t return str\n\t\t}\n\n\t\tfunction utf8ToBytes (string, units) {\n\t\t units = units || Infinity;\n\t\t let codePoint;\n\t\t const length = string.length;\n\t\t let leadSurrogate = null;\n\t\t const bytes = [];\n\n\t\t for (let i = 0; i < length; ++i) {\n\t\t codePoint = string.charCodeAt(i);\n\n\t\t // is surrogate component\n\t\t if (codePoint > 0xD7FF && codePoint < 0xE000) {\n\t\t // last char was a lead\n\t\t if (!leadSurrogate) {\n\t\t // no lead yet\n\t\t if (codePoint > 0xDBFF) {\n\t\t // unexpected trail\n\t\t if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n\t\t continue\n\t\t } else if (i + 1 === length) {\n\t\t // unpaired lead\n\t\t if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n\t\t continue\n\t\t }\n\n\t\t // valid lead\n\t\t leadSurrogate = codePoint;\n\n\t\t continue\n\t\t }\n\n\t\t // 2 leads in a row\n\t\t if (codePoint < 0xDC00) {\n\t\t if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n\t\t leadSurrogate = codePoint;\n\t\t continue\n\t\t }\n\n\t\t // valid surrogate pair\n\t\t codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;\n\t\t } else if (leadSurrogate) {\n\t\t // valid bmp char, but last char was a lead\n\t\t if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n\t\t }\n\n\t\t leadSurrogate = null;\n\n\t\t // encode utf8\n\t\t if (codePoint < 0x80) {\n\t\t if ((units -= 1) < 0) break\n\t\t bytes.push(codePoint);\n\t\t } else if (codePoint < 0x800) {\n\t\t if ((units -= 2) < 0) break\n\t\t bytes.push(\n\t\t codePoint >> 0x6 | 0xC0,\n\t\t codePoint & 0x3F | 0x80\n\t\t );\n\t\t } else if (codePoint < 0x10000) {\n\t\t if ((units -= 3) < 0) break\n\t\t bytes.push(\n\t\t codePoint >> 0xC | 0xE0,\n\t\t codePoint >> 0x6 & 0x3F | 0x80,\n\t\t codePoint & 0x3F | 0x80\n\t\t );\n\t\t } else if (codePoint < 0x110000) {\n\t\t if ((units -= 4) < 0) break\n\t\t bytes.push(\n\t\t codePoint >> 0x12 | 0xF0,\n\t\t codePoint >> 0xC & 0x3F | 0x80,\n\t\t codePoint >> 0x6 & 0x3F | 0x80,\n\t\t codePoint & 0x3F | 0x80\n\t\t );\n\t\t } else {\n\t\t throw new Error('Invalid code point')\n\t\t }\n\t\t }\n\n\t\t return bytes\n\t\t}\n\n\t\tfunction asciiToBytes (str) {\n\t\t const byteArray = [];\n\t\t for (let i = 0; i < str.length; ++i) {\n\t\t // Node's code seems to be doing this and not & 0x7F..\n\t\t byteArray.push(str.charCodeAt(i) & 0xFF);\n\t\t }\n\t\t return byteArray\n\t\t}\n\n\t\tfunction utf16leToBytes (str, units) {\n\t\t let c, hi, lo;\n\t\t const byteArray = [];\n\t\t for (let i = 0; i < str.length; ++i) {\n\t\t if ((units -= 2) < 0) break\n\n\t\t c = str.charCodeAt(i);\n\t\t hi = c >> 8;\n\t\t lo = c % 256;\n\t\t byteArray.push(lo);\n\t\t byteArray.push(hi);\n\t\t }\n\n\t\t return byteArray\n\t\t}\n\n\t\tfunction base64ToBytes (str) {\n\t\t return base64.toByteArray(base64clean(str))\n\t\t}\n\n\t\tfunction blitBuffer (src, dst, offset, length) {\n\t\t let i;\n\t\t for (i = 0; i < length; ++i) {\n\t\t if ((i + offset >= dst.length) || (i >= src.length)) break\n\t\t dst[i + offset] = src[i];\n\t\t }\n\t\t return i\n\t\t}\n\n\t\t// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n\t\t// the `instanceof` check but they should be treated as of that type.\n\t\t// See: https://github.com/feross/buffer/issues/166\n\t\tfunction isInstance (obj, type) {\n\t\t return obj instanceof type ||\n\t\t (obj != null && obj.constructor != null && obj.constructor.name != null &&\n\t\t obj.constructor.name === type.name)\n\t\t}\n\t\tfunction numberIsNaN (obj) {\n\t\t // For IE11 support\n\t\t return obj !== obj // eslint-disable-line no-self-compare\n\t\t}\n\n\t\t// Create lookup table for `toString('hex')`\n\t\t// See: https://github.com/feross/buffer/issues/219\n\t\tconst hexSliceLookupTable = (function () {\n\t\t const alphabet = '0123456789abcdef';\n\t\t const table = new Array(256);\n\t\t for (let i = 0; i < 16; ++i) {\n\t\t const i16 = i * 16;\n\t\t for (let j = 0; j < 16; ++j) {\n\t\t table[i16 + j] = alphabet[i] + alphabet[j];\n\t\t }\n\t\t }\n\t\t return table\n\t\t})();\n\n\t\t// Return not function with Error if BigInt not supported\n\t\tfunction defineBigIntMethod (fn) {\n\t\t return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n\t\t}\n\n\t\tfunction BufferBigIntNotDefined () {\n\t\t throw new Error('BigInt not supported')\n\t\t} \n\t} (buffer));\n\treturn buffer;\n}\n\nvar bufferExports = requireBuffer();\n\nvar dist = {};\n\nvar Codecs = {};\n\nvar Frames = {};\n\nvar hasRequiredFrames;\n\nfunction requireFrames () {\n\tif (hasRequiredFrames) return Frames;\n\thasRequiredFrames = 1;\n\t(function (exports$1) {\n\t\t/*\n\t\t * Copyright 2021-2022 the original author or authors.\n\t\t *\n\t\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t\t * you may not use this file except in compliance with the License.\n\t\t * You may obtain a copy of the License at\n\t\t *\n\t\t * http://www.apache.org/licenses/LICENSE-2.0\n\t\t *\n\t\t * Unless required by applicable law or agreed to in writing, software\n\t\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t\t * See the License for the specific language governing permissions and\n\t\t * limitations under the License.\n\t\t */\n\t\tObject.defineProperty(exports$1, \"__esModule\", { value: true });\n\t\texports$1.Frame = exports$1.Lengths = exports$1.Flags = exports$1.FrameTypes = void 0;\n\t\tvar FrameTypes;\n\t\t(function (FrameTypes) {\n\t\t FrameTypes[FrameTypes[\"RESERVED\"] = 0] = \"RESERVED\";\n\t\t FrameTypes[FrameTypes[\"SETUP\"] = 1] = \"SETUP\";\n\t\t FrameTypes[FrameTypes[\"LEASE\"] = 2] = \"LEASE\";\n\t\t FrameTypes[FrameTypes[\"KEEPALIVE\"] = 3] = \"KEEPALIVE\";\n\t\t FrameTypes[FrameTypes[\"REQUEST_RESPONSE\"] = 4] = \"REQUEST_RESPONSE\";\n\t\t FrameTypes[FrameTypes[\"REQUEST_FNF\"] = 5] = \"REQUEST_FNF\";\n\t\t FrameTypes[FrameTypes[\"REQUEST_STREAM\"] = 6] = \"REQUEST_STREAM\";\n\t\t FrameTypes[FrameTypes[\"REQUEST_CHANNEL\"] = 7] = \"REQUEST_CHANNEL\";\n\t\t FrameTypes[FrameTypes[\"REQUEST_N\"] = 8] = \"REQUEST_N\";\n\t\t FrameTypes[FrameTypes[\"CANCEL\"] = 9] = \"CANCEL\";\n\t\t FrameTypes[FrameTypes[\"PAYLOAD\"] = 10] = \"PAYLOAD\";\n\t\t FrameTypes[FrameTypes[\"ERROR\"] = 11] = \"ERROR\";\n\t\t FrameTypes[FrameTypes[\"METADATA_PUSH\"] = 12] = \"METADATA_PUSH\";\n\t\t FrameTypes[FrameTypes[\"RESUME\"] = 13] = \"RESUME\";\n\t\t FrameTypes[FrameTypes[\"RESUME_OK\"] = 14] = \"RESUME_OK\";\n\t\t FrameTypes[FrameTypes[\"EXT\"] = 63] = \"EXT\";\n\t\t})(FrameTypes = exports$1.FrameTypes || (exports$1.FrameTypes = {}));\n\t\t(function (Flags) {\n\t\t Flags[Flags[\"NONE\"] = 0] = \"NONE\";\n\t\t Flags[Flags[\"COMPLETE\"] = 64] = \"COMPLETE\";\n\t\t Flags[Flags[\"FOLLOWS\"] = 128] = \"FOLLOWS\";\n\t\t Flags[Flags[\"IGNORE\"] = 512] = \"IGNORE\";\n\t\t Flags[Flags[\"LEASE\"] = 64] = \"LEASE\";\n\t\t Flags[Flags[\"METADATA\"] = 256] = \"METADATA\";\n\t\t Flags[Flags[\"NEXT\"] = 32] = \"NEXT\";\n\t\t Flags[Flags[\"RESPOND\"] = 128] = \"RESPOND\";\n\t\t Flags[Flags[\"RESUME_ENABLE\"] = 128] = \"RESUME_ENABLE\";\n\t\t})(exports$1.Flags || (exports$1.Flags = {}));\n\t\t(function (Flags) {\n\t\t function hasMetadata(flags) {\n\t\t return (flags & Flags.METADATA) === Flags.METADATA;\n\t\t }\n\t\t Flags.hasMetadata = hasMetadata;\n\t\t function hasComplete(flags) {\n\t\t return (flags & Flags.COMPLETE) === Flags.COMPLETE;\n\t\t }\n\t\t Flags.hasComplete = hasComplete;\n\t\t function hasNext(flags) {\n\t\t return (flags & Flags.NEXT) === Flags.NEXT;\n\t\t }\n\t\t Flags.hasNext = hasNext;\n\t\t function hasFollows(flags) {\n\t\t return (flags & Flags.FOLLOWS) === Flags.FOLLOWS;\n\t\t }\n\t\t Flags.hasFollows = hasFollows;\n\t\t function hasIgnore(flags) {\n\t\t return (flags & Flags.IGNORE) === Flags.IGNORE;\n\t\t }\n\t\t Flags.hasIgnore = hasIgnore;\n\t\t function hasRespond(flags) {\n\t\t return (flags & Flags.RESPOND) === Flags.RESPOND;\n\t\t }\n\t\t Flags.hasRespond = hasRespond;\n\t\t function hasLease(flags) {\n\t\t return (flags & Flags.LEASE) === Flags.LEASE;\n\t\t }\n\t\t Flags.hasLease = hasLease;\n\t\t function hasResume(flags) {\n\t\t return (flags & Flags.RESUME_ENABLE) === Flags.RESUME_ENABLE;\n\t\t }\n\t\t Flags.hasResume = hasResume;\n\t\t})(exports$1.Flags || (exports$1.Flags = {}));\n\t\t(function (Lengths) {\n\t\t Lengths[Lengths[\"FRAME\"] = 3] = \"FRAME\";\n\t\t Lengths[Lengths[\"HEADER\"] = 6] = \"HEADER\";\n\t\t Lengths[Lengths[\"METADATA\"] = 3] = \"METADATA\";\n\t\t Lengths[Lengths[\"REQUEST\"] = 3] = \"REQUEST\";\n\t\t})(exports$1.Lengths || (exports$1.Lengths = {}));\n\t\t(function (Frame) {\n\t\t function isConnection(frame) {\n\t\t return frame.streamId === 0;\n\t\t }\n\t\t Frame.isConnection = isConnection;\n\t\t function isRequest(frame) {\n\t\t return (FrameTypes.REQUEST_RESPONSE <= frame.type &&\n\t\t frame.type <= FrameTypes.REQUEST_CHANNEL);\n\t\t }\n\t\t Frame.isRequest = isRequest;\n\t\t})(exports$1.Frame || (exports$1.Frame = {}));\n\t\t\n\t} (Frames));\n\treturn Frames;\n}\n\nvar hasRequiredCodecs;\n\nfunction requireCodecs () {\n\tif (hasRequiredCodecs) return Codecs;\n\thasRequiredCodecs = 1;\n\t(function (exports$1) {\n\t\tvar __generator = (Codecs && Codecs.__generator) || function (thisArg, body) {\n\t\t var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n\t\t return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n\t\t function verb(n) { return function (v) { return step([n, v]); }; }\n\t\t function step(op) {\n\t\t if (f) throw new TypeError(\"Generator is already executing.\");\n\t\t while (_) try {\n\t\t if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n\t\t if (y = 0, t) op = [op[0] & 2, t.value];\n\t\t switch (op[0]) {\n\t\t case 0: case 1: t = op; break;\n\t\t case 4: _.label++; return { value: op[1], done: false };\n\t\t case 5: _.label++; y = op[1]; op = [0]; continue;\n\t\t case 7: op = _.ops.pop(); _.trys.pop(); continue;\n\t\t default:\n\t\t if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n\t\t if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n\t\t if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n\t\t if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n\t\t if (t[2]) _.ops.pop();\n\t\t _.trys.pop(); continue;\n\t\t }\n\t\t op = body.call(thisArg, _);\n\t\t } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n\t\t if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n\t\t }\n\t\t};\n\t\tObject.defineProperty(exports$1, \"__esModule\", { value: true });\n\t\texports$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;\n\t\tvar Frames_1 = requireFrames();\n\t\texports$1.FLAGS_MASK = 0x3ff; // low 10 bits\n\t\texports$1.FRAME_TYPE_OFFFSET = 10; // frame type is offset 10 bytes within the uint16 containing type + flags\n\t\texports$1.MAX_CODE = 0x7fffffff; // uint31\n\t\texports$1.MAX_KEEPALIVE = 0x7fffffff; // uint31\n\t\texports$1.MAX_LIFETIME = 0x7fffffff; // uint31\n\t\texports$1.MAX_METADATA_LENGTH = 0xffffff; // uint24\n\t\texports$1.MAX_MIME_LENGTH = 0xff; // int8\n\t\texports$1.MAX_REQUEST_COUNT = 0x7fffffff; // uint31\n\t\texports$1.MAX_REQUEST_N = 0x7fffffff; // uint31\n\t\texports$1.MAX_RESUME_LENGTH = 0xffff; // uint16\n\t\texports$1.MAX_STREAM_ID = 0x7fffffff; // uint31\n\t\texports$1.MAX_TTL = 0x7fffffff; // uint31\n\t\texports$1.MAX_VERSION = 0xffff; // uint16\n\t\t/**\n\t\t * Mimimum value that would overflow bitwise operators (2^32).\n\t\t */\n\t\tvar BITWISE_OVERFLOW = 0x100000000;\n\t\t/**\n\t\t * Read a uint24 from a buffer starting at the given offset.\n\t\t */\n\t\tfunction readUInt24BE(buffer, offset) {\n\t\t var val1 = buffer.readUInt8(offset) << 16;\n\t\t var val2 = buffer.readUInt8(offset + 1) << 8;\n\t\t var val3 = buffer.readUInt8(offset + 2);\n\t\t return val1 | val2 | val3;\n\t\t}\n\t\texports$1.readUInt24BE = readUInt24BE;\n\t\t/**\n\t\t * Writes a uint24 to a buffer starting at the given offset, returning the\n\t\t * offset of the next byte.\n\t\t */\n\t\tfunction writeUInt24BE(buffer, value, offset) {\n\t\t offset = buffer.writeUInt8(value >>> 16, offset); // 3rd byte\n\t\t offset = buffer.writeUInt8((value >>> 8) & 0xff, offset); // 2nd byte\n\t\t return buffer.writeUInt8(value & 0xff, offset); // 1st byte\n\t\t}\n\t\texports$1.writeUInt24BE = writeUInt24BE;\n\t\t/**\n\t\t * Read a uint64 (technically supports up to 53 bits per JS number\n\t\t * representation).\n\t\t */\n\t\tfunction readUInt64BE(buffer, offset) {\n\t\t var high = buffer.readUInt32BE(offset);\n\t\t var low = buffer.readUInt32BE(offset + 4);\n\t\t return high * BITWISE_OVERFLOW + low;\n\t\t}\n\t\texports$1.readUInt64BE = readUInt64BE;\n\t\t/**\n\t\t * Write a uint64 (technically supports up to 53 bits per JS number\n\t\t * representation).\n\t\t */\n\t\tfunction writeUInt64BE(buffer, value, offset) {\n\t\t var high = (value / BITWISE_OVERFLOW) | 0;\n\t\t var low = value % BITWISE_OVERFLOW;\n\t\t offset = buffer.writeUInt32BE(high, offset); // first half of uint64\n\t\t return buffer.writeUInt32BE(low, offset); // second half of uint64\n\t\t}\n\t\texports$1.writeUInt64BE = writeUInt64BE;\n\t\t/**\n\t\t * Frame header is:\n\t\t * - stream id (uint32 = 4)\n\t\t * - type + flags (uint 16 = 2)\n\t\t */\n\t\tvar FRAME_HEADER_SIZE = 6;\n\t\t/**\n\t\t * Size of frame length and metadata length fields.\n\t\t */\n\t\tvar UINT24_SIZE = 3;\n\t\t/**\n\t\t * Reads a frame from a buffer that is prefixed with the frame length.\n\t\t */\n\t\tfunction deserializeFrameWithLength(buffer) {\n\t\t var frameLength = readUInt24BE(buffer, 0);\n\t\t return deserializeFrame(buffer.slice(UINT24_SIZE, UINT24_SIZE + frameLength));\n\t\t}\n\t\texports$1.deserializeFrameWithLength = deserializeFrameWithLength;\n\t\t/**\n\t\t * Given a buffer that may contain zero or more length-prefixed frames followed\n\t\t * by zero or more bytes of a (partial) subsequent frame, returns an array of\n\t\t * the frames and an int representing the buffer offset.\n\t\t */\n\t\tfunction deserializeFrames(buffer) {\n\t\t var offset, frameLength, frameStart, frameEnd, frameBuffer, frame;\n\t\t return __generator(this, function (_a) {\n\t\t switch (_a.label) {\n\t\t case 0:\n\t\t offset = 0;\n\t\t _a.label = 1;\n\t\t case 1:\n\t\t if (!(offset + UINT24_SIZE < buffer.length)) return [3 /*break*/, 3];\n\t\t frameLength = readUInt24BE(buffer, offset);\n\t\t frameStart = offset + UINT24_SIZE;\n\t\t frameEnd = frameStart + frameLength;\n\t\t if (frameEnd > buffer.length) {\n\t\t // not all bytes of next frame received\n\t\t return [3 /*break*/, 3];\n\t\t }\n\t\t frameBuffer = buffer.slice(frameStart, frameEnd);\n\t\t frame = deserializeFrame(frameBuffer);\n\t\t offset = frameEnd;\n\t\t return [4 /*yield*/, [frame, offset]];\n\t\t case 2:\n\t\t _a.sent();\n\t\t return [3 /*break*/, 1];\n\t\t case 3: return [2 /*return*/];\n\t\t }\n\t\t });\n\t\t}\n\t\texports$1.deserializeFrames = deserializeFrames;\n\t\t/**\n\t\t * Writes a frame to a buffer with a length prefix.\n\t\t */\n\t\tfunction serializeFrameWithLength(frame) {\n\t\t var buffer = serializeFrame(frame);\n\t\t var lengthPrefixed = bufferExports.Buffer.allocUnsafe(buffer.length + UINT24_SIZE);\n\t\t writeUInt24BE(lengthPrefixed, buffer.length, 0);\n\t\t buffer.copy(lengthPrefixed, UINT24_SIZE);\n\t\t return lengthPrefixed;\n\t\t}\n\t\texports$1.serializeFrameWithLength = serializeFrameWithLength;\n\t\t/**\n\t\t * Read a frame from the buffer.\n\t\t */\n\t\tfunction deserializeFrame(buffer) {\n\t\t var offset = 0;\n\t\t var streamId = buffer.readInt32BE(offset);\n\t\t offset += 4;\n\t\t // invariant(\n\t\t // streamId >= 0,\n\t\t // 'RSocketBinaryFraming: Invalid frame, expected a positive stream id, got `%s.',\n\t\t // streamId,\n\t\t // );\n\t\t var typeAndFlags = buffer.readUInt16BE(offset);\n\t\t offset += 2;\n\t\t var type = typeAndFlags >>> exports$1.FRAME_TYPE_OFFFSET; // keep highest 6 bits\n\t\t var flags = typeAndFlags & exports$1.FLAGS_MASK; // keep lowest 10 bits\n\t\t switch (type) {\n\t\t case Frames_1.FrameTypes.SETUP:\n\t\t return deserializeSetupFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.PAYLOAD:\n\t\t return deserializePayloadFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.ERROR:\n\t\t return deserializeErrorFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.KEEPALIVE:\n\t\t return deserializeKeepAliveFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.REQUEST_FNF:\n\t\t return deserializeRequestFnfFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.REQUEST_RESPONSE:\n\t\t return deserializeRequestResponseFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.REQUEST_STREAM:\n\t\t return deserializeRequestStreamFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.REQUEST_CHANNEL:\n\t\t return deserializeRequestChannelFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.METADATA_PUSH:\n\t\t return deserializeMetadataPushFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.REQUEST_N:\n\t\t return deserializeRequestNFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.RESUME:\n\t\t return deserializeResumeFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.RESUME_OK:\n\t\t return deserializeResumeOkFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.CANCEL:\n\t\t return deserializeCancelFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.LEASE:\n\t\t return deserializeLeaseFrame(buffer, streamId, flags);\n\t\t // invariant(\n\t\t // false,\n\t\t // \"RSocketBinaryFraming: Unsupported frame type `%s`.\",\n\t\t // getFrameTypeName(type)\n\t\t // );\n\t\t }\n\t\t}\n\t\texports$1.deserializeFrame = deserializeFrame;\n\t\t/**\n\t\t * Convert the frame to a (binary) buffer.\n\t\t */\n\t\tfunction serializeFrame(frame) {\n\t\t switch (frame.type) {\n\t\t case Frames_1.FrameTypes.SETUP:\n\t\t return serializeSetupFrame(frame);\n\t\t case Frames_1.FrameTypes.PAYLOAD:\n\t\t return serializePayloadFrame(frame);\n\t\t case Frames_1.FrameTypes.ERROR:\n\t\t return serializeErrorFrame(frame);\n\t\t case Frames_1.FrameTypes.KEEPALIVE:\n\t\t return serializeKeepAliveFrame(frame);\n\t\t case Frames_1.FrameTypes.REQUEST_FNF:\n\t\t case Frames_1.FrameTypes.REQUEST_RESPONSE:\n\t\t return serializeRequestFrame(frame);\n\t\t case Frames_1.FrameTypes.REQUEST_STREAM:\n\t\t case Frames_1.FrameTypes.REQUEST_CHANNEL:\n\t\t return serializeRequestManyFrame(frame);\n\t\t case Frames_1.FrameTypes.METADATA_PUSH:\n\t\t return serializeMetadataPushFrame(frame);\n\t\t case Frames_1.FrameTypes.REQUEST_N:\n\t\t return serializeRequestNFrame(frame);\n\t\t case Frames_1.FrameTypes.RESUME:\n\t\t return serializeResumeFrame(frame);\n\t\t case Frames_1.FrameTypes.RESUME_OK:\n\t\t return serializeResumeOkFrame(frame);\n\t\t case Frames_1.FrameTypes.CANCEL:\n\t\t return serializeCancelFrame(frame);\n\t\t case Frames_1.FrameTypes.LEASE:\n\t\t return serializeLeaseFrame(frame);\n\t\t // invariant(\n\t\t // false,\n\t\t // \"RSocketBinaryFraming: Unsupported frame type `%s`.\",\n\t\t // getFrameTypeName(frame.type)\n\t\t // );\n\t\t }\n\t\t}\n\t\texports$1.serializeFrame = serializeFrame;\n\t\t/**\n\t\t * Byte size of frame without size prefix\n\t\t */\n\t\tfunction sizeOfFrame(frame) {\n\t\t switch (frame.type) {\n\t\t case Frames_1.FrameTypes.SETUP:\n\t\t return sizeOfSetupFrame(frame);\n\t\t case Frames_1.FrameTypes.PAYLOAD:\n\t\t return sizeOfPayloadFrame(frame);\n\t\t case Frames_1.FrameTypes.ERROR:\n\t\t return sizeOfErrorFrame(frame);\n\t\t case Frames_1.FrameTypes.KEEPALIVE:\n\t\t return sizeOfKeepAliveFrame(frame);\n\t\t case Frames_1.FrameTypes.REQUEST_FNF:\n\t\t case Frames_1.FrameTypes.REQUEST_RESPONSE:\n\t\t return sizeOfRequestFrame(frame);\n\t\t case Frames_1.FrameTypes.REQUEST_STREAM:\n\t\t case Frames_1.FrameTypes.REQUEST_CHANNEL:\n\t\t return sizeOfRequestManyFrame(frame);\n\t\t case Frames_1.FrameTypes.METADATA_PUSH:\n\t\t return sizeOfMetadataPushFrame(frame);\n\t\t case Frames_1.FrameTypes.REQUEST_N:\n\t\t return sizeOfRequestNFrame();\n\t\t case Frames_1.FrameTypes.RESUME:\n\t\t return sizeOfResumeFrame(frame);\n\t\t case Frames_1.FrameTypes.RESUME_OK:\n\t\t return sizeOfResumeOkFrame();\n\t\t case Frames_1.FrameTypes.CANCEL:\n\t\t return sizeOfCancelFrame();\n\t\t case Frames_1.FrameTypes.LEASE:\n\t\t return sizeOfLeaseFrame(frame);\n\t\t // invariant(\n\t\t // false,\n\t\t // \"RSocketBinaryFraming: Unsupported frame type `%s`.\",\n\t\t // getFrameTypeName(frame.type)\n\t\t // );\n\t\t }\n\t\t}\n\t\texports$1.sizeOfFrame = sizeOfFrame;\n\t\t/**\n\t\t * Writes a SETUP frame into a new buffer and returns it.\n\t\t *\n\t\t * Prefix size is:\n\t\t * - version (2x uint16 = 4)\n\t\t * - keepalive (uint32 = 4)\n\t\t * - lifetime (uint32 = 4)\n\t\t * - mime lengths (2x uint8 = 2)\n\t\t */\n\t\tvar SETUP_FIXED_SIZE = 14;\n\t\tvar RESUME_TOKEN_LENGTH_SIZE = 2;\n\t\tfunction serializeSetupFrame(frame) {\n\t\t var resumeTokenLength = frame.resumeToken != null ? frame.resumeToken.byteLength : 0;\n\t\t var metadataMimeTypeLength = frame.metadataMimeType != null\n\t\t ? bufferExports.Buffer.byteLength(frame.metadataMimeType, \"ascii\")\n\t\t : 0;\n\t\t var dataMimeTypeLength = frame.dataMimeType != null\n\t\t ? bufferExports.Buffer.byteLength(frame.dataMimeType, \"ascii\")\n\t\t : 0;\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE +\n\t\t SETUP_FIXED_SIZE + //\n\t\t (resumeTokenLength ? RESUME_TOKEN_LENGTH_SIZE + resumeTokenLength : 0) +\n\t\t metadataMimeTypeLength +\n\t\t dataMimeTypeLength +\n\t\t payloadLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t offset = buffer.writeUInt16BE(frame.majorVersion, offset);\n\t\t offset = buffer.writeUInt16BE(frame.minorVersion, offset);\n\t\t offset = buffer.writeUInt32BE(frame.keepAlive, offset);\n\t\t offset = buffer.writeUInt32BE(frame.lifetime, offset);\n\t\t if (frame.flags & Frames_1.Flags.RESUME_ENABLE) {\n\t\t offset = buffer.writeUInt16BE(resumeTokenLength, offset);\n\t\t if (frame.resumeToken != null) {\n\t\t offset += frame.resumeToken.copy(buffer, offset);\n\t\t }\n\t\t }\n\t\t offset = buffer.writeUInt8(metadataMimeTypeLength, offset);\n\t\t if (frame.metadataMimeType != null) {\n\t\t offset += buffer.write(frame.metadataMimeType, offset, offset + metadataMimeTypeLength, \"ascii\");\n\t\t }\n\t\t offset = buffer.writeUInt8(dataMimeTypeLength, offset);\n\t\t if (frame.dataMimeType != null) {\n\t\t offset += buffer.write(frame.dataMimeType, offset, offset + dataMimeTypeLength, \"ascii\");\n\t\t }\n\t\t writePayload(frame, buffer, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfSetupFrame(frame) {\n\t\t var resumeTokenLength = frame.resumeToken != null ? frame.resumeToken.byteLength : 0;\n\t\t var metadataMimeTypeLength = frame.metadataMimeType != null\n\t\t ? bufferExports.Buffer.byteLength(frame.metadataMimeType, \"ascii\")\n\t\t : 0;\n\t\t var dataMimeTypeLength = frame.dataMimeType != null\n\t\t ? bufferExports.Buffer.byteLength(frame.dataMimeType, \"ascii\")\n\t\t : 0;\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t return (FRAME_HEADER_SIZE +\n\t\t SETUP_FIXED_SIZE + //\n\t\t (resumeTokenLength ? RESUME_TOKEN_LENGTH_SIZE + resumeTokenLength : 0) +\n\t\t metadataMimeTypeLength +\n\t\t dataMimeTypeLength +\n\t\t payloadLength);\n\t\t}\n\t\t/**\n\t\t * Reads a SETUP frame from the buffer and returns it.\n\t\t */\n\t\tfunction deserializeSetupFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId === 0,\n\t\t // 'RSocketBinaryFraming: Invalid SETUP frame, expected stream id to be 0.',\n\t\t // );\n\t\t buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var majorVersion = buffer.readUInt16BE(offset);\n\t\t offset += 2;\n\t\t var minorVersion = buffer.readUInt16BE(offset);\n\t\t offset += 2;\n\t\t var keepAlive = buffer.readInt32BE(offset);\n\t\t offset += 4;\n\t\t // invariant(\n\t\t // keepAlive >= 0 && keepAlive <= MAX_KEEPALIVE,\n\t\t // 'RSocketBinaryFraming: Invalid SETUP frame, expected keepAlive to be ' +\n\t\t // '>= 0 and <= %s. Got `%s`.',\n\t\t // MAX_KEEPALIVE,\n\t\t // keepAlive,\n\t\t // );\n\t\t var lifetime = buffer.readInt32BE(offset);\n\t\t offset += 4;\n\t\t // invariant(\n\t\t // lifetime >= 0 && lifetime <= MAX_LIFETIME,\n\t\t // 'RSocketBinaryFraming: Invalid SETUP frame, expected lifetime to be ' +\n\t\t // '>= 0 and <= %s. Got `%s`.',\n\t\t // MAX_LIFETIME,\n\t\t // lifetime,\n\t\t // );\n\t\t var resumeToken = null;\n\t\t if (flags & Frames_1.Flags.RESUME_ENABLE) {\n\t\t var resumeTokenLength = buffer.readInt16BE(offset);\n\t\t offset += 2;\n\t\t // invariant(\n\t\t // resumeTokenLength >= 0 && resumeTokenLength <= MAX_RESUME_LENGTH,\n\t\t // 'RSocketBinaryFraming: Invalid SETUP frame, expected resumeToken length ' +\n\t\t // 'to be >= 0 and <= %s. Got `%s`.',\n\t\t // MAX_RESUME_LENGTH,\n\t\t // resumeTokenLength,\n\t\t // );\n\t\t resumeToken = buffer.slice(offset, offset + resumeTokenLength);\n\t\t offset += resumeTokenLength;\n\t\t }\n\t\t var metadataMimeTypeLength = buffer.readUInt8(offset);\n\t\t offset += 1;\n\t\t var metadataMimeType = buffer.toString(\"ascii\", offset, offset + metadataMimeTypeLength);\n\t\t offset += metadataMimeTypeLength;\n\t\t var dataMimeTypeLength = buffer.readUInt8(offset);\n\t\t offset += 1;\n\t\t var dataMimeType = buffer.toString(\"ascii\", offset, offset + dataMimeTypeLength);\n\t\t offset += dataMimeTypeLength;\n\t\t var frame = {\n\t\t data: null,\n\t\t dataMimeType: dataMimeType,\n\t\t flags: flags,\n\t\t keepAlive: keepAlive,\n\t\t lifetime: lifetime,\n\t\t majorVersion: majorVersion,\n\t\t metadata: null,\n\t\t metadataMimeType: metadataMimeType,\n\t\t minorVersion: minorVersion,\n\t\t resumeToken: resumeToken,\n\t\t // streamId,\n\t\t streamId: 0,\n\t\t type: Frames_1.FrameTypes.SETUP,\n\t\t };\n\t\t readPayload(buffer, frame, offset);\n\t\t return frame;\n\t\t}\n\t\t/**\n\t\t * Writes an ERROR frame into a new buffer and returns it.\n\t\t *\n\t\t * Prefix size is for the error code (uint32 = 4).\n\t\t */\n\t\tvar ERROR_FIXED_SIZE = 4;\n\t\tfunction serializeErrorFrame(frame) {\n\t\t var messageLength = frame.message != null ? bufferExports.Buffer.byteLength(frame.message, \"utf8\") : 0;\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + ERROR_FIXED_SIZE + messageLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t offset = buffer.writeUInt32BE(frame.code, offset);\n\t\t if (frame.message != null) {\n\t\t buffer.write(frame.message, offset, offset + messageLength, \"utf8\");\n\t\t }\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfErrorFrame(frame) {\n\t\t var messageLength = frame.message != null ? bufferExports.Buffer.byteLength(frame.message, \"utf8\") : 0;\n\t\t return FRAME_HEADER_SIZE + ERROR_FIXED_SIZE + messageLength;\n\t\t}\n\t\t/**\n\t\t * Reads an ERROR frame from the buffer and returns it.\n\t\t */\n\t\tfunction deserializeErrorFrame(buffer, streamId, flags) {\n\t\t buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var code = buffer.readInt32BE(offset);\n\t\t offset += 4;\n\t\t // invariant(\n\t\t // code >= 0 && code <= MAX_CODE,\n\t\t // \"RSocketBinaryFraming: Invalid ERROR frame, expected code to be >= 0 and <= %s. Got `%s`.\",\n\t\t // MAX_CODE,\n\t\t // code\n\t\t // );\n\t\t var messageLength = buffer.length - offset;\n\t\t var message = \"\";\n\t\t if (messageLength > 0) {\n\t\t message = buffer.toString(\"utf8\", offset, offset + messageLength);\n\t\t offset += messageLength;\n\t\t }\n\t\t return {\n\t\t code: code,\n\t\t flags: flags,\n\t\t message: message,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.ERROR,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a KEEPALIVE frame into a new buffer and returns it.\n\t\t *\n\t\t * Prefix size is for the last received position (uint64 = 8).\n\t\t */\n\t\tvar KEEPALIVE_FIXED_SIZE = 8;\n\t\tfunction serializeKeepAliveFrame(frame) {\n\t\t var dataLength = frame.data != null ? frame.data.byteLength : 0;\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + KEEPALIVE_FIXED_SIZE + dataLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t offset = writeUInt64BE(buffer, frame.lastReceivedPosition, offset);\n\t\t if (frame.data != null) {\n\t\t frame.data.copy(buffer, offset);\n\t\t }\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfKeepAliveFrame(frame) {\n\t\t var dataLength = frame.data != null ? frame.data.byteLength : 0;\n\t\t return FRAME_HEADER_SIZE + KEEPALIVE_FIXED_SIZE + dataLength;\n\t\t}\n\t\t/**\n\t\t * Reads a KEEPALIVE frame from the buffer and returns it.\n\t\t */\n\t\tfunction deserializeKeepAliveFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId === 0,\n\t\t // \"RSocketBinaryFraming: Invalid KEEPALIVE frame, expected stream id to be 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var lastReceivedPosition = readUInt64BE(buffer, offset);\n\t\t offset += 8;\n\t\t var data = null;\n\t\t if (offset < buffer.length) {\n\t\t data = buffer.slice(offset, buffer.length);\n\t\t }\n\t\t return {\n\t\t data: data,\n\t\t flags: flags,\n\t\t lastReceivedPosition: lastReceivedPosition,\n\t\t // streamId,\n\t\t streamId: 0,\n\t\t type: Frames_1.FrameTypes.KEEPALIVE,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a LEASE frame into a new buffer and returns it.\n\t\t *\n\t\t * Prefix size is for the ttl (uint32) and requestcount (uint32).\n\t\t */\n\t\tvar LEASE_FIXED_SIZE = 8;\n\t\tfunction serializeLeaseFrame(frame) {\n\t\t var metaLength = frame.metadata != null ? frame.metadata.byteLength : 0;\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + LEASE_FIXED_SIZE + metaLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t offset = buffer.writeUInt32BE(frame.ttl, offset);\n\t\t offset = buffer.writeUInt32BE(frame.requestCount, offset);\n\t\t if (frame.metadata != null) {\n\t\t frame.metadata.copy(buffer, offset);\n\t\t }\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfLeaseFrame(frame) {\n\t\t var metaLength = frame.metadata != null ? frame.metadata.byteLength : 0;\n\t\t return FRAME_HEADER_SIZE + LEASE_FIXED_SIZE + metaLength;\n\t\t}\n\t\t/**\n\t\t * Reads a LEASE frame from the buffer and returns it.\n\t\t */\n\t\tfunction deserializeLeaseFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId === 0,\n\t\t // \"RSocketBinaryFraming: Invalid LEASE frame, expected stream id to be 0.\"\n\t\t // );\n\t\t // const length = buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var ttl = buffer.readUInt32BE(offset);\n\t\t offset += 4;\n\t\t var requestCount = buffer.readUInt32BE(offset);\n\t\t offset += 4;\n\t\t var metadata = null;\n\t\t if (offset < buffer.length) {\n\t\t metadata = buffer.slice(offset, buffer.length);\n\t\t }\n\t\t return {\n\t\t flags: flags,\n\t\t metadata: metadata,\n\t\t requestCount: requestCount,\n\t\t // streamId,\n\t\t streamId: 0,\n\t\t ttl: ttl,\n\t\t type: Frames_1.FrameTypes.LEASE,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a REQUEST_FNF or REQUEST_RESPONSE frame to a new buffer and returns\n\t\t * it.\n\t\t *\n\t\t * Note that these frames have the same shape and only differ in their type.\n\t\t */\n\t\tfunction serializeRequestFrame(frame) {\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + payloadLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t writePayload(frame, buffer, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfRequestFrame(frame) {\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t return FRAME_HEADER_SIZE + payloadLength;\n\t\t}\n\t\t/**\n\t\t * Writes a METADATA_PUSH frame to a new buffer and returns\n\t\t * it.\n\t\t */\n\t\tfunction serializeMetadataPushFrame(frame) {\n\t\t var metadata = frame.metadata;\n\t\t if (metadata != null) {\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + metadata.byteLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t metadata.copy(buffer, offset);\n\t\t return buffer;\n\t\t }\n\t\t else {\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE);\n\t\t writeHeader(frame, buffer);\n\t\t return buffer;\n\t\t }\n\t\t}\n\t\tfunction sizeOfMetadataPushFrame(frame) {\n\t\t return (FRAME_HEADER_SIZE + (frame.metadata != null ? frame.metadata.byteLength : 0));\n\t\t}\n\t\tfunction deserializeRequestFnfFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_FNF frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var frame = {\n\t\t data: null,\n\t\t flags: flags,\n\t\t // length,\n\t\t metadata: null,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.REQUEST_FNF,\n\t\t };\n\t\t readPayload(buffer, frame, FRAME_HEADER_SIZE);\n\t\t return frame;\n\t\t}\n\t\tfunction deserializeRequestResponseFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_RESPONSE frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t // const length = buffer.length;\n\t\t var frame = {\n\t\t data: null,\n\t\t flags: flags,\n\t\t // length,\n\t\t metadata: null,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.REQUEST_RESPONSE,\n\t\t };\n\t\t readPayload(buffer, frame, FRAME_HEADER_SIZE);\n\t\t return frame;\n\t\t}\n\t\tfunction deserializeMetadataPushFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId === 0,\n\t\t // \"RSocketBinaryFraming: Invalid METADATA_PUSH frame, expected stream id to be 0.\"\n\t\t // );\n\t\t // const length = buffer.length;\n\t\t return {\n\t\t flags: flags,\n\t\t // length,\n\t\t metadata: length === FRAME_HEADER_SIZE\n\t\t ? null\n\t\t : buffer.slice(FRAME_HEADER_SIZE, length),\n\t\t // streamId,\n\t\t streamId: 0,\n\t\t type: Frames_1.FrameTypes.METADATA_PUSH,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a REQUEST_STREAM or REQUEST_CHANNEL frame to a new buffer and returns\n\t\t * it.\n\t\t *\n\t\t * Note that these frames have the same shape and only differ in their type.\n\t\t *\n\t\t * Prefix size is for requestN (uint32 = 4).\n\t\t */\n\t\tvar REQUEST_MANY_HEADER = 4;\n\t\tfunction serializeRequestManyFrame(frame) {\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + REQUEST_MANY_HEADER + payloadLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t offset = buffer.writeUInt32BE(frame.requestN, offset);\n\t\t writePayload(frame, buffer, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfRequestManyFrame(frame) {\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t return FRAME_HEADER_SIZE + REQUEST_MANY_HEADER + payloadLength;\n\t\t}\n\t\tfunction deserializeRequestStreamFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_STREAM frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var requestN = buffer.readInt32BE(offset);\n\t\t offset += 4;\n\t\t // invariant(\n\t\t // requestN > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_STREAM frame, expected requestN to be > 0, got `%s`.\",\n\t\t // requestN\n\t\t // );\n\t\t var frame = {\n\t\t data: null,\n\t\t flags: flags,\n\t\t // length,\n\t\t metadata: null,\n\t\t requestN: requestN,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.REQUEST_STREAM,\n\t\t };\n\t\t readPayload(buffer, frame, offset);\n\t\t return frame;\n\t\t}\n\t\tfunction deserializeRequestChannelFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_CHANNEL frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var requestN = buffer.readInt32BE(offset);\n\t\t offset += 4;\n\t\t // invariant(\n\t\t // requestN > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_STREAM frame, expected requestN to be > 0, got `%s`.\",\n\t\t // requestN\n\t\t // );\n\t\t var frame = {\n\t\t data: null,\n\t\t flags: flags,\n\t\t // length,\n\t\t metadata: null,\n\t\t requestN: requestN,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.REQUEST_CHANNEL,\n\t\t };\n\t\t readPayload(buffer, frame, offset);\n\t\t return frame;\n\t\t}\n\t\t/**\n\t\t * Writes a REQUEST_N frame to a new buffer and returns it.\n\t\t *\n\t\t * Prefix size is for requestN (uint32 = 4).\n\t\t */\n\t\tvar REQUEST_N_HEADER = 4;\n\t\tfunction serializeRequestNFrame(frame) {\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + REQUEST_N_HEADER);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t buffer.writeUInt32BE(frame.requestN, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfRequestNFrame(frame) {\n\t\t return FRAME_HEADER_SIZE + REQUEST_N_HEADER;\n\t\t}\n\t\tfunction deserializeRequestNFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_N frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var requestN = buffer.readInt32BE(FRAME_HEADER_SIZE);\n\t\t // invariant(\n\t\t // requestN > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_STREAM frame, expected requestN to be > 0, got `%s`.\",\n\t\t // requestN\n\t\t // );\n\t\t return {\n\t\t flags: flags,\n\t\t // length,\n\t\t requestN: requestN,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.REQUEST_N,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a CANCEL frame to a new buffer and returns it.\n\t\t */\n\t\tfunction serializeCancelFrame(frame) {\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE);\n\t\t writeHeader(frame, buffer);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfCancelFrame(frame) {\n\t\t return FRAME_HEADER_SIZE;\n\t\t}\n\t\tfunction deserializeCancelFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid CANCEL frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t return {\n\t\t flags: flags,\n\t\t // length,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.CANCEL,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a PAYLOAD frame to a new buffer and returns it.\n\t\t */\n\t\tfunction serializePayloadFrame(frame) {\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + payloadLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t writePayload(frame, buffer, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfPayloadFrame(frame) {\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t return FRAME_HEADER_SIZE + payloadLength;\n\t\t}\n\t\tfunction deserializePayloadFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid PAYLOAD frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var frame = {\n\t\t data: null,\n\t\t flags: flags,\n\t\t // length,\n\t\t metadata: null,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.PAYLOAD,\n\t\t };\n\t\t readPayload(buffer, frame, FRAME_HEADER_SIZE);\n\t\t return frame;\n\t\t}\n\t\t/**\n\t\t * Writes a RESUME frame into a new buffer and returns it.\n\t\t *\n\t\t * Fixed size is:\n\t\t * - major version (uint16 = 2)\n\t\t * - minor version (uint16 = 2)\n\t\t * - token length (uint16 = 2)\n\t\t * - client position (uint64 = 8)\n\t\t * - server position (uint64 = 8)\n\t\t */\n\t\tvar RESUME_FIXED_SIZE = 22;\n\t\tfunction serializeResumeFrame(frame) {\n\t\t var resumeTokenLength = frame.resumeToken.byteLength;\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + RESUME_FIXED_SIZE + resumeTokenLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t offset = buffer.writeUInt16BE(frame.majorVersion, offset);\n\t\t offset = buffer.writeUInt16BE(frame.minorVersion, offset);\n\t\t offset = buffer.writeUInt16BE(resumeTokenLength, offset);\n\t\t offset += frame.resumeToken.copy(buffer, offset);\n\t\t offset = writeUInt64BE(buffer, frame.serverPosition, offset);\n\t\t writeUInt64BE(buffer, frame.clientPosition, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfResumeFrame(frame) {\n\t\t var resumeTokenLength = frame.resumeToken.byteLength;\n\t\t return FRAME_HEADER_SIZE + RESUME_FIXED_SIZE + resumeTokenLength;\n\t\t}\n\t\tfunction deserializeResumeFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId === 0,\n\t\t // \"RSocketBinaryFraming: Invalid RESUME frame, expected stream id to be 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var majorVersion = buffer.readUInt16BE(offset);\n\t\t offset += 2;\n\t\t var minorVersion = buffer.readUInt16BE(offset);\n\t\t offset += 2;\n\t\t var resumeTokenLength = buffer.readInt16BE(offset);\n\t\t offset += 2;\n\t\t // invariant(\n\t\t // resumeTokenLength >= 0 && resumeTokenLength <= MAX_RESUME_LENGTH,\n\t\t // \"RSocketBinaryFraming: Invalid SETUP frame, expected resumeToken length \" +\n\t\t // \"to be >= 0 and <= %s. Got `%s`.\",\n\t\t // MAX_RESUME_LENGTH,\n\t\t // resumeTokenLength\n\t\t // );\n\t\t var resumeToken = buffer.slice(offset, offset + resumeTokenLength);\n\t\t offset += resumeTokenLength;\n\t\t var serverPosition = readUInt64BE(buffer, offset);\n\t\t offset += 8;\n\t\t var clientPosition = readUInt64BE(buffer, offset);\n\t\t offset += 8;\n\t\t return {\n\t\t clientPosition: clientPosition,\n\t\t flags: flags,\n\t\t // length,\n\t\t majorVersion: majorVersion,\n\t\t minorVersion: minorVersion,\n\t\t resumeToken: resumeToken,\n\t\t serverPosition: serverPosition,\n\t\t // streamId,\n\t\t streamId: 0,\n\t\t type: Frames_1.FrameTypes.RESUME,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a RESUME_OK frame into a new buffer and returns it.\n\t\t *\n\t\t * Fixed size is:\n\t\t * - client position (uint64 = 8)\n\t\t */\n\t\tvar RESUME_OK_FIXED_SIZE = 8;\n\t\tfunction serializeResumeOkFrame(frame) {\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + RESUME_OK_FIXED_SIZE);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t writeUInt64BE(buffer, frame.clientPosition, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfResumeOkFrame(frame) {\n\t\t return FRAME_HEADER_SIZE + RESUME_OK_FIXED_SIZE;\n\t\t}\n\t\tfunction deserializeResumeOkFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId === 0,\n\t\t // \"RSocketBinaryFraming: Invalid RESUME frame, expected stream id to be 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var clientPosition = readUInt64BE(buffer, FRAME_HEADER_SIZE);\n\t\t return {\n\t\t clientPosition: clientPosition,\n\t\t flags: flags,\n\t\t // length,\n\t\t // streamId,\n\t\t streamId: 0,\n\t\t type: Frames_1.FrameTypes.RESUME_OK,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Write the header of the frame into the buffer.\n\t\t */\n\t\tfunction writeHeader(frame, buffer) {\n\t\t var offset = buffer.writeInt32BE(frame.streamId, 0);\n\t\t // shift frame to high 6 bits, extract lowest 10 bits from flags\n\t\t return buffer.writeUInt16BE((frame.type << exports$1.FRAME_TYPE_OFFFSET) | (frame.flags & exports$1.FLAGS_MASK), offset);\n\t\t}\n\t\t/**\n\t\t * Determine the length of the payload section of a frame. Only applies to\n\t\t * frame types that MAY have both metadata and data.\n\t\t */\n\t\tfunction getPayloadLength(frame) {\n\t\t var payloadLength = 0;\n\t\t if (frame.data != null) {\n\t\t payloadLength += frame.data.byteLength;\n\t\t }\n\t\t if (Frames_1.Flags.hasMetadata(frame.flags)) {\n\t\t payloadLength += UINT24_SIZE;\n\t\t if (frame.metadata != null) {\n\t\t payloadLength += frame.metadata.byteLength;\n\t\t }\n\t\t }\n\t\t return payloadLength;\n\t\t}\n\t\t/**\n\t\t * Write the payload of a frame into the given buffer. Only applies to frame\n\t\t * types that MAY have both metadata and data.\n\t\t */\n\t\tfunction writePayload(frame, buffer, offset) {\n\t\t if (Frames_1.Flags.hasMetadata(frame.flags)) {\n\t\t if (frame.metadata != null) {\n\t\t var metaLength = frame.metadata.byteLength;\n\t\t offset = writeUInt24BE(buffer, metaLength, offset);\n\t\t offset += frame.metadata.copy(buffer, offset);\n\t\t }\n\t\t else {\n\t\t offset = writeUInt24BE(buffer, 0, offset);\n\t\t }\n\t\t }\n\t\t if (frame.data != null) {\n\t\t frame.data.copy(buffer, offset);\n\t\t }\n\t\t}\n\t\t/**\n\t\t * Read the payload from a buffer and write it into the frame. Only applies to\n\t\t * frame types that MAY have both metadata and data.\n\t\t */\n\t\tfunction readPayload(buffer, frame, offset) {\n\t\t if (Frames_1.Flags.hasMetadata(frame.flags)) {\n\t\t var metaLength = readUInt24BE(buffer, offset);\n\t\t offset += UINT24_SIZE;\n\t\t if (metaLength > 0) {\n\t\t frame.metadata = buffer.slice(offset, offset + metaLength);\n\t\t offset += metaLength;\n\t\t }\n\t\t }\n\t\t if (offset < buffer.length) {\n\t\t frame.data = buffer.slice(offset, buffer.length);\n\t\t }\n\t\t}\n\t\t// exported as class to facilitate testing\n\t\tvar Deserializer = /** @class */ (function () {\n\t\t function Deserializer() {\n\t\t }\n\t\t /**\n\t\t * Read a frame from the buffer.\n\t\t */\n\t\t Deserializer.prototype.deserializeFrame = function (buffer) {\n\t\t return deserializeFrame(buffer);\n\t\t };\n\t\t /**\n\t\t * Reads a frame from a buffer that is prefixed with the frame length.\n\t\t */\n\t\t Deserializer.prototype.deserializeFrameWithLength = function (buffer) {\n\t\t return deserializeFrameWithLength(buffer);\n\t\t };\n\t\t /**\n\t\t * Given a buffer that may contain zero or more length-prefixed frames followed\n\t\t * by zero or more bytes of a (partial) subsequent frame, returns an array of\n\t\t * the frames and a int representing the buffer offset.\n\t\t */\n\t\t Deserializer.prototype.deserializeFrames = function (buffer) {\n\t\t return deserializeFrames(buffer);\n\t\t };\n\t\t return Deserializer;\n\t\t}());\n\t\texports$1.Deserializer = Deserializer;\n\t\t\n\t} (Codecs));\n\treturn Codecs;\n}\n\nvar Common = {};\n\nvar hasRequiredCommon;\n\nfunction requireCommon () {\n\tif (hasRequiredCommon) return Common;\n\thasRequiredCommon = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tObject.defineProperty(Common, \"__esModule\", { value: true });\n\t\n\treturn Common;\n}\n\nvar Deferred = {};\n\nvar hasRequiredDeferred;\n\nfunction requireDeferred () {\n\tif (hasRequiredDeferred) return Deferred;\n\thasRequiredDeferred = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __values = (Deferred && Deferred.__values) || function(o) {\n\t var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n\t if (m) return m.call(o);\n\t if (o && typeof o.length === \"number\") return {\n\t next: function () {\n\t if (o && i >= o.length) o = void 0;\n\t return { value: o && o[i++], done: !o };\n\t }\n\t };\n\t throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n\t};\n\tObject.defineProperty(Deferred, \"__esModule\", { value: true });\n\tDeferred.Deferred = void 0;\n\tvar Deferred$1 = /** @class */ (function () {\n\t function Deferred() {\n\t this._done = false;\n\t this.onCloseCallbacks = [];\n\t }\n\t Object.defineProperty(Deferred.prototype, \"done\", {\n\t get: function () {\n\t return this._done;\n\t },\n\t enumerable: false,\n\t configurable: true\n\t });\n\t /**\n\t * Signals to an observer that the Deferred operation has been closed, which invokes\n\t * the provided `onClose` callback.\n\t */\n\t Deferred.prototype.close = function (error) {\n\t var e_1, _a, e_2, _b;\n\t if (this.done) {\n\t console.warn(\"Trying to close for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t this._done = true;\n\t this._error = error;\n\t if (error) {\n\t try {\n\t for (var _c = __values(this.onCloseCallbacks), _d = _c.next(); !_d.done; _d = _c.next()) {\n\t var callback = _d.value;\n\t callback(error);\n\t }\n\t }\n\t catch (e_1_1) { e_1 = { error: e_1_1 }; }\n\t finally {\n\t try {\n\t if (_d && !_d.done && (_a = _c.return)) _a.call(_c);\n\t }\n\t finally { if (e_1) throw e_1.error; }\n\t }\n\t return;\n\t }\n\t try {\n\t for (var _e = __values(this.onCloseCallbacks), _f = _e.next(); !_f.done; _f = _e.next()) {\n\t var callback = _f.value;\n\t callback();\n\t }\n\t }\n\t catch (e_2_1) { e_2 = { error: e_2_1 }; }\n\t finally {\n\t try {\n\t if (_f && !_f.done && (_b = _e.return)) _b.call(_e);\n\t }\n\t finally { if (e_2) throw e_2.error; }\n\t }\n\t };\n\t /**\n\t * Registers a callback to be called when the Closeable is closed. optionally with an Error.\n\t */\n\t Deferred.prototype.onClose = function (callback) {\n\t if (this._done) {\n\t callback(this._error);\n\t return;\n\t }\n\t this.onCloseCallbacks.push(callback);\n\t };\n\t return Deferred;\n\t}());\n\tDeferred.Deferred = Deferred$1;\n\t\n\treturn Deferred;\n}\n\nvar Errors = {};\n\nvar hasRequiredErrors;\n\nfunction requireErrors () {\n\tif (hasRequiredErrors) return Errors;\n\thasRequiredErrors = 1;\n\t(function (exports$1) {\n\t\t/*\n\t\t * Copyright 2021-2022 the original author or authors.\n\t\t *\n\t\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t\t * you may not use this file except in compliance with the License.\n\t\t * You may obtain a copy of the License at\n\t\t *\n\t\t * http://www.apache.org/licenses/LICENSE-2.0\n\t\t *\n\t\t * Unless required by applicable law or agreed to in writing, software\n\t\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t\t * See the License for the specific language governing permissions and\n\t\t * limitations under the License.\n\t\t */\n\t\tvar __extends = (Errors && Errors.__extends) || (function () {\n\t\t var extendStatics = function (d, b) {\n\t\t extendStatics = Object.setPrototypeOf ||\n\t\t ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n\t\t function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n\t\t return extendStatics(d, b);\n\t\t };\n\t\t return function (d, b) {\n\t\t if (typeof b !== \"function\" && b !== null)\n\t\t throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n\t\t extendStatics(d, b);\n\t\t function __() { this.constructor = d; }\n\t\t d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n\t\t };\n\t\t})();\n\t\tObject.defineProperty(exports$1, \"__esModule\", { value: true });\n\t\texports$1.ErrorCodes = exports$1.RSocketError = void 0;\n\t\tvar RSocketError = /** @class */ (function (_super) {\n\t\t __extends(RSocketError, _super);\n\t\t function RSocketError(code, message) {\n\t\t var _this = _super.call(this, message) || this;\n\t\t _this.code = code;\n\t\t return _this;\n\t\t }\n\t\t return RSocketError;\n\t\t}(Error));\n\t\texports$1.RSocketError = RSocketError;\n\t\t(function (ErrorCodes) {\n\t\t ErrorCodes[ErrorCodes[\"RESERVED\"] = 0] = \"RESERVED\";\n\t\t ErrorCodes[ErrorCodes[\"INVALID_SETUP\"] = 1] = \"INVALID_SETUP\";\n\t\t ErrorCodes[ErrorCodes[\"UNSUPPORTED_SETUP\"] = 2] = \"UNSUPPORTED_SETUP\";\n\t\t ErrorCodes[ErrorCodes[\"REJECTED_SETUP\"] = 3] = \"REJECTED_SETUP\";\n\t\t ErrorCodes[ErrorCodes[\"REJECTED_RESUME\"] = 4] = \"REJECTED_RESUME\";\n\t\t ErrorCodes[ErrorCodes[\"CONNECTION_CLOSE\"] = 258] = \"CONNECTION_CLOSE\";\n\t\t ErrorCodes[ErrorCodes[\"CONNECTION_ERROR\"] = 257] = \"CONNECTION_ERROR\";\n\t\t ErrorCodes[ErrorCodes[\"APPLICATION_ERROR\"] = 513] = \"APPLICATION_ERROR\";\n\t\t ErrorCodes[ErrorCodes[\"REJECTED\"] = 514] = \"REJECTED\";\n\t\t ErrorCodes[ErrorCodes[\"CANCELED\"] = 515] = \"CANCELED\";\n\t\t ErrorCodes[ErrorCodes[\"INVALID\"] = 516] = \"INVALID\";\n\t\t ErrorCodes[ErrorCodes[\"RESERVED_EXTENSION\"] = 4294967295] = \"RESERVED_EXTENSION\";\n\t\t})(exports$1.ErrorCodes || (exports$1.ErrorCodes = {}));\n\t\t\n\t} (Errors));\n\treturn Errors;\n}\n\nvar RSocket = {};\n\nvar hasRequiredRSocket;\n\nfunction requireRSocket () {\n\tif (hasRequiredRSocket) return RSocket;\n\thasRequiredRSocket = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tObject.defineProperty(RSocket, \"__esModule\", { value: true });\n\t\n\treturn RSocket;\n}\n\nvar RSocketConnector = {};\n\nvar ClientServerMultiplexerDemultiplexer = {};\n\nvar hasRequiredClientServerMultiplexerDemultiplexer;\n\nfunction requireClientServerMultiplexerDemultiplexer () {\n\tif (hasRequiredClientServerMultiplexerDemultiplexer) return ClientServerMultiplexerDemultiplexer;\n\thasRequiredClientServerMultiplexerDemultiplexer = 1;\n\t(function (exports$1) {\n\t\t/*\n\t\t * Copyright 2021-2022 the original author or authors.\n\t\t *\n\t\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t\t * you may not use this file except in compliance with the License.\n\t\t * You may obtain a copy of the License at\n\t\t *\n\t\t * http://www.apache.org/licenses/LICENSE-2.0\n\t\t *\n\t\t * Unless required by applicable law or agreed to in writing, software\n\t\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t\t * See the License for the specific language governing permissions and\n\t\t * limitations under the License.\n\t\t */\n\t\tvar __extends = (ClientServerMultiplexerDemultiplexer && ClientServerMultiplexerDemultiplexer.__extends) || (function () {\n\t\t var extendStatics = function (d, b) {\n\t\t extendStatics = Object.setPrototypeOf ||\n\t\t ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n\t\t function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n\t\t return extendStatics(d, b);\n\t\t };\n\t\t return function (d, b) {\n\t\t if (typeof b !== \"function\" && b !== null)\n\t\t throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n\t\t extendStatics(d, b);\n\t\t function __() { this.constructor = d; }\n\t\t d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n\t\t };\n\t\t})();\n\t\tvar __awaiter = (ClientServerMultiplexerDemultiplexer && ClientServerMultiplexerDemultiplexer.__awaiter) || function (thisArg, _arguments, P, generator) {\n\t\t function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n\t\t return new (P || (P = Promise))(function (resolve, reject) {\n\t\t function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n\t\t function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n\t\t function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n\t\t step((generator = generator.apply(thisArg, _arguments || [])).next());\n\t\t });\n\t\t};\n\t\tvar __generator = (ClientServerMultiplexerDemultiplexer && ClientServerMultiplexerDemultiplexer.__generator) || function (thisArg, body) {\n\t\t var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n\t\t return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n\t\t function verb(n) { return function (v) { return step([n, v]); }; }\n\t\t function step(op) {\n\t\t if (f) throw new TypeError(\"Generator is already executing.\");\n\t\t while (_) try {\n\t\t if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n\t\t if (y = 0, t) op = [op[0] & 2, t.value];\n\t\t switch (op[0]) {\n\t\t case 0: case 1: t = op; break;\n\t\t case 4: _.label++; return { value: op[1], done: false };\n\t\t case 5: _.label++; y = op[1]; op = [0]; continue;\n\t\t case 7: op = _.ops.pop(); _.trys.pop(); continue;\n\t\t default:\n\t\t if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n\t\t if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n\t\t if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n\t\t if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n\t\t if (t[2]) _.ops.pop();\n\t\t _.trys.pop(); continue;\n\t\t }\n\t\t op = body.call(thisArg, _);\n\t\t } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n\t\t if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n\t\t }\n\t\t};\n\t\tObject.defineProperty(exports$1, \"__esModule\", { value: true });\n\t\texports$1.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = exports$1.ResumableClientServerInputMultiplexerDemultiplexer = exports$1.ClientServerInputMultiplexerDemultiplexer = exports$1.StreamIdGenerator = void 0;\n\t\tvar _1 = requireDist();\n\t\tvar Deferred_1 = requireDeferred();\n\t\tvar Errors_1 = requireErrors();\n\t\tvar Frames_1 = requireFrames();\n\t\t(function (StreamIdGenerator) {\n\t\t function create(seedId) {\n\t\t return new StreamIdGeneratorImpl(seedId);\n\t\t }\n\t\t StreamIdGenerator.create = create;\n\t\t var StreamIdGeneratorImpl = /** @class */ (function () {\n\t\t function StreamIdGeneratorImpl(currentId) {\n\t\t this.currentId = currentId;\n\t\t }\n\t\t StreamIdGeneratorImpl.prototype.next = function (handler) {\n\t\t var nextId = this.currentId + 2;\n\t\t if (!handler(nextId)) {\n\t\t return;\n\t\t }\n\t\t this.currentId = nextId;\n\t\t };\n\t\t return StreamIdGeneratorImpl;\n\t\t }());\n\t\t})(exports$1.StreamIdGenerator || (exports$1.StreamIdGenerator = {}));\n\t\tvar ClientServerInputMultiplexerDemultiplexer = /** @class */ (function (_super) {\n\t\t __extends(ClientServerInputMultiplexerDemultiplexer, _super);\n\t\t function ClientServerInputMultiplexerDemultiplexer(streamIdSupplier, outbound, closeable) {\n\t\t var _this = _super.call(this) || this;\n\t\t _this.streamIdSupplier = streamIdSupplier;\n\t\t _this.outbound = outbound;\n\t\t _this.closeable = closeable;\n\t\t _this.registry = {};\n\t\t closeable.onClose(_this.close.bind(_this));\n\t\t return _this;\n\t\t }\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.handle = function (frame) {\n\t\t if (Frames_1.Frame.isConnection(frame)) {\n\t\t if (frame.type === _1.FrameTypes.RESERVED) {\n\t\t // TODO: throw\n\t\t return;\n\t\t }\n\t\t this.connectionFramesHandler.handle(frame);\n\t\t // TODO: Connection Handler\n\t\t }\n\t\t else if (Frames_1.Frame.isRequest(frame)) {\n\t\t if (this.registry[frame.streamId]) {\n\t\t // TODO: Send error and close connection\n\t\t return;\n\t\t }\n\t\t this.requestFramesHandler.handle(frame, this);\n\t\t }\n\t\t else {\n\t\t var handler = this.registry[frame.streamId];\n\t\t if (!handler) {\n\t\t // TODO: add validation\n\t\t return;\n\t\t }\n\t\t handler.handle(frame);\n\t\t }\n\t\t // TODO: add extensions support\n\t\t };\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.connectionInbound = function (handler) {\n\t\t if (this.connectionFramesHandler) {\n\t\t throw new Error(\"Connection frame handler has already been installed\");\n\t\t }\n\t\t this.connectionFramesHandler = handler;\n\t\t };\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.handleRequestStream = function (handler) {\n\t\t if (this.requestFramesHandler) {\n\t\t throw new Error(\"Stream handler has already been installed\");\n\t\t }\n\t\t this.requestFramesHandler = handler;\n\t\t };\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.send = function (frame) {\n\t\t this.outbound.send(frame);\n\t\t };\n\t\t Object.defineProperty(ClientServerInputMultiplexerDemultiplexer.prototype, \"connectionOutbound\", {\n\t\t get: function () {\n\t\t return this;\n\t\t },\n\t\t enumerable: false,\n\t\t configurable: true\n\t\t });\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.createRequestStream = function (streamHandler) {\n\t\t var _this = this;\n\t\t // handle requester side stream registration\n\t\t if (this.done) {\n\t\t streamHandler.handleReject(new Error(\"Already closed\"));\n\t\t return;\n\t\t }\n\t\t var registry = this.registry;\n\t\t this.streamIdSupplier.next(function (streamId) { return streamHandler.handleReady(streamId, _this); }, Object.keys(registry));\n\t\t };\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.connect = function (handler) {\n\t\t this.registry[handler.streamId] = handler;\n\t\t };\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.disconnect = function (stream) {\n\t\t delete this.registry[stream.streamId];\n\t\t };\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.close = function (error) {\n\t\t if (this.done) {\n\t\t _super.prototype.close.call(this, error);\n\t\t return;\n\t\t }\n\t\t for (var streamId in this.registry) {\n\t\t var stream = this.registry[streamId];\n\t\t stream.close(new Error(\"Closed. \".concat(error ? \"Original cause [\".concat(error, \"].\") : \"\")));\n\t\t }\n\t\t _super.prototype.close.call(this, error);\n\t\t };\n\t\t return ClientServerInputMultiplexerDemultiplexer;\n\t\t}(Deferred_1.Deferred));\n\t\texports$1.ClientServerInputMultiplexerDemultiplexer = ClientServerInputMultiplexerDemultiplexer;\n\t\tvar ResumableClientServerInputMultiplexerDemultiplexer = /** @class */ (function (_super) {\n\t\t __extends(ResumableClientServerInputMultiplexerDemultiplexer, _super);\n\t\t function ResumableClientServerInputMultiplexerDemultiplexer(streamIdSupplier, outbound, closeable, frameStore, token, sessionStoreOrReconnector, sessionTimeout) {\n\t\t var _this = _super.call(this, streamIdSupplier, outbound, new Deferred_1.Deferred()) || this;\n\t\t _this.frameStore = frameStore;\n\t\t _this.token = token;\n\t\t _this.sessionTimeout = sessionTimeout;\n\t\t if (sessionStoreOrReconnector instanceof Function) {\n\t\t _this.reconnector = sessionStoreOrReconnector;\n\t\t }\n\t\t else {\n\t\t _this.sessionStore = sessionStoreOrReconnector;\n\t\t }\n\t\t closeable.onClose(_this.handleConnectionClose.bind(_this));\n\t\t return _this;\n\t\t }\n\t\t ResumableClientServerInputMultiplexerDemultiplexer.prototype.send = function (frame) {\n\t\t if (Frames_1.Frame.isConnection(frame)) {\n\t\t if (frame.type === _1.FrameTypes.KEEPALIVE) {\n\t\t frame.lastReceivedPosition = this.frameStore.lastReceivedFramePosition;\n\t\t }\n\t\t else if (frame.type === _1.FrameTypes.ERROR) {\n\t\t this.outbound.send(frame);\n\t\t if (this.sessionStore) {\n\t\t delete this.sessionStore[this.token];\n\t\t }\n\t\t _super.prototype.close.call(this, new Errors_1.RSocketError(frame.code, frame.message));\n\t\t return;\n\t\t }\n\t\t }\n\t\t else {\n\t\t this.frameStore.store(frame);\n\t\t }\n\t\t this.outbound.send(frame);\n\t\t };\n\t\t ResumableClientServerInputMultiplexerDemultiplexer.prototype.handle = function (frame) {\n\t\t if (Frames_1.Frame.isConnection(frame)) {\n\t\t if (frame.type === _1.FrameTypes.KEEPALIVE) {\n\t\t try {\n\t\t this.frameStore.dropTo(frame.lastReceivedPosition);\n\t\t }\n\t\t catch (re) {\n\t\t this.outbound.send({\n\t\t type: _1.FrameTypes.ERROR,\n\t\t streamId: 0,\n\t\t flags: _1.Flags.NONE,\n\t\t code: re.code,\n\t\t message: re.message,\n\t\t });\n\t\t this.close(re);\n\t\t }\n\t\t }\n\t\t else if (frame.type === _1.FrameTypes.ERROR) {\n\t\t _super.prototype.handle.call(this, frame);\n\t\t if (this.sessionStore) {\n\t\t delete this.sessionStore[this.token];\n\t\t }\n\t\t _super.prototype.close.call(this, new Errors_1.RSocketError(frame.code, frame.message));\n\t\t return;\n\t\t }\n\t\t }\n\t\t else {\n\t\t this.frameStore.record(frame);\n\t\t }\n\t\t _super.prototype.handle.call(this, frame);\n\t\t };\n\t\t ResumableClientServerInputMultiplexerDemultiplexer.prototype.resume = function (frame, outbound, closeable) {\n\t\t this.outbound = outbound;\n\t\t switch (frame.type) {\n\t\t case _1.FrameTypes.RESUME: {\n\t\t clearTimeout(this.timeoutId);\n\t\t if (this.frameStore.lastReceivedFramePosition < frame.clientPosition) {\n\t\t var e = new Errors_1.RSocketError(_1.ErrorCodes.REJECTED_RESUME, \"Impossible to resume since first available client frame position is greater than last received server frame position\");\n\t\t this.outbound.send({\n\t\t type: _1.FrameTypes.ERROR,\n\t\t streamId: 0,\n\t\t flags: _1.Flags.NONE,\n\t\t code: e.code,\n\t\t message: e.message,\n\t\t });\n\t\t this.close(e);\n\t\t return;\n\t\t }\n\t\t try {\n\t\t this.frameStore.dropTo(frame.serverPosition);\n\t\t }\n\t\t catch (re) {\n\t\t this.outbound.send({\n\t\t type: _1.FrameTypes.ERROR,\n\t\t streamId: 0,\n\t\t flags: _1.Flags.NONE,\n\t\t code: re.code,\n\t\t message: re.message,\n\t\t });\n\t\t this.close(re);\n\t\t return;\n\t\t }\n\t\t this.outbound.send({\n\t\t type: _1.FrameTypes.RESUME_OK,\n\t\t streamId: 0,\n\t\t flags: _1.Flags.NONE,\n\t\t clientPosition: this.frameStore.lastReceivedFramePosition,\n\t\t });\n\t\t break;\n\t\t }\n\t\t case _1.FrameTypes.RESUME_OK: {\n\t\t try {\n\t\t this.frameStore.dropTo(frame.clientPosition);\n\t\t }\n\t\t catch (re) {\n\t\t this.outbound.send({\n\t\t type: _1.FrameTypes.ERROR,\n\t\t streamId: 0,\n\t\t flags: _1.Flags.NONE,\n\t\t code: re.code,\n\t\t message: re.message,\n\t\t });\n\t\t this.close(re);\n\t\t }\n\t\t break;\n\t\t }\n\t\t }\n\t\t this.frameStore.drain(this.outbound.send.bind(this.outbound));\n\t\t closeable.onClose(this.handleConnectionClose.bind(this));\n\t\t this.connectionFramesHandler.resume();\n\t\t };\n\t\t ResumableClientServerInputMultiplexerDemultiplexer.prototype.handleConnectionClose = function (_error) {\n\t\t return __awaiter(this, void 0, void 0, function () {\n\t\t var e_1;\n\t\t return __generator(this, function (_a) {\n\t\t switch (_a.label) {\n\t\t case 0:\n\t\t this.connectionFramesHandler.pause();\n\t\t if (!this.reconnector) return [3 /*break*/, 5];\n\t\t _a.label = 1;\n\t\t case 1:\n\t\t _a.trys.push([1, 3, , 4]);\n\t\t return [4 /*yield*/, this.reconnector(this, this.frameStore)];\n\t\t case 2:\n\t\t _a.sent();\n\t\t return [3 /*break*/, 4];\n\t\t case 3:\n\t\t e_1 = _a.sent();\n\t\t this.close(e_1);\n\t\t return [3 /*break*/, 4];\n\t\t case 4: return [3 /*break*/, 6];\n\t\t case 5:\n\t\t this.timeoutId = setTimeout(this.close.bind(this), this.sessionTimeout);\n\t\t _a.label = 6;\n\t\t case 6: return [2 /*return*/];\n\t\t }\n\t\t });\n\t\t });\n\t\t };\n\t\t return ResumableClientServerInputMultiplexerDemultiplexer;\n\t\t}(ClientServerInputMultiplexerDemultiplexer));\n\t\texports$1.ResumableClientServerInputMultiplexerDemultiplexer = ResumableClientServerInputMultiplexerDemultiplexer;\n\t\tvar ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = /** @class */ (function () {\n\t\t function ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer(outbound, closeable, delegate) {\n\t\t this.outbound = outbound;\n\t\t this.closeable = closeable;\n\t\t this.delegate = delegate;\n\t\t this.resumed = false;\n\t\t }\n\t\t ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype.close = function () {\n\t\t this.delegate.close();\n\t\t };\n\t\t ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype.onClose = function (callback) {\n\t\t this.delegate.onClose(callback);\n\t\t };\n\t\t Object.defineProperty(ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype, \"connectionOutbound\", {\n\t\t get: function () {\n\t\t return this.delegate.connectionOutbound;\n\t\t },\n\t\t enumerable: false,\n\t\t configurable: true\n\t\t });\n\t\t ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype.createRequestStream = function (streamHandler) {\n\t\t this.delegate.createRequestStream(streamHandler);\n\t\t };\n\t\t ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype.connectionInbound = function (handler) {\n\t\t this.delegate.connectionInbound(handler);\n\t\t };\n\t\t ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype.handleRequestStream = function (handler) {\n\t\t this.delegate.handleRequestStream(handler);\n\t\t };\n\t\t ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype.handle = function (frame) {\n\t\t var _this = this;\n\t\t if (!this.resumed) {\n\t\t if (frame.type === _1.FrameTypes.RESUME_OK) {\n\t\t this.resumed = true;\n\t\t this.delegate.resume(frame, this.outbound, this.closeable);\n\t\t return;\n\t\t }\n\t\t else {\n\t\t this.outbound.send({\n\t\t type: _1.FrameTypes.ERROR,\n\t\t streamId: 0,\n\t\t code: _1.ErrorCodes.CONNECTION_ERROR,\n\t\t message: \"Incomplete RESUME handshake. Unexpected frame \".concat(frame.type, \" received\"),\n\t\t flags: _1.Flags.NONE,\n\t\t });\n\t\t this.closeable.close();\n\t\t this.closeable.onClose(function () {\n\t\t return _this.delegate.close(new Errors_1.RSocketError(_1.ErrorCodes.CONNECTION_ERROR, \"Incomplete RESUME handshake. Unexpected frame \".concat(frame.type, \" received\")));\n\t\t });\n\t\t }\n\t\t return;\n\t\t }\n\t\t this.delegate.handle(frame);\n\t\t };\n\t\t return ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer;\n\t\t}());\n\t\texports$1.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer;\n\t\t\n\t} (ClientServerMultiplexerDemultiplexer));\n\treturn ClientServerMultiplexerDemultiplexer;\n}\n\nvar RSocketSupport = {};\n\nvar RequestChannelStream = {};\n\nvar Fragmenter = {};\n\nvar hasRequiredFragmenter;\n\nfunction requireFragmenter () {\n\tif (hasRequiredFragmenter) return Fragmenter;\n\thasRequiredFragmenter = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __generator = (Fragmenter && Fragmenter.__generator) || function (thisArg, body) {\n\t var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n\t return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n\t function verb(n) { return function (v) { return step([n, v]); }; }\n\t function step(op) {\n\t if (f) throw new TypeError(\"Generator is already executing.\");\n\t while (_) try {\n\t if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n\t if (y = 0, t) op = [op[0] & 2, t.value];\n\t switch (op[0]) {\n\t case 0: case 1: t = op; break;\n\t case 4: _.label++; return { value: op[1], done: false };\n\t case 5: _.label++; y = op[1]; op = [0]; continue;\n\t case 7: op = _.ops.pop(); _.trys.pop(); continue;\n\t default:\n\t if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n\t if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n\t if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n\t if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n\t if (t[2]) _.ops.pop();\n\t _.trys.pop(); continue;\n\t }\n\t op = body.call(thisArg, _);\n\t } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n\t if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n\t }\n\t};\n\tObject.defineProperty(Fragmenter, \"__esModule\", { value: true });\n\tFragmenter.fragmentWithRequestN = Fragmenter.fragment = Fragmenter.isFragmentable = void 0;\n\tvar Frames_1 = requireFrames();\n\tfunction isFragmentable(payload, fragmentSize, frameType) {\n\t if (fragmentSize === 0) {\n\t return false;\n\t }\n\t return (payload.data.byteLength +\n\t (payload.metadata ? payload.metadata.byteLength + Frames_1.Lengths.METADATA : 0) +\n\t (frameType == Frames_1.FrameTypes.REQUEST_STREAM ||\n\t frameType == Frames_1.FrameTypes.REQUEST_CHANNEL\n\t ? Frames_1.Lengths.REQUEST\n\t : 0) >\n\t fragmentSize);\n\t}\n\tFragmenter.isFragmentable = isFragmentable;\n\tfunction fragment(streamId, payload, fragmentSize, frameType, isComplete) {\n\t var dataLength, firstFrame, remaining, metadata, metadataLength, metadataPosition, nextMetadataPosition, nextMetadataPosition, dataPosition, data, nextDataPosition, nextDataPosition;\n\t var _a, _b;\n\t if (isComplete === void 0) { isComplete = false; }\n\t return __generator(this, function (_c) {\n\t switch (_c.label) {\n\t case 0:\n\t dataLength = (_b = (_a = payload.data) === null || _a === void 0 ? void 0 : _a.byteLength) !== null && _b !== void 0 ? _b : 0;\n\t firstFrame = frameType !== Frames_1.FrameTypes.PAYLOAD;\n\t remaining = fragmentSize;\n\t if (!payload.metadata) return [3 /*break*/, 6];\n\t metadataLength = payload.metadata.byteLength;\n\t if (!(metadataLength === 0)) return [3 /*break*/, 1];\n\t remaining -= Frames_1.Lengths.METADATA;\n\t metadata = bufferExports.Buffer.allocUnsafe(0);\n\t return [3 /*break*/, 6];\n\t case 1:\n\t metadataPosition = 0;\n\t if (!firstFrame) return [3 /*break*/, 3];\n\t remaining -= Frames_1.Lengths.METADATA;\n\t nextMetadataPosition = Math.min(metadataLength, metadataPosition + remaining);\n\t metadata = payload.metadata.slice(metadataPosition, nextMetadataPosition);\n\t remaining -= metadata.byteLength;\n\t metadataPosition = nextMetadataPosition;\n\t if (!(remaining === 0)) return [3 /*break*/, 3];\n\t firstFrame = false;\n\t return [4 /*yield*/, {\n\t type: frameType,\n\t flags: Frames_1.Flags.FOLLOWS | Frames_1.Flags.METADATA,\n\t data: undefined,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 2:\n\t _c.sent();\n\t metadata = undefined;\n\t remaining = fragmentSize;\n\t _c.label = 3;\n\t case 3:\n\t if (!(metadataPosition < metadataLength)) return [3 /*break*/, 6];\n\t remaining -= Frames_1.Lengths.METADATA;\n\t nextMetadataPosition = Math.min(metadataLength, metadataPosition + remaining);\n\t metadata = payload.metadata.slice(metadataPosition, nextMetadataPosition);\n\t remaining -= metadata.byteLength;\n\t metadataPosition = nextMetadataPosition;\n\t if (!(remaining === 0 || dataLength === 0)) return [3 /*break*/, 5];\n\t return [4 /*yield*/, {\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.NEXT |\n\t Frames_1.Flags.METADATA |\n\t (metadataPosition === metadataLength &&\n\t isComplete &&\n\t dataLength === 0\n\t ? Frames_1.Flags.COMPLETE\n\t : Frames_1.Flags.FOLLOWS),\n\t data: undefined,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 4:\n\t _c.sent();\n\t metadata = undefined;\n\t remaining = fragmentSize;\n\t _c.label = 5;\n\t case 5: return [3 /*break*/, 3];\n\t case 6:\n\t dataPosition = 0;\n\t if (!firstFrame) return [3 /*break*/, 8];\n\t nextDataPosition = Math.min(dataLength, dataPosition + remaining);\n\t data = payload.data.slice(dataPosition, nextDataPosition);\n\t remaining -= data.byteLength;\n\t dataPosition = nextDataPosition;\n\t return [4 /*yield*/, {\n\t type: frameType,\n\t flags: Frames_1.Flags.FOLLOWS | (metadata ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE),\n\t data: data,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 7:\n\t _c.sent();\n\t metadata = undefined;\n\t data = undefined;\n\t remaining = fragmentSize;\n\t _c.label = 8;\n\t case 8:\n\t if (!(dataPosition < dataLength)) return [3 /*break*/, 10];\n\t nextDataPosition = Math.min(dataLength, dataPosition + remaining);\n\t data = payload.data.slice(dataPosition, nextDataPosition);\n\t remaining -= data.byteLength;\n\t dataPosition = nextDataPosition;\n\t return [4 /*yield*/, {\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: dataPosition === dataLength\n\t ? (isComplete ? Frames_1.Flags.COMPLETE : Frames_1.Flags.NONE) |\n\t Frames_1.Flags.NEXT |\n\t (metadata ? Frames_1.Flags.METADATA : 0)\n\t : Frames_1.Flags.FOLLOWS | Frames_1.Flags.NEXT | (metadata ? Frames_1.Flags.METADATA : 0),\n\t data: data,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 9:\n\t _c.sent();\n\t metadata = undefined;\n\t data = undefined;\n\t remaining = fragmentSize;\n\t return [3 /*break*/, 8];\n\t case 10: return [2 /*return*/];\n\t }\n\t });\n\t}\n\tFragmenter.fragment = fragment;\n\tfunction fragmentWithRequestN(streamId, payload, fragmentSize, frameType, requestN, isComplete) {\n\t var dataLength, firstFrame, remaining, metadata, metadataLength, metadataPosition, nextMetadataPosition, nextMetadataPosition, dataPosition, data, nextDataPosition, nextDataPosition;\n\t var _a, _b;\n\t if (isComplete === void 0) { isComplete = false; }\n\t return __generator(this, function (_c) {\n\t switch (_c.label) {\n\t case 0:\n\t dataLength = (_b = (_a = payload.data) === null || _a === void 0 ? void 0 : _a.byteLength) !== null && _b !== void 0 ? _b : 0;\n\t firstFrame = true;\n\t remaining = fragmentSize;\n\t if (!payload.metadata) return [3 /*break*/, 6];\n\t metadataLength = payload.metadata.byteLength;\n\t if (!(metadataLength === 0)) return [3 /*break*/, 1];\n\t remaining -= Frames_1.Lengths.METADATA;\n\t metadata = bufferExports.Buffer.allocUnsafe(0);\n\t return [3 /*break*/, 6];\n\t case 1:\n\t metadataPosition = 0;\n\t if (!firstFrame) return [3 /*break*/, 3];\n\t remaining -= Frames_1.Lengths.METADATA + Frames_1.Lengths.REQUEST;\n\t nextMetadataPosition = Math.min(metadataLength, metadataPosition + remaining);\n\t metadata = payload.metadata.slice(metadataPosition, nextMetadataPosition);\n\t remaining -= metadata.byteLength;\n\t metadataPosition = nextMetadataPosition;\n\t if (!(remaining === 0)) return [3 /*break*/, 3];\n\t firstFrame = false;\n\t return [4 /*yield*/, {\n\t type: frameType,\n\t flags: Frames_1.Flags.FOLLOWS | Frames_1.Flags.METADATA,\n\t data: undefined,\n\t requestN: requestN,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 2:\n\t _c.sent();\n\t metadata = undefined;\n\t remaining = fragmentSize;\n\t _c.label = 3;\n\t case 3:\n\t if (!(metadataPosition < metadataLength)) return [3 /*break*/, 6];\n\t remaining -= Frames_1.Lengths.METADATA;\n\t nextMetadataPosition = Math.min(metadataLength, metadataPosition + remaining);\n\t metadata = payload.metadata.slice(metadataPosition, nextMetadataPosition);\n\t remaining -= metadata.byteLength;\n\t metadataPosition = nextMetadataPosition;\n\t if (!(remaining === 0 || dataLength === 0)) return [3 /*break*/, 5];\n\t return [4 /*yield*/, {\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.NEXT |\n\t Frames_1.Flags.METADATA |\n\t (metadataPosition === metadataLength &&\n\t isComplete &&\n\t dataLength === 0\n\t ? Frames_1.Flags.COMPLETE\n\t : Frames_1.Flags.FOLLOWS),\n\t data: undefined,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 4:\n\t _c.sent();\n\t metadata = undefined;\n\t remaining = fragmentSize;\n\t _c.label = 5;\n\t case 5: return [3 /*break*/, 3];\n\t case 6:\n\t dataPosition = 0;\n\t if (!firstFrame) return [3 /*break*/, 8];\n\t remaining -= Frames_1.Lengths.REQUEST;\n\t nextDataPosition = Math.min(dataLength, dataPosition + remaining);\n\t data = payload.data.slice(dataPosition, nextDataPosition);\n\t remaining -= data.byteLength;\n\t dataPosition = nextDataPosition;\n\t return [4 /*yield*/, {\n\t type: frameType,\n\t flags: Frames_1.Flags.FOLLOWS | (metadata ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE),\n\t data: data,\n\t requestN: requestN,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 7:\n\t _c.sent();\n\t metadata = undefined;\n\t data = undefined;\n\t remaining = fragmentSize;\n\t _c.label = 8;\n\t case 8:\n\t if (!(dataPosition < dataLength)) return [3 /*break*/, 10];\n\t nextDataPosition = Math.min(dataLength, dataPosition + remaining);\n\t data = payload.data.slice(dataPosition, nextDataPosition);\n\t remaining -= data.byteLength;\n\t dataPosition = nextDataPosition;\n\t return [4 /*yield*/, {\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: dataPosition === dataLength\n\t ? (isComplete ? Frames_1.Flags.COMPLETE : Frames_1.Flags.NONE) |\n\t Frames_1.Flags.NEXT |\n\t (metadata ? Frames_1.Flags.METADATA : 0)\n\t : Frames_1.Flags.FOLLOWS | Frames_1.Flags.NEXT | (metadata ? Frames_1.Flags.METADATA : 0),\n\t data: data,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 9:\n\t _c.sent();\n\t metadata = undefined;\n\t data = undefined;\n\t remaining = fragmentSize;\n\t return [3 /*break*/, 8];\n\t case 10: return [2 /*return*/];\n\t }\n\t });\n\t}\n\tFragmenter.fragmentWithRequestN = fragmentWithRequestN;\n\t\n\treturn Fragmenter;\n}\n\nvar Reassembler = {};\n\nvar hasRequiredReassembler;\n\nfunction requireReassembler () {\n\tif (hasRequiredReassembler) return Reassembler;\n\thasRequiredReassembler = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tObject.defineProperty(Reassembler, \"__esModule\", { value: true });\n\tReassembler.cancel = Reassembler.reassemble = Reassembler.add = void 0;\n\tfunction add(holder, dataFragment, metadataFragment) {\n\t if (!holder.hasFragments) {\n\t holder.hasFragments = true;\n\t holder.data = dataFragment;\n\t if (metadataFragment) {\n\t holder.metadata = metadataFragment;\n\t }\n\t return true;\n\t }\n\t // TODO: add validation\n\t holder.data = holder.data\n\t ? bufferExports.Buffer.concat([holder.data, dataFragment])\n\t : dataFragment;\n\t if (holder.metadata && metadataFragment) {\n\t holder.metadata = bufferExports.Buffer.concat([holder.metadata, metadataFragment]);\n\t }\n\t return true;\n\t}\n\tReassembler.add = add;\n\tfunction reassemble(holder, dataFragment, metadataFragment) {\n\t // TODO: add validation\n\t holder.hasFragments = false;\n\t var data = holder.data\n\t ? bufferExports.Buffer.concat([holder.data, dataFragment])\n\t : dataFragment;\n\t holder.data = undefined;\n\t if (holder.metadata) {\n\t var metadata = metadataFragment\n\t ? bufferExports.Buffer.concat([holder.metadata, metadataFragment])\n\t : holder.metadata;\n\t holder.metadata = undefined;\n\t return {\n\t data: data,\n\t metadata: metadata,\n\t };\n\t }\n\t return {\n\t data: data,\n\t };\n\t}\n\tReassembler.reassemble = reassemble;\n\tfunction cancel(holder) {\n\t holder.hasFragments = false;\n\t holder.data = undefined;\n\t holder.metadata = undefined;\n\t}\n\tReassembler.cancel = cancel;\n\t\n\treturn Reassembler;\n}\n\nvar hasRequiredRequestChannelStream;\n\nfunction requireRequestChannelStream () {\n\tif (hasRequiredRequestChannelStream) return RequestChannelStream;\n\thasRequiredRequestChannelStream = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __createBinding = (RequestChannelStream && RequestChannelStream.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n\t}) : (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t o[k2] = m[k];\n\t}));\n\tvar __setModuleDefault = (RequestChannelStream && RequestChannelStream.__setModuleDefault) || (Object.create ? (function(o, v) {\n\t Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n\t}) : function(o, v) {\n\t o[\"default\"] = v;\n\t});\n\tvar __importStar = (RequestChannelStream && RequestChannelStream.__importStar) || function (mod) {\n\t if (mod && mod.__esModule) return mod;\n\t var result = {};\n\t if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\t __setModuleDefault(result, mod);\n\t return result;\n\t};\n\tvar __values = (RequestChannelStream && RequestChannelStream.__values) || function(o) {\n\t var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n\t if (m) return m.call(o);\n\t if (o && typeof o.length === \"number\") return {\n\t next: function () {\n\t if (o && i >= o.length) o = void 0;\n\t return { value: o && o[i++], done: !o };\n\t }\n\t };\n\t throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n\t};\n\tObject.defineProperty(RequestChannelStream, \"__esModule\", { value: true });\n\tRequestChannelStream.RequestChannelResponderStream = RequestChannelStream.RequestChannelRequesterStream = void 0;\n\tvar Errors_1 = requireErrors();\n\tvar Fragmenter_1 = requireFragmenter();\n\tvar Frames_1 = requireFrames();\n\tvar Reassembler = __importStar(requireReassembler());\n\tvar RequestChannelRequesterStream = /** @class */ (function () {\n\t function RequestChannelRequesterStream(payload, isComplete, receiver, fragmentSize, initialRequestN, leaseManager) {\n\t this.payload = payload;\n\t this.isComplete = isComplete;\n\t this.receiver = receiver;\n\t this.fragmentSize = fragmentSize;\n\t this.initialRequestN = initialRequestN;\n\t this.leaseManager = leaseManager;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_CHANNEL;\n\t // TODO: add payload size validation\n\t }\n\t RequestChannelRequesterStream.prototype.handleReady = function (streamId, stream) {\n\t var e_1, _a;\n\t if (this.outboundDone) {\n\t return false;\n\t }\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t stream.connect(this);\n\t var isCompleted = this.isComplete;\n\t if (isCompleted) {\n\t this.outboundDone = isCompleted;\n\t }\n\t if ((0, Fragmenter_1.isFragmentable)(this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_CHANNEL)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragmentWithRequestN)(streamId, this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_CHANNEL, this.initialRequestN, isCompleted)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_1_1) { e_1 = { error: e_1_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_1) throw e_1.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_CHANNEL,\n\t data: this.payload.data,\n\t metadata: this.payload.metadata,\n\t requestN: this.initialRequestN,\n\t flags: (this.payload.metadata !== undefined ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE) |\n\t (isCompleted ? Frames_1.Flags.COMPLETE : Frames_1.Flags.NONE),\n\t streamId: streamId,\n\t });\n\t }\n\t if (this.hasExtension) {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.EXT,\n\t streamId: streamId,\n\t extendedContent: this.extendedContent,\n\t extendedType: this.extendedType,\n\t flags: this.flags,\n\t });\n\t }\n\t return true;\n\t };\n\t RequestChannelRequesterStream.prototype.handleReject = function (error) {\n\t if (this.inboundDone) {\n\t return;\n\t }\n\t this.inboundDone = true;\n\t this.outboundDone = true;\n\t this.receiver.onError(error);\n\t };\n\t RequestChannelRequesterStream.prototype.handle = function (frame) {\n\t var errorMessage;\n\t var frameType = frame.type;\n\t switch (frameType) {\n\t case Frames_1.FrameTypes.PAYLOAD: {\n\t var hasComplete = Frames_1.Flags.hasComplete(frame.flags);\n\t var hasNext = Frames_1.Flags.hasNext(frame.flags);\n\t if (hasComplete || !Frames_1.Flags.hasFollows(frame.flags)) {\n\t if (hasComplete) {\n\t this.inboundDone = true;\n\t if (this.outboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t if (!hasNext) {\n\t // TODO: add validation no frame in reassembly\n\t this.receiver.onComplete();\n\t return;\n\t }\n\t }\n\t var payload = this.hasFragments\n\t ? Reassembler.reassemble(this, frame.data, frame.metadata)\n\t : {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t this.receiver.onNext(payload, hasComplete);\n\t return;\n\t }\n\t if (Reassembler.add(this, frame.data, frame.metadata)) {\n\t return;\n\t }\n\t errorMessage = \"Unexpected frame size\";\n\t break;\n\t }\n\t case Frames_1.FrameTypes.CANCEL: {\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t this.outboundDone = true;\n\t if (this.inboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t this.receiver.cancel();\n\t return;\n\t }\n\t case Frames_1.FrameTypes.REQUEST_N: {\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t if (this.hasFragments) {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"] during reassembly\");\n\t break;\n\t }\n\t this.receiver.request(frame.requestN);\n\t return;\n\t }\n\t case Frames_1.FrameTypes.ERROR: {\n\t var outboundDone = this.outboundDone;\n\t this.inboundDone = true;\n\t this.outboundDone = true;\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t if (!outboundDone) {\n\t this.receiver.cancel();\n\t }\n\t this.receiver.onError(new Errors_1.RSocketError(frame.code, frame.message));\n\t return;\n\t }\n\t case Frames_1.FrameTypes.EXT:\n\t this.receiver.onExtension(frame.extendedType, frame.extendedContent, Frames_1.Flags.hasIgnore(frame.flags));\n\t return;\n\t default: {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"]\");\n\t }\n\t }\n\t this.close(new Errors_1.RSocketError(Errors_1.ErrorCodes.CANCELED, errorMessage));\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.CANCEL,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t this.stream.disconnect(this);\n\t };\n\t RequestChannelRequesterStream.prototype.request = function (n) {\n\t if (this.inboundDone) {\n\t return;\n\t }\n\t if (!this.streamId) {\n\t this.initialRequestN += n;\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_N,\n\t flags: Frames_1.Flags.NONE,\n\t requestN: n,\n\t streamId: this.streamId,\n\t });\n\t };\n\t RequestChannelRequesterStream.prototype.cancel = function () {\n\t var _a;\n\t var inboundDone = this.inboundDone;\n\t var outboundDone = this.outboundDone;\n\t if (inboundDone && outboundDone) {\n\t return;\n\t }\n\t this.inboundDone = true;\n\t this.outboundDone = true;\n\t if (!outboundDone) {\n\t this.receiver.cancel();\n\t }\n\t if (!this.streamId) {\n\t (_a = this.leaseManager) === null || _a === void 0 ? void 0 : _a.cancelRequest(this);\n\t return;\n\t }\n\t this.stream.send({\n\t type: inboundDone ? Frames_1.FrameTypes.ERROR : Frames_1.FrameTypes.CANCEL,\n\t flags: Frames_1.Flags.NONE,\n\t streamId: this.streamId,\n\t code: Errors_1.ErrorCodes.CANCELED,\n\t message: \"Cancelled\",\n\t });\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t };\n\t RequestChannelRequesterStream.prototype.onNext = function (payload, isComplete) {\n\t var e_2, _a;\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t if (isComplete) {\n\t this.outboundDone = true;\n\t if (this.inboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t }\n\t if ((0, Fragmenter_1.isFragmentable)(payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragment)(this.streamId, payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD, isComplete)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_2_1) { e_2 = { error: e_2_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_2) throw e_2.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.NEXT |\n\t (payload.metadata ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE) |\n\t (isComplete ? Frames_1.Flags.COMPLETE : Frames_1.Flags.NONE),\n\t data: payload.data,\n\t metadata: payload.metadata,\n\t });\n\t }\n\t };\n\t RequestChannelRequesterStream.prototype.onComplete = function () {\n\t if (!this.streamId) {\n\t this.isComplete = true;\n\t return;\n\t }\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t this.outboundDone = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.COMPLETE,\n\t data: null,\n\t metadata: null,\n\t });\n\t if (this.inboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t };\n\t RequestChannelRequesterStream.prototype.onError = function (error) {\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t var inboundDone = this.inboundDone;\n\t this.outboundDone = true;\n\t this.inboundDone = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.NONE,\n\t code: error instanceof Errors_1.RSocketError\n\t ? error.code\n\t : Errors_1.ErrorCodes.APPLICATION_ERROR,\n\t message: error.message,\n\t });\n\t this.stream.disconnect(this);\n\t if (!inboundDone) {\n\t this.receiver.onError(error);\n\t }\n\t };\n\t RequestChannelRequesterStream.prototype.onExtension = function (extendedType, content, canBeIgnored) {\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t if (!this.streamId) {\n\t this.hasExtension = true;\n\t this.extendedType = extendedType;\n\t this.extendedContent = content;\n\t this.flags = canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE;\n\t return;\n\t }\n\t this.stream.send({\n\t streamId: this.streamId,\n\t type: Frames_1.FrameTypes.EXT,\n\t extendedType: extendedType,\n\t extendedContent: content,\n\t flags: canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE,\n\t });\n\t };\n\t RequestChannelRequesterStream.prototype.close = function (error) {\n\t if (this.inboundDone && this.outboundDone) {\n\t return;\n\t }\n\t var inboundDone = this.inboundDone;\n\t var outboundDone = this.outboundDone;\n\t this.inboundDone = true;\n\t this.outboundDone = true;\n\t Reassembler.cancel(this);\n\t if (!outboundDone) {\n\t this.receiver.cancel();\n\t }\n\t if (!inboundDone) {\n\t if (error) {\n\t this.receiver.onError(error);\n\t }\n\t else {\n\t this.receiver.onComplete();\n\t }\n\t }\n\t };\n\t return RequestChannelRequesterStream;\n\t}());\n\tRequestChannelStream.RequestChannelRequesterStream = RequestChannelRequesterStream;\n\tvar RequestChannelResponderStream = /** @class */ (function () {\n\t function RequestChannelResponderStream(streamId, stream, fragmentSize, handler, frame) {\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t this.fragmentSize = fragmentSize;\n\t this.handler = handler;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_CHANNEL;\n\t stream.connect(this);\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t Reassembler.add(this, frame.data, frame.metadata);\n\t this.initialRequestN = frame.requestN;\n\t this.isComplete = Frames_1.Flags.hasComplete(frame.flags);\n\t return;\n\t }\n\t var payload = {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t var hasComplete = Frames_1.Flags.hasComplete(frame.flags);\n\t this.inboundDone = hasComplete;\n\t try {\n\t this.receiver = handler(payload, frame.requestN, hasComplete, this);\n\t if (this.outboundDone && this.defferedError) {\n\t this.receiver.onError(this.defferedError);\n\t }\n\t }\n\t catch (error) {\n\t if (this.outboundDone && !this.inboundDone) {\n\t this.cancel();\n\t }\n\t else {\n\t this.inboundDone = true;\n\t }\n\t this.onError(error);\n\t }\n\t }\n\t RequestChannelResponderStream.prototype.handle = function (frame) {\n\t var errorMessage;\n\t var frameType = frame.type;\n\t switch (frameType) {\n\t case Frames_1.FrameTypes.PAYLOAD: {\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t if (Reassembler.add(this, frame.data, frame.metadata)) {\n\t return;\n\t }\n\t errorMessage = \"Unexpected frame size\";\n\t break;\n\t }\n\t var payload = this.hasFragments\n\t ? Reassembler.reassemble(this, frame.data, frame.metadata)\n\t : {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t var hasComplete = Frames_1.Flags.hasComplete(frame.flags);\n\t if (!this.receiver) {\n\t var inboundDone = this.isComplete || hasComplete;\n\t if (inboundDone) {\n\t this.inboundDone = true;\n\t if (this.outboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t }\n\t try {\n\t this.receiver = this.handler(payload, this.initialRequestN, inboundDone, this);\n\t if (this.outboundDone && this.defferedError) {\n\t }\n\t }\n\t catch (error) {\n\t if (this.outboundDone && !this.inboundDone) {\n\t this.cancel();\n\t }\n\t else {\n\t this.inboundDone = true;\n\t }\n\t this.onError(error);\n\t }\n\t }\n\t else {\n\t if (hasComplete) {\n\t this.inboundDone = true;\n\t if (this.outboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t if (!Frames_1.Flags.hasNext(frame.flags)) {\n\t this.receiver.onComplete();\n\t return;\n\t }\n\t }\n\t this.receiver.onNext(payload, hasComplete);\n\t }\n\t return;\n\t }\n\t case Frames_1.FrameTypes.REQUEST_N: {\n\t if (!this.receiver || this.hasFragments) {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"] during reassembly\");\n\t break;\n\t }\n\t this.receiver.request(frame.requestN);\n\t return;\n\t }\n\t case Frames_1.FrameTypes.ERROR:\n\t case Frames_1.FrameTypes.CANCEL: {\n\t var inboundDone = this.inboundDone;\n\t var outboundDone = this.outboundDone;\n\t this.inboundDone = true;\n\t this.outboundDone = true;\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t if (!this.receiver) {\n\t return;\n\t }\n\t if (!outboundDone) {\n\t this.receiver.cancel();\n\t }\n\t if (!inboundDone) {\n\t var error = frameType === Frames_1.FrameTypes.CANCEL\n\t ? new Errors_1.RSocketError(Errors_1.ErrorCodes.CANCELED, \"Cancelled\")\n\t : new Errors_1.RSocketError(frame.code, frame.message);\n\t this.receiver.onError(error);\n\t }\n\t return;\n\t }\n\t case Frames_1.FrameTypes.EXT: {\n\t if (!this.receiver || this.hasFragments) {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"] during reassembly\");\n\t break;\n\t }\n\t this.receiver.onExtension(frame.extendedType, frame.extendedContent, Frames_1.Flags.hasIgnore(frame.flags));\n\t return;\n\t }\n\t default: {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"]\");\n\t // TODO: throws if strict\n\t }\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t flags: Frames_1.Flags.NONE,\n\t code: Errors_1.ErrorCodes.CANCELED,\n\t message: errorMessage,\n\t streamId: this.streamId,\n\t });\n\t this.stream.disconnect(this);\n\t this.close(new Errors_1.RSocketError(Errors_1.ErrorCodes.CANCELED, errorMessage));\n\t };\n\t RequestChannelResponderStream.prototype.onError = function (error) {\n\t if (this.outboundDone) {\n\t console.warn(\"Trying to error for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t var inboundDone = this.inboundDone;\n\t this.outboundDone = true;\n\t this.inboundDone = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t flags: Frames_1.Flags.NONE,\n\t code: error instanceof Errors_1.RSocketError\n\t ? error.code\n\t : Errors_1.ErrorCodes.APPLICATION_ERROR,\n\t message: error.message,\n\t streamId: this.streamId,\n\t });\n\t this.stream.disconnect(this);\n\t if (!inboundDone) {\n\t if (this.receiver) {\n\t this.receiver.onError(error);\n\t }\n\t else {\n\t this.defferedError = error;\n\t }\n\t }\n\t };\n\t RequestChannelResponderStream.prototype.onNext = function (payload, isCompletion) {\n\t var e_3, _a;\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t if (isCompletion) {\n\t this.outboundDone = true;\n\t }\n\t // TODO: add payload size validation\n\t if ((0, Fragmenter_1.isFragmentable)(payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragment)(this.streamId, payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD, isCompletion)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_3_1) { e_3 = { error: e_3_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_3) throw e_3.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.NEXT |\n\t (isCompletion ? Frames_1.Flags.COMPLETE : Frames_1.Flags.NONE) |\n\t (payload.metadata ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE),\n\t data: payload.data,\n\t metadata: payload.metadata,\n\t streamId: this.streamId,\n\t });\n\t }\n\t if (isCompletion && this.inboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t };\n\t RequestChannelResponderStream.prototype.onComplete = function () {\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t this.outboundDone = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.COMPLETE,\n\t streamId: this.streamId,\n\t data: null,\n\t metadata: null,\n\t });\n\t if (this.inboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t };\n\t RequestChannelResponderStream.prototype.onExtension = function (extendedType, content, canBeIgnored) {\n\t if (this.outboundDone && this.inboundDone) {\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.EXT,\n\t streamId: this.streamId,\n\t flags: canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE,\n\t extendedType: extendedType,\n\t extendedContent: content,\n\t });\n\t };\n\t RequestChannelResponderStream.prototype.request = function (n) {\n\t if (this.inboundDone) {\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_N,\n\t flags: Frames_1.Flags.NONE,\n\t streamId: this.streamId,\n\t requestN: n,\n\t });\n\t };\n\t RequestChannelResponderStream.prototype.cancel = function () {\n\t if (this.inboundDone) {\n\t return;\n\t }\n\t this.inboundDone = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.CANCEL,\n\t flags: Frames_1.Flags.NONE,\n\t streamId: this.streamId,\n\t });\n\t if (this.outboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t };\n\t RequestChannelResponderStream.prototype.close = function (error) {\n\t if (this.inboundDone && this.outboundDone) {\n\t console.warn(\"Trying to close for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t var inboundDone = this.inboundDone;\n\t var outboundDone = this.outboundDone;\n\t this.inboundDone = true;\n\t this.outboundDone = true;\n\t Reassembler.cancel(this);\n\t var receiver = this.receiver;\n\t if (!receiver) {\n\t return;\n\t }\n\t if (!outboundDone) {\n\t receiver.cancel();\n\t }\n\t if (!inboundDone) {\n\t if (error) {\n\t receiver.onError(error);\n\t }\n\t else {\n\t receiver.onComplete();\n\t }\n\t }\n\t };\n\t return RequestChannelResponderStream;\n\t}());\n\tRequestChannelStream.RequestChannelResponderStream = RequestChannelResponderStream;\n\t\n\treturn RequestChannelStream;\n}\n\nvar RequestFnFStream = {};\n\nvar hasRequiredRequestFnFStream;\n\nfunction requireRequestFnFStream () {\n\tif (hasRequiredRequestFnFStream) return RequestFnFStream;\n\thasRequiredRequestFnFStream = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __createBinding = (RequestFnFStream && RequestFnFStream.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n\t}) : (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t o[k2] = m[k];\n\t}));\n\tvar __setModuleDefault = (RequestFnFStream && RequestFnFStream.__setModuleDefault) || (Object.create ? (function(o, v) {\n\t Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n\t}) : function(o, v) {\n\t o[\"default\"] = v;\n\t});\n\tvar __importStar = (RequestFnFStream && RequestFnFStream.__importStar) || function (mod) {\n\t if (mod && mod.__esModule) return mod;\n\t var result = {};\n\t if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\t __setModuleDefault(result, mod);\n\t return result;\n\t};\n\tvar __values = (RequestFnFStream && RequestFnFStream.__values) || function(o) {\n\t var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n\t if (m) return m.call(o);\n\t if (o && typeof o.length === \"number\") return {\n\t next: function () {\n\t if (o && i >= o.length) o = void 0;\n\t return { value: o && o[i++], done: !o };\n\t }\n\t };\n\t throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n\t};\n\tObject.defineProperty(RequestFnFStream, \"__esModule\", { value: true });\n\tRequestFnFStream.RequestFnfResponderStream = RequestFnFStream.RequestFnFRequesterStream = void 0;\n\tvar Errors_1 = requireErrors();\n\tvar Fragmenter_1 = requireFragmenter();\n\tvar Frames_1 = requireFrames();\n\tvar Reassembler = __importStar(requireReassembler());\n\tvar RequestFnFRequesterStream = /** @class */ (function () {\n\t function RequestFnFRequesterStream(payload, receiver, fragmentSize, leaseManager) {\n\t this.payload = payload;\n\t this.receiver = receiver;\n\t this.fragmentSize = fragmentSize;\n\t this.leaseManager = leaseManager;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_FNF;\n\t }\n\t RequestFnFRequesterStream.prototype.handleReady = function (streamId, stream) {\n\t var e_1, _a;\n\t if (this.done) {\n\t return false;\n\t }\n\t this.streamId = streamId;\n\t if ((0, Fragmenter_1.isFragmentable)(this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_FNF)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragment)(streamId, this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_FNF)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t stream.send(frame);\n\t }\n\t }\n\t catch (e_1_1) { e_1 = { error: e_1_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_1) throw e_1.error; }\n\t }\n\t }\n\t else {\n\t stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_FNF,\n\t data: this.payload.data,\n\t metadata: this.payload.metadata,\n\t flags: this.payload.metadata ? Frames_1.Flags.METADATA : 0,\n\t streamId: streamId,\n\t });\n\t }\n\t this.done = true;\n\t this.receiver.onComplete();\n\t return true;\n\t };\n\t RequestFnFRequesterStream.prototype.handleReject = function (error) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t this.receiver.onError(error);\n\t };\n\t RequestFnFRequesterStream.prototype.cancel = function () {\n\t var _a;\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t (_a = this.leaseManager) === null || _a === void 0 ? void 0 : _a.cancelRequest(this);\n\t };\n\t RequestFnFRequesterStream.prototype.handle = function (frame) {\n\t if (frame.type == Frames_1.FrameTypes.ERROR) {\n\t this.close(new Errors_1.RSocketError(frame.code, frame.message));\n\t return;\n\t }\n\t this.close(new Errors_1.RSocketError(Errors_1.ErrorCodes.CANCELED, \"Received invalid frame\"));\n\t };\n\t RequestFnFRequesterStream.prototype.close = function (error) {\n\t if (this.done) {\n\t console.warn(\"Trying to close for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t if (error) {\n\t this.receiver.onError(error);\n\t }\n\t else {\n\t this.receiver.onComplete();\n\t }\n\t };\n\t return RequestFnFRequesterStream;\n\t}());\n\tRequestFnFStream.RequestFnFRequesterStream = RequestFnFRequesterStream;\n\tvar RequestFnfResponderStream = /** @class */ (function () {\n\t function RequestFnfResponderStream(streamId, stream, handler, frame) {\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t this.handler = handler;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_FNF;\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t Reassembler.add(this, frame.data, frame.metadata);\n\t stream.connect(this);\n\t return;\n\t }\n\t var payload = {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t try {\n\t this.cancellable = handler(payload, this);\n\t }\n\t catch (e) {\n\t // do nothing\n\t }\n\t }\n\t RequestFnfResponderStream.prototype.handle = function (frame) {\n\t var errorMessage;\n\t if (frame.type == Frames_1.FrameTypes.PAYLOAD) {\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t if (Reassembler.add(this, frame.data, frame.metadata)) {\n\t return;\n\t }\n\t errorMessage = \"Unexpected fragment size\";\n\t }\n\t else {\n\t this.stream.disconnect(this);\n\t var payload = Reassembler.reassemble(this, frame.data, frame.metadata);\n\t try {\n\t this.cancellable = this.handler(payload, this);\n\t }\n\t catch (e) {\n\t // do nothing\n\t }\n\t return;\n\t }\n\t }\n\t else {\n\t errorMessage = \"Unexpected frame type [\".concat(frame.type, \"]\");\n\t }\n\t this.done = true;\n\t if (frame.type != Frames_1.FrameTypes.CANCEL && frame.type != Frames_1.FrameTypes.ERROR) {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.NONE,\n\t code: Errors_1.ErrorCodes.CANCELED,\n\t message: errorMessage,\n\t });\n\t }\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t // TODO: throws if strict\n\t };\n\t RequestFnfResponderStream.prototype.close = function (error) {\n\t var _a;\n\t if (this.done) {\n\t console.warn(\"Trying to close for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t this.done = true;\n\t Reassembler.cancel(this);\n\t (_a = this.cancellable) === null || _a === void 0 ? void 0 : _a.cancel();\n\t };\n\t RequestFnfResponderStream.prototype.onError = function (error) { };\n\t RequestFnfResponderStream.prototype.onComplete = function () { };\n\t return RequestFnfResponderStream;\n\t}());\n\tRequestFnFStream.RequestFnfResponderStream = RequestFnfResponderStream;\n\t/*\n\texport function request(\n\t payload: Payload,\n\t responderStream: UnidirectionalStream\n\t): Handler<Cancellable> {\n\t return {\n\t create: (r) => {\n\t const response = new RequestFnFRequesterHandler(\n\t payload,\n\t responderStream,\n\t r\n\t );\n\n\t r.add(response);\n\n\t return response;\n\t },\n\t };\n\t}\n\n\texport function response(\n\t handler: (payload: Payload, responderStream: UnidirectionalStream,) => void\n\t): Handler<void> {\n\t return {\n\t create: (r) => new RequestFnfResponderHandler(),\n\t };\n\t} */\n\t\n\treturn RequestFnFStream;\n}\n\nvar RequestResponseStream = {};\n\nvar hasRequiredRequestResponseStream;\n\nfunction requireRequestResponseStream () {\n\tif (hasRequiredRequestResponseStream) return RequestResponseStream;\n\thasRequiredRequestResponseStream = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __createBinding = (RequestResponseStream && RequestResponseStream.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n\t}) : (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t o[k2] = m[k];\n\t}));\n\tvar __setModuleDefault = (RequestResponseStream && RequestResponseStream.__setModuleDefault) || (Object.create ? (function(o, v) {\n\t Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n\t}) : function(o, v) {\n\t o[\"default\"] = v;\n\t});\n\tvar __importStar = (RequestResponseStream && RequestResponseStream.__importStar) || function (mod) {\n\t if (mod && mod.__esModule) return mod;\n\t var result = {};\n\t if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\t __setModuleDefault(result, mod);\n\t return result;\n\t};\n\tvar __values = (RequestResponseStream && RequestResponseStream.__values) || function(o) {\n\t var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n\t if (m) return m.call(o);\n\t if (o && typeof o.length === \"number\") return {\n\t next: function () {\n\t if (o && i >= o.length) o = void 0;\n\t return { value: o && o[i++], done: !o };\n\t }\n\t };\n\t throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n\t};\n\tObject.defineProperty(RequestResponseStream, \"__esModule\", { value: true });\n\tRequestResponseStream.RequestResponseResponderStream = RequestResponseStream.RequestResponseRequesterStream = void 0;\n\tvar Errors_1 = requireErrors();\n\tvar Fragmenter_1 = requireFragmenter();\n\tvar Frames_1 = requireFrames();\n\tvar Reassembler = __importStar(requireReassembler());\n\tvar RequestResponseRequesterStream = /** @class */ (function () {\n\t function RequestResponseRequesterStream(payload, receiver, fragmentSize, leaseManager) {\n\t this.payload = payload;\n\t this.receiver = receiver;\n\t this.fragmentSize = fragmentSize;\n\t this.leaseManager = leaseManager;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_RESPONSE;\n\t }\n\t RequestResponseRequesterStream.prototype.handleReady = function (streamId, stream) {\n\t var e_1, _a;\n\t if (this.done) {\n\t return false;\n\t }\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t stream.connect(this);\n\t if ((0, Fragmenter_1.isFragmentable)(this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_RESPONSE)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragment)(streamId, this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_RESPONSE)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_1_1) { e_1 = { error: e_1_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_1) throw e_1.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_RESPONSE,\n\t data: this.payload.data,\n\t metadata: this.payload.metadata,\n\t flags: this.payload.metadata ? Frames_1.Flags.METADATA : 0,\n\t streamId: streamId,\n\t });\n\t }\n\t if (this.hasExtension) {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.EXT,\n\t streamId: streamId,\n\t extendedContent: this.extendedContent,\n\t extendedType: this.extendedType,\n\t flags: this.flags,\n\t });\n\t }\n\t return true;\n\t };\n\t RequestResponseRequesterStream.prototype.handleReject = function (error) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t this.receiver.onError(error);\n\t };\n\t RequestResponseRequesterStream.prototype.handle = function (frame) {\n\t var errorMessage;\n\t var frameType = frame.type;\n\t switch (frameType) {\n\t case Frames_1.FrameTypes.PAYLOAD: {\n\t var hasComplete = Frames_1.Flags.hasComplete(frame.flags);\n\t var hasPayload = Frames_1.Flags.hasNext(frame.flags);\n\t if (hasComplete || !Frames_1.Flags.hasFollows(frame.flags)) {\n\t this.done = true;\n\t this.stream.disconnect(this);\n\t if (!hasPayload) {\n\t // TODO: add validation no frame in reassembly\n\t this.receiver.onComplete();\n\t return;\n\t }\n\t var payload = this.hasFragments\n\t ? Reassembler.reassemble(this, frame.data, frame.metadata)\n\t : {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t this.receiver.onNext(payload, true);\n\t return;\n\t }\n\t if (!Reassembler.add(this, frame.data, frame.metadata)) {\n\t errorMessage = \"Unexpected fragment size\";\n\t break;\n\t }\n\t return;\n\t }\n\t case Frames_1.FrameTypes.ERROR: {\n\t this.done = true;\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t this.receiver.onError(new Errors_1.RSocketError(frame.code, frame.message));\n\t return;\n\t }\n\t case Frames_1.FrameTypes.EXT: {\n\t if (this.hasFragments) {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"] during reassembly\");\n\t break;\n\t }\n\t this.receiver.onExtension(frame.extendedType, frame.extendedContent, Frames_1.Flags.hasIgnore(frame.flags));\n\t return;\n\t }\n\t default: {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"]\");\n\t }\n\t }\n\t this.close(new Errors_1.RSocketError(Errors_1.ErrorCodes.CANCELED, errorMessage));\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.CANCEL,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t this.stream.disconnect(this);\n\t // TODO: throw an exception if strict frame handling mode\n\t };\n\t RequestResponseRequesterStream.prototype.cancel = function () {\n\t var _a;\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t if (!this.streamId) {\n\t (_a = this.leaseManager) === null || _a === void 0 ? void 0 : _a.cancelRequest(this);\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.CANCEL,\n\t flags: Frames_1.Flags.NONE,\n\t streamId: this.streamId,\n\t });\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t };\n\t RequestResponseRequesterStream.prototype.onExtension = function (extendedType, content, canBeIgnored) {\n\t if (this.done) {\n\t return;\n\t }\n\t if (!this.streamId) {\n\t this.hasExtension = true;\n\t this.extendedType = extendedType;\n\t this.extendedContent = content;\n\t this.flags = canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE;\n\t return;\n\t }\n\t this.stream.send({\n\t streamId: this.streamId,\n\t type: Frames_1.FrameTypes.EXT,\n\t extendedType: extendedType,\n\t extendedContent: content,\n\t flags: canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE,\n\t });\n\t };\n\t RequestResponseRequesterStream.prototype.close = function (error) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t Reassembler.cancel(this);\n\t if (error) {\n\t this.receiver.onError(error);\n\t }\n\t else {\n\t this.receiver.onComplete();\n\t }\n\t };\n\t return RequestResponseRequesterStream;\n\t}());\n\tRequestResponseStream.RequestResponseRequesterStream = RequestResponseRequesterStream;\n\tvar RequestResponseResponderStream = /** @class */ (function () {\n\t function RequestResponseResponderStream(streamId, stream, fragmentSize, handler, frame) {\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t this.fragmentSize = fragmentSize;\n\t this.handler = handler;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_RESPONSE;\n\t stream.connect(this);\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t Reassembler.add(this, frame.data, frame.metadata);\n\t return;\n\t }\n\t var payload = {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t try {\n\t this.receiver = handler(payload, this);\n\t }\n\t catch (error) {\n\t this.onError(error);\n\t }\n\t }\n\t RequestResponseResponderStream.prototype.handle = function (frame) {\n\t var _a;\n\t var errorMessage;\n\t if (!this.receiver || this.hasFragments) {\n\t if (frame.type === Frames_1.FrameTypes.PAYLOAD) {\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t if (Reassembler.add(this, frame.data, frame.metadata)) {\n\t return;\n\t }\n\t errorMessage = \"Unexpected fragment size\";\n\t }\n\t else {\n\t var payload = Reassembler.reassemble(this, frame.data, frame.metadata);\n\t try {\n\t this.receiver = this.handler(payload, this);\n\t }\n\t catch (error) {\n\t this.onError(error);\n\t }\n\t return;\n\t }\n\t }\n\t else {\n\t errorMessage = \"Unexpected frame type [\".concat(frame.type, \"] during reassembly\");\n\t }\n\t }\n\t else if (frame.type === Frames_1.FrameTypes.EXT) {\n\t this.receiver.onExtension(frame.extendedType, frame.extendedContent, Frames_1.Flags.hasIgnore(frame.flags));\n\t return;\n\t }\n\t else {\n\t errorMessage = \"Unexpected frame type [\".concat(frame.type, \"]\");\n\t }\n\t this.done = true;\n\t (_a = this.receiver) === null || _a === void 0 ? void 0 : _a.cancel();\n\t if (frame.type !== Frames_1.FrameTypes.CANCEL && frame.type !== Frames_1.FrameTypes.ERROR) {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t flags: Frames_1.Flags.NONE,\n\t code: Errors_1.ErrorCodes.CANCELED,\n\t message: errorMessage,\n\t streamId: this.streamId,\n\t });\n\t }\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t // TODO: throws if strict\n\t };\n\t RequestResponseResponderStream.prototype.onError = function (error) {\n\t if (this.done) {\n\t console.warn(\"Trying to error for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t this.done = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t flags: Frames_1.Flags.NONE,\n\t code: error instanceof Errors_1.RSocketError\n\t ? error.code\n\t : Errors_1.ErrorCodes.APPLICATION_ERROR,\n\t message: error.message,\n\t streamId: this.streamId,\n\t });\n\t this.stream.disconnect(this);\n\t };\n\t RequestResponseResponderStream.prototype.onNext = function (payload, isCompletion) {\n\t var e_2, _a;\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t // TODO: add payload size validation\n\t if ((0, Fragmenter_1.isFragmentable)(payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragment)(this.streamId, payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD, true)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_2_1) { e_2 = { error: e_2_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_2) throw e_2.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.NEXT | Frames_1.Flags.COMPLETE | (payload.metadata ? Frames_1.Flags.METADATA : 0),\n\t data: payload.data,\n\t metadata: payload.metadata,\n\t streamId: this.streamId,\n\t });\n\t }\n\t this.stream.disconnect(this);\n\t };\n\t RequestResponseResponderStream.prototype.onComplete = function () {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.COMPLETE,\n\t streamId: this.streamId,\n\t data: null,\n\t metadata: null,\n\t });\n\t this.stream.disconnect(this);\n\t };\n\t RequestResponseResponderStream.prototype.onExtension = function (extendedType, content, canBeIgnored) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.EXT,\n\t streamId: this.streamId,\n\t flags: canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE,\n\t extendedType: extendedType,\n\t extendedContent: content,\n\t });\n\t };\n\t RequestResponseResponderStream.prototype.close = function (error) {\n\t var _a;\n\t if (this.done) {\n\t console.warn(\"Trying to close for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t Reassembler.cancel(this);\n\t (_a = this.receiver) === null || _a === void 0 ? void 0 : _a.cancel();\n\t };\n\t return RequestResponseResponderStream;\n\t}());\n\tRequestResponseStream.RequestResponseResponderStream = RequestResponseResponderStream;\n\t\n\treturn RequestResponseStream;\n}\n\nvar RequestStreamStream = {};\n\nvar hasRequiredRequestStreamStream;\n\nfunction requireRequestStreamStream () {\n\tif (hasRequiredRequestStreamStream) return RequestStreamStream;\n\thasRequiredRequestStreamStream = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __createBinding = (RequestStreamStream && RequestStreamStream.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n\t}) : (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t o[k2] = m[k];\n\t}));\n\tvar __setModuleDefault = (RequestStreamStream && RequestStreamStream.__setModuleDefault) || (Object.create ? (function(o, v) {\n\t Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n\t}) : function(o, v) {\n\t o[\"default\"] = v;\n\t});\n\tvar __importStar = (RequestStreamStream && RequestStreamStream.__importStar) || function (mod) {\n\t if (mod && mod.__esModule) return mod;\n\t var result = {};\n\t if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\t __setModuleDefault(result, mod);\n\t return result;\n\t};\n\tvar __values = (RequestStreamStream && RequestStreamStream.__values) || function(o) {\n\t var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n\t if (m) return m.call(o);\n\t if (o && typeof o.length === \"number\") return {\n\t next: function () {\n\t if (o && i >= o.length) o = void 0;\n\t return { value: o && o[i++], done: !o };\n\t }\n\t };\n\t throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n\t};\n\tObject.defineProperty(RequestStreamStream, \"__esModule\", { value: true });\n\tRequestStreamStream.RequestStreamResponderStream = RequestStreamStream.RequestStreamRequesterStream = void 0;\n\tvar Errors_1 = requireErrors();\n\tvar Fragmenter_1 = requireFragmenter();\n\tvar Frames_1 = requireFrames();\n\tvar Reassembler = __importStar(requireReassembler());\n\tvar RequestStreamRequesterStream = /** @class */ (function () {\n\t function RequestStreamRequesterStream(payload, receiver, fragmentSize, initialRequestN, leaseManager) {\n\t this.payload = payload;\n\t this.receiver = receiver;\n\t this.fragmentSize = fragmentSize;\n\t this.initialRequestN = initialRequestN;\n\t this.leaseManager = leaseManager;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_STREAM;\n\t // TODO: add payload size validation\n\t }\n\t RequestStreamRequesterStream.prototype.handleReady = function (streamId, stream) {\n\t var e_1, _a;\n\t if (this.done) {\n\t return false;\n\t }\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t stream.connect(this);\n\t if ((0, Fragmenter_1.isFragmentable)(this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_STREAM)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragmentWithRequestN)(streamId, this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_STREAM, this.initialRequestN)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_1_1) { e_1 = { error: e_1_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_1) throw e_1.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_STREAM,\n\t data: this.payload.data,\n\t metadata: this.payload.metadata,\n\t requestN: this.initialRequestN,\n\t flags: this.payload.metadata !== undefined ? Frames_1.Flags.METADATA : 0,\n\t streamId: streamId,\n\t });\n\t }\n\t if (this.hasExtension) {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.EXT,\n\t streamId: streamId,\n\t extendedContent: this.extendedContent,\n\t extendedType: this.extendedType,\n\t flags: this.flags,\n\t });\n\t }\n\t return true;\n\t };\n\t RequestStreamRequesterStream.prototype.handleReject = function (error) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t this.receiver.onError(error);\n\t };\n\t RequestStreamRequesterStream.prototype.handle = function (frame) {\n\t var errorMessage;\n\t var frameType = frame.type;\n\t switch (frameType) {\n\t case Frames_1.FrameTypes.PAYLOAD: {\n\t var hasComplete = Frames_1.Flags.hasComplete(frame.flags);\n\t var hasNext = Frames_1.Flags.hasNext(frame.flags);\n\t if (hasComplete || !Frames_1.Flags.hasFollows(frame.flags)) {\n\t if (hasComplete) {\n\t this.done = true;\n\t this.stream.disconnect(this);\n\t if (!hasNext) {\n\t // TODO: add validation no frame in reassembly\n\t this.receiver.onComplete();\n\t return;\n\t }\n\t }\n\t var payload = this.hasFragments\n\t ? Reassembler.reassemble(this, frame.data, frame.metadata)\n\t : {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t this.receiver.onNext(payload, hasComplete);\n\t return;\n\t }\n\t if (!Reassembler.add(this, frame.data, frame.metadata)) {\n\t errorMessage = \"Unexpected fragment size\";\n\t break;\n\t }\n\t return;\n\t }\n\t case Frames_1.FrameTypes.ERROR: {\n\t this.done = true;\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t this.receiver.onError(new Errors_1.RSocketError(frame.code, frame.message));\n\t return;\n\t }\n\t case Frames_1.FrameTypes.EXT: {\n\t if (this.hasFragments) {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"] during reassembly\");\n\t break;\n\t }\n\t this.receiver.onExtension(frame.extendedType, frame.extendedContent, Frames_1.Flags.hasIgnore(frame.flags));\n\t return;\n\t }\n\t default: {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"]\");\n\t }\n\t }\n\t this.close(new Errors_1.RSocketError(Errors_1.ErrorCodes.CANCELED, errorMessage));\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.CANCEL,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t this.stream.disconnect(this);\n\t // TODO: throw an exception if strict frame handling mode\n\t };\n\t RequestStreamRequesterStream.prototype.request = function (n) {\n\t if (this.done) {\n\t return;\n\t }\n\t if (!this.streamId) {\n\t this.initialRequestN += n;\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_N,\n\t flags: Frames_1.Flags.NONE,\n\t requestN: n,\n\t streamId: this.streamId,\n\t });\n\t };\n\t RequestStreamRequesterStream.prototype.cancel = function () {\n\t var _a;\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t if (!this.streamId) {\n\t (_a = this.leaseManager) === null || _a === void 0 ? void 0 : _a.cancelRequest(this);\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.CANCEL,\n\t flags: Frames_1.Flags.NONE,\n\t streamId: this.streamId,\n\t });\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t };\n\t RequestStreamRequesterStream.prototype.onExtension = function (extendedType, content, canBeIgnored) {\n\t if (this.done) {\n\t return;\n\t }\n\t if (!this.streamId) {\n\t this.hasExtension = true;\n\t this.extendedType = extendedType;\n\t this.extendedContent = content;\n\t this.flags = canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE;\n\t return;\n\t }\n\t this.stream.send({\n\t streamId: this.streamId,\n\t type: Frames_1.FrameTypes.EXT,\n\t extendedType: extendedType,\n\t extendedContent: content,\n\t flags: canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE,\n\t });\n\t };\n\t RequestStreamRequesterStream.prototype.close = function (error) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t Reassembler.cancel(this);\n\t if (error) {\n\t this.receiver.onError(error);\n\t }\n\t else {\n\t this.receiver.onComplete();\n\t }\n\t };\n\t return RequestStreamRequesterStream;\n\t}());\n\tRequestStreamStream.RequestStreamRequesterStream = RequestStreamRequesterStream;\n\tvar RequestStreamResponderStream = /** @class */ (function () {\n\t function RequestStreamResponderStream(streamId, stream, fragmentSize, handler, frame) {\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t this.fragmentSize = fragmentSize;\n\t this.handler = handler;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_STREAM;\n\t stream.connect(this);\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t this.initialRequestN = frame.requestN;\n\t Reassembler.add(this, frame.data, frame.metadata);\n\t return;\n\t }\n\t var payload = {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t try {\n\t this.receiver = handler(payload, frame.requestN, this);\n\t }\n\t catch (error) {\n\t this.onError(error);\n\t }\n\t }\n\t RequestStreamResponderStream.prototype.handle = function (frame) {\n\t var _a;\n\t var errorMessage;\n\t if (!this.receiver || this.hasFragments) {\n\t if (frame.type === Frames_1.FrameTypes.PAYLOAD) {\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t if (Reassembler.add(this, frame.data, frame.metadata)) {\n\t return;\n\t }\n\t errorMessage = \"Unexpected frame size\";\n\t }\n\t else {\n\t var payload = Reassembler.reassemble(this, frame.data, frame.metadata);\n\t try {\n\t this.receiver = this.handler(payload, this.initialRequestN, this);\n\t }\n\t catch (error) {\n\t this.onError(error);\n\t }\n\t return;\n\t }\n\t }\n\t else {\n\t errorMessage = \"Unexpected frame type [\".concat(frame.type, \"] during reassembly\");\n\t }\n\t }\n\t else if (frame.type === Frames_1.FrameTypes.REQUEST_N) {\n\t this.receiver.request(frame.requestN);\n\t return;\n\t }\n\t else if (frame.type === Frames_1.FrameTypes.EXT) {\n\t this.receiver.onExtension(frame.extendedType, frame.extendedContent, Frames_1.Flags.hasIgnore(frame.flags));\n\t return;\n\t }\n\t else {\n\t errorMessage = \"Unexpected frame type [\".concat(frame.type, \"]\");\n\t }\n\t this.done = true;\n\t Reassembler.cancel(this);\n\t (_a = this.receiver) === null || _a === void 0 ? void 0 : _a.cancel();\n\t if (frame.type !== Frames_1.FrameTypes.CANCEL && frame.type !== Frames_1.FrameTypes.ERROR) {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t flags: Frames_1.Flags.NONE,\n\t code: Errors_1.ErrorCodes.CANCELED,\n\t message: errorMessage,\n\t streamId: this.streamId,\n\t });\n\t }\n\t this.stream.disconnect(this);\n\t // TODO: throws if strict\n\t };\n\t RequestStreamResponderStream.prototype.onError = function (error) {\n\t if (this.done) {\n\t console.warn(\"Trying to error for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t this.done = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t flags: Frames_1.Flags.NONE,\n\t code: error instanceof Errors_1.RSocketError\n\t ? error.code\n\t : Errors_1.ErrorCodes.APPLICATION_ERROR,\n\t message: error.message,\n\t streamId: this.streamId,\n\t });\n\t this.stream.disconnect(this);\n\t };\n\t RequestStreamResponderStream.prototype.onNext = function (payload, isCompletion) {\n\t var e_2, _a;\n\t if (this.done) {\n\t return;\n\t }\n\t if (isCompletion) {\n\t this.done = true;\n\t }\n\t // TODO: add payload size validation\n\t if ((0, Fragmenter_1.isFragmentable)(payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragment)(this.streamId, payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD, isCompletion)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_2_1) { e_2 = { error: e_2_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_2) throw e_2.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.NEXT |\n\t (isCompletion ? Frames_1.Flags.COMPLETE : Frames_1.Flags.NONE) |\n\t (payload.metadata ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE),\n\t data: payload.data,\n\t metadata: payload.metadata,\n\t streamId: this.streamId,\n\t });\n\t }\n\t if (isCompletion) {\n\t this.stream.disconnect(this);\n\t }\n\t };\n\t RequestStreamResponderStream.prototype.onComplete = function () {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.COMPLETE,\n\t streamId: this.streamId,\n\t data: null,\n\t metadata: null,\n\t });\n\t this.stream.disconnect(this);\n\t };\n\t RequestStreamResponderStream.prototype.onExtension = function (extendedType, content, canBeIgnored) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.EXT,\n\t streamId: this.streamId,\n\t flags: canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE,\n\t extendedType: extendedType,\n\t extendedContent: content,\n\t });\n\t };\n\t RequestStreamResponderStream.prototype.close = function (error) {\n\t var _a;\n\t if (this.done) {\n\t console.warn(\"Trying to close for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t Reassembler.cancel(this);\n\t (_a = this.receiver) === null || _a === void 0 ? void 0 : _a.cancel();\n\t };\n\t return RequestStreamResponderStream;\n\t}());\n\tRequestStreamStream.RequestStreamResponderStream = RequestStreamResponderStream;\n\t\n\treturn RequestStreamStream;\n}\n\nvar hasRequiredRSocketSupport;\n\nfunction requireRSocketSupport () {\n\tif (hasRequiredRSocketSupport) return RSocketSupport;\n\thasRequiredRSocketSupport = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tObject.defineProperty(RSocketSupport, \"__esModule\", { value: true });\n\tRSocketSupport.KeepAliveSender = RSocketSupport.KeepAliveHandler = RSocketSupport.DefaultConnectionFrameHandler = RSocketSupport.DefaultStreamRequestHandler = RSocketSupport.LeaseHandler = RSocketSupport.RSocketRequester = void 0;\n\tvar Errors_1 = requireErrors();\n\tvar Frames_1 = requireFrames();\n\tvar RequestChannelStream_1 = requireRequestChannelStream();\n\tvar RequestFnFStream_1 = requireRequestFnFStream();\n\tvar RequestResponseStream_1 = requireRequestResponseStream();\n\tvar RequestStreamStream_1 = requireRequestStreamStream();\n\tvar RSocketRequester = /** @class */ (function () {\n\t function RSocketRequester(connection, fragmentSize, leaseManager) {\n\t this.connection = connection;\n\t this.fragmentSize = fragmentSize;\n\t this.leaseManager = leaseManager;\n\t }\n\t RSocketRequester.prototype.fireAndForget = function (payload, responderStream) {\n\t var handler = new RequestFnFStream_1.RequestFnFRequesterStream(payload, responderStream, this.fragmentSize, this.leaseManager);\n\t if (this.leaseManager) {\n\t this.leaseManager.requestLease(handler);\n\t }\n\t else {\n\t this.connection.multiplexerDemultiplexer.createRequestStream(handler);\n\t }\n\t return handler;\n\t };\n\t RSocketRequester.prototype.requestResponse = function (payload, responderStream) {\n\t var handler = new RequestResponseStream_1.RequestResponseRequesterStream(payload, responderStream, this.fragmentSize, this.leaseManager);\n\t if (this.leaseManager) {\n\t this.leaseManager.requestLease(handler);\n\t }\n\t else {\n\t this.connection.multiplexerDemultiplexer.createRequestStream(handler);\n\t }\n\t return handler;\n\t };\n\t RSocketRequester.prototype.requestStream = function (payload, initialRequestN, responderStream) {\n\t var handler = new RequestStreamStream_1.RequestStreamRequesterStream(payload, responderStream, this.fragmentSize, initialRequestN, this.leaseManager);\n\t if (this.leaseManager) {\n\t this.leaseManager.requestLease(handler);\n\t }\n\t else {\n\t this.connection.multiplexerDemultiplexer.createRequestStream(handler);\n\t }\n\t return handler;\n\t };\n\t RSocketRequester.prototype.requestChannel = function (payload, initialRequestN, isCompleted, responderStream) {\n\t var handler = new RequestChannelStream_1.RequestChannelRequesterStream(payload, isCompleted, responderStream, this.fragmentSize, initialRequestN, this.leaseManager);\n\t if (this.leaseManager) {\n\t this.leaseManager.requestLease(handler);\n\t }\n\t else {\n\t this.connection.multiplexerDemultiplexer.createRequestStream(handler);\n\t }\n\t return handler;\n\t };\n\t RSocketRequester.prototype.metadataPush = function (metadata, responderStream) {\n\t throw new Error(\"Method not implemented.\");\n\t };\n\t RSocketRequester.prototype.close = function (error) {\n\t this.connection.close(error);\n\t };\n\t RSocketRequester.prototype.onClose = function (callback) {\n\t this.connection.onClose(callback);\n\t };\n\t return RSocketRequester;\n\t}());\n\tRSocketSupport.RSocketRequester = RSocketRequester;\n\tvar LeaseHandler = /** @class */ (function () {\n\t function LeaseHandler(maxPendingRequests, multiplexer) {\n\t this.maxPendingRequests = maxPendingRequests;\n\t this.multiplexer = multiplexer;\n\t this.pendingRequests = [];\n\t this.expirationTime = 0;\n\t this.availableLease = 0;\n\t }\n\t LeaseHandler.prototype.handle = function (frame) {\n\t this.expirationTime = frame.ttl + Date.now();\n\t this.availableLease = frame.requestCount;\n\t while (this.availableLease > 0 && this.pendingRequests.length > 0) {\n\t var handler = this.pendingRequests.shift();\n\t this.availableLease--;\n\t this.multiplexer.createRequestStream(handler);\n\t }\n\t };\n\t LeaseHandler.prototype.requestLease = function (handler) {\n\t var availableLease = this.availableLease;\n\t if (availableLease > 0 && Date.now() < this.expirationTime) {\n\t this.availableLease = availableLease - 1;\n\t this.multiplexer.createRequestStream(handler);\n\t return;\n\t }\n\t if (this.pendingRequests.length >= this.maxPendingRequests) {\n\t handler.handleReject(new Errors_1.RSocketError(Errors_1.ErrorCodes.REJECTED, \"No available lease given\"));\n\t return;\n\t }\n\t this.pendingRequests.push(handler);\n\t };\n\t LeaseHandler.prototype.cancelRequest = function (handler) {\n\t var index = this.pendingRequests.indexOf(handler);\n\t if (index > -1) {\n\t this.pendingRequests.splice(index, 1);\n\t }\n\t };\n\t return LeaseHandler;\n\t}());\n\tRSocketSupport.LeaseHandler = LeaseHandler;\n\tvar DefaultStreamRequestHandler = /** @class */ (function () {\n\t function DefaultStreamRequestHandler(rsocket, fragmentSize) {\n\t this.rsocket = rsocket;\n\t this.fragmentSize = fragmentSize;\n\t }\n\t DefaultStreamRequestHandler.prototype.handle = function (frame, stream) {\n\t switch (frame.type) {\n\t case Frames_1.FrameTypes.REQUEST_FNF:\n\t if (this.rsocket.fireAndForget) {\n\t new RequestFnFStream_1.RequestFnfResponderStream(frame.streamId, stream, this.rsocket.fireAndForget.bind(this.rsocket), frame);\n\t }\n\t return;\n\t case Frames_1.FrameTypes.REQUEST_RESPONSE:\n\t if (this.rsocket.requestResponse) {\n\t new RequestResponseStream_1.RequestResponseResponderStream(frame.streamId, stream, this.fragmentSize, this.rsocket.requestResponse.bind(this.rsocket), frame);\n\t return;\n\t }\n\t this.rejectRequest(frame.streamId, stream);\n\t return;\n\t case Frames_1.FrameTypes.REQUEST_STREAM:\n\t if (this.rsocket.requestStream) {\n\t new RequestStreamStream_1.RequestStreamResponderStream(frame.streamId, stream, this.fragmentSize, this.rsocket.requestStream.bind(this.rsocket), frame);\n\t return;\n\t }\n\t this.rejectRequest(frame.streamId, stream);\n\t return;\n\t case Frames_1.FrameTypes.REQUEST_CHANNEL:\n\t if (this.rsocket.requestChannel) {\n\t new RequestChannelStream_1.RequestChannelResponderStream(frame.streamId, stream, this.fragmentSize, this.rsocket.requestChannel.bind(this.rsocket), frame);\n\t return;\n\t }\n\t this.rejectRequest(frame.streamId, stream);\n\t return;\n\t }\n\t };\n\t DefaultStreamRequestHandler.prototype.rejectRequest = function (streamId, stream) {\n\t stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: streamId,\n\t flags: Frames_1.Flags.NONE,\n\t code: Errors_1.ErrorCodes.REJECTED,\n\t message: \"No available handler found\",\n\t });\n\t };\n\t DefaultStreamRequestHandler.prototype.close = function () { };\n\t return DefaultStreamRequestHandler;\n\t}());\n\tRSocketSupport.DefaultStreamRequestHandler = DefaultStreamRequestHandler;\n\tvar DefaultConnectionFrameHandler = /** @class */ (function () {\n\t function DefaultConnectionFrameHandler(connection, keepAliveHandler, keepAliveSender, leaseHandler, rsocket) {\n\t this.connection = connection;\n\t this.keepAliveHandler = keepAliveHandler;\n\t this.keepAliveSender = keepAliveSender;\n\t this.leaseHandler = leaseHandler;\n\t this.rsocket = rsocket;\n\t }\n\t DefaultConnectionFrameHandler.prototype.handle = function (frame) {\n\t switch (frame.type) {\n\t case Frames_1.FrameTypes.KEEPALIVE:\n\t this.keepAliveHandler.handle(frame);\n\t return;\n\t case Frames_1.FrameTypes.LEASE:\n\t if (this.leaseHandler) {\n\t this.leaseHandler.handle(frame);\n\t return;\n\t }\n\t // TODO throw exception and close connection\n\t return;\n\t case Frames_1.FrameTypes.ERROR:\n\t // TODO: add code validation\n\t this.connection.close(new Errors_1.RSocketError(frame.code, frame.message));\n\t return;\n\t case Frames_1.FrameTypes.METADATA_PUSH:\n\t if (this.rsocket.metadataPush) ;\n\t return;\n\t default:\n\t this.connection.multiplexerDemultiplexer.connectionOutbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t flags: Frames_1.Flags.NONE,\n\t message: \"Received unknown frame type\",\n\t code: Errors_1.ErrorCodes.CONNECTION_ERROR,\n\t });\n\t // TODO: throw an exception and close connection\n\t }\n\t };\n\t DefaultConnectionFrameHandler.prototype.pause = function () {\n\t var _a;\n\t this.keepAliveHandler.pause();\n\t (_a = this.keepAliveSender) === null || _a === void 0 ? void 0 : _a.pause();\n\t };\n\t DefaultConnectionFrameHandler.prototype.resume = function () {\n\t var _a;\n\t this.keepAliveHandler.start();\n\t (_a = this.keepAliveSender) === null || _a === void 0 ? void 0 : _a.start();\n\t };\n\t DefaultConnectionFrameHandler.prototype.close = function (error) {\n\t var _a;\n\t this.keepAliveHandler.close();\n\t (_a = this.rsocket.close) === null || _a === void 0 ? void 0 : _a.call(this.rsocket, error);\n\t };\n\t return DefaultConnectionFrameHandler;\n\t}());\n\tRSocketSupport.DefaultConnectionFrameHandler = DefaultConnectionFrameHandler;\n\tvar KeepAliveHandlerStates;\n\t(function (KeepAliveHandlerStates) {\n\t KeepAliveHandlerStates[KeepAliveHandlerStates[\"Paused\"] = 0] = \"Paused\";\n\t KeepAliveHandlerStates[KeepAliveHandlerStates[\"Running\"] = 1] = \"Running\";\n\t KeepAliveHandlerStates[KeepAliveHandlerStates[\"Closed\"] = 2] = \"Closed\";\n\t})(KeepAliveHandlerStates || (KeepAliveHandlerStates = {}));\n\tvar KeepAliveHandler = /** @class */ (function () {\n\t function KeepAliveHandler(connection, keepAliveTimeoutDuration) {\n\t this.connection = connection;\n\t this.keepAliveTimeoutDuration = keepAliveTimeoutDuration;\n\t this.state = KeepAliveHandlerStates.Paused;\n\t this.outbound = connection.multiplexerDemultiplexer.connectionOutbound;\n\t }\n\t KeepAliveHandler.prototype.handle = function (frame) {\n\t this.keepAliveLastReceivedMillis = Date.now();\n\t if (Frames_1.Flags.hasRespond(frame.flags)) {\n\t this.outbound.send({\n\t type: Frames_1.FrameTypes.KEEPALIVE,\n\t streamId: 0,\n\t data: frame.data,\n\t flags: frame.flags ^ Frames_1.Flags.RESPOND,\n\t lastReceivedPosition: 0,\n\t });\n\t }\n\t };\n\t KeepAliveHandler.prototype.start = function () {\n\t if (this.state !== KeepAliveHandlerStates.Paused) {\n\t return;\n\t }\n\t this.keepAliveLastReceivedMillis = Date.now();\n\t this.state = KeepAliveHandlerStates.Running;\n\t this.activeTimeout = setTimeout(this.timeoutCheck.bind(this), this.keepAliveTimeoutDuration);\n\t };\n\t KeepAliveHandler.prototype.pause = function () {\n\t if (this.state !== KeepAliveHandlerStates.Running) {\n\t return;\n\t }\n\t this.state = KeepAliveHandlerStates.Paused;\n\t clearTimeout(this.activeTimeout);\n\t };\n\t KeepAliveHandler.prototype.close = function () {\n\t this.state = KeepAliveHandlerStates.Closed;\n\t clearTimeout(this.activeTimeout);\n\t };\n\t KeepAliveHandler.prototype.timeoutCheck = function () {\n\t var now = Date.now();\n\t var noKeepAliveDuration = now - this.keepAliveLastReceivedMillis;\n\t if (noKeepAliveDuration >= this.keepAliveTimeoutDuration) {\n\t this.connection.close(new Error(\"No keep-alive acks for \".concat(this.keepAliveTimeoutDuration, \" millis\")));\n\t }\n\t else {\n\t this.activeTimeout = setTimeout(this.timeoutCheck.bind(this), Math.max(100, this.keepAliveTimeoutDuration - noKeepAliveDuration));\n\t }\n\t };\n\t return KeepAliveHandler;\n\t}());\n\tRSocketSupport.KeepAliveHandler = KeepAliveHandler;\n\tvar KeepAliveSenderStates;\n\t(function (KeepAliveSenderStates) {\n\t KeepAliveSenderStates[KeepAliveSenderStates[\"Paused\"] = 0] = \"Paused\";\n\t KeepAliveSenderStates[KeepAliveSenderStates[\"Running\"] = 1] = \"Running\";\n\t KeepAliveSenderStates[KeepAliveSenderStates[\"Closed\"] = 2] = \"Closed\";\n\t})(KeepAliveSenderStates || (KeepAliveSenderStates = {}));\n\tvar KeepAliveSender = /** @class */ (function () {\n\t function KeepAliveSender(outbound, keepAlivePeriodDuration) {\n\t this.outbound = outbound;\n\t this.keepAlivePeriodDuration = keepAlivePeriodDuration;\n\t this.state = KeepAliveSenderStates.Paused;\n\t }\n\t KeepAliveSender.prototype.sendKeepAlive = function () {\n\t this.outbound.send({\n\t type: Frames_1.FrameTypes.KEEPALIVE,\n\t streamId: 0,\n\t data: undefined,\n\t flags: Frames_1.Flags.RESPOND,\n\t lastReceivedPosition: 0,\n\t });\n\t };\n\t KeepAliveSender.prototype.start = function () {\n\t if (this.state !== KeepAliveSenderStates.Paused) {\n\t return;\n\t }\n\t this.state = KeepAliveSenderStates.Running;\n\t this.activeInterval = setInterval(this.sendKeepAlive.bind(this), this.keepAlivePeriodDuration);\n\t };\n\t KeepAliveSender.prototype.pause = function () {\n\t if (this.state !== KeepAliveSenderStates.Running) {\n\t return;\n\t }\n\t this.state = KeepAliveSenderStates.Paused;\n\t clearInterval(this.activeInterval);\n\t };\n\t KeepAliveSender.prototype.close = function () {\n\t this.state = KeepAliveSenderStates.Closed;\n\t clearInterval(this.activeInterval);\n\t };\n\t return KeepAliveSender;\n\t}());\n\tRSocketSupport.KeepAliveSender = KeepAliveSender;\n\t\n\treturn RSocketSupport;\n}\n\nvar Resume = {};\n\nvar hasRequiredResume;\n\nfunction requireResume () {\n\tif (hasRequiredResume) return Resume;\n\thasRequiredResume = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __values = (Resume && Resume.__values) || function(o) {\n\t var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n\t if (m) return m.call(o);\n\t if (o && typeof o.length === \"number\") return {\n\t next: function () {\n\t if (o && i >= o.length) o = void 0;\n\t return { value: o && o[i++], done: !o };\n\t }\n\t };\n\t throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n\t};\n\tObject.defineProperty(Resume, \"__esModule\", { value: true });\n\tResume.FrameStore = void 0;\n\tvar _1 = requireDist();\n\tvar Codecs_1 = requireCodecs();\n\tvar FrameStore = /** @class */ (function () {\n\t function FrameStore() {\n\t this.storedFrames = [];\n\t this._lastReceivedFramePosition = 0;\n\t this._firstAvailableFramePosition = 0;\n\t this._lastSentFramePosition = 0;\n\t }\n\t Object.defineProperty(FrameStore.prototype, \"lastReceivedFramePosition\", {\n\t get: function () {\n\t return this._lastReceivedFramePosition;\n\t },\n\t enumerable: false,\n\t configurable: true\n\t });\n\t Object.defineProperty(FrameStore.prototype, \"firstAvailableFramePosition\", {\n\t get: function () {\n\t return this._firstAvailableFramePosition;\n\t },\n\t enumerable: false,\n\t configurable: true\n\t });\n\t Object.defineProperty(FrameStore.prototype, \"lastSentFramePosition\", {\n\t get: function () {\n\t return this._lastSentFramePosition;\n\t },\n\t enumerable: false,\n\t configurable: true\n\t });\n\t FrameStore.prototype.store = function (frame) {\n\t this._lastSentFramePosition += (0, Codecs_1.sizeOfFrame)(frame);\n\t this.storedFrames.push(frame);\n\t };\n\t FrameStore.prototype.record = function (frame) {\n\t this._lastReceivedFramePosition += (0, Codecs_1.sizeOfFrame)(frame);\n\t };\n\t FrameStore.prototype.dropTo = function (lastReceivedPosition) {\n\t var bytesToDrop = lastReceivedPosition - this._firstAvailableFramePosition;\n\t while (bytesToDrop > 0 && this.storedFrames.length > 0) {\n\t var storedFrame = this.storedFrames.shift();\n\t bytesToDrop -= (0, Codecs_1.sizeOfFrame)(storedFrame);\n\t }\n\t if (bytesToDrop !== 0) {\n\t throw new _1.RSocketError(_1.ErrorCodes.CONNECTION_ERROR, \"State inconsistency. Expected bytes to drop \".concat(lastReceivedPosition - this._firstAvailableFramePosition, \" but actual \").concat(bytesToDrop));\n\t }\n\t this._firstAvailableFramePosition = lastReceivedPosition;\n\t };\n\t FrameStore.prototype.drain = function (consumer) {\n\t var e_1, _a;\n\t try {\n\t for (var _b = __values(this.storedFrames), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t consumer(frame);\n\t }\n\t }\n\t catch (e_1_1) { e_1 = { error: e_1_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_1) throw e_1.error; }\n\t }\n\t };\n\t return FrameStore;\n\t}());\n\tResume.FrameStore = FrameStore;\n\t\n\treturn Resume;\n}\n\nvar hasRequiredRSocketConnector;\n\nfunction requireRSocketConnector () {\n\tif (hasRequiredRSocketConnector) return RSocketConnector;\n\thasRequiredRSocketConnector = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __awaiter = (RSocketConnector && RSocketConnector.__awaiter) || function (thisArg, _arguments, P, generator) {\n\t function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n\t return new (P || (P = Promise))(function (resolve, reject) {\n\t function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n\t function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n\t function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n\t step((generator = generator.apply(thisArg, _arguments || [])).next());\n\t });\n\t};\n\tvar __generator = (RSocketConnector && RSocketConnector.__generator) || function (thisArg, body) {\n\t var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n\t return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n\t function verb(n) { return function (v) { return step([n, v]); }; }\n\t function step(op) {\n\t if (f) throw new TypeError(\"Generator is already executing.\");\n\t while (_) try {\n\t if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n\t if (y = 0, t) op = [op[0] & 2, t.value];\n\t switch (op[0]) {\n\t case 0: case 1: t = op; break;\n\t case 4: _.label++; return { value: op[1], done: false };\n\t case 5: _.label++; y = op[1]; op = [0]; continue;\n\t case 7: op = _.ops.pop(); _.trys.pop(); continue;\n\t default:\n\t if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n\t if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n\t if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n\t if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n\t if (t[2]) _.ops.pop();\n\t _.trys.pop(); continue;\n\t }\n\t op = body.call(thisArg, _);\n\t } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n\t if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n\t }\n\t};\n\tObject.defineProperty(RSocketConnector, \"__esModule\", { value: true });\n\tRSocketConnector.RSocketConnector = void 0;\n\tvar ClientServerMultiplexerDemultiplexer_1 = requireClientServerMultiplexerDemultiplexer();\n\tvar Frames_1 = requireFrames();\n\tvar RSocketSupport_1 = requireRSocketSupport();\n\tvar Resume_1 = requireResume();\n\tvar RSocketConnector$1 = /** @class */ (function () {\n\t function RSocketConnector(config) {\n\t this.config = config;\n\t }\n\t RSocketConnector.prototype.connect = function () {\n\t var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;\n\t return __awaiter(this, void 0, void 0, function () {\n\t var config, setupFrame, connection, keepAliveSender, keepAliveHandler, leaseHandler, responder, connectionFrameHandler, streamsHandler;\n\t var _this = this;\n\t return __generator(this, function (_w) {\n\t switch (_w.label) {\n\t case 0:\n\t config = this.config;\n\t setupFrame = {\n\t type: Frames_1.FrameTypes.SETUP,\n\t dataMimeType: (_b = (_a = config.setup) === null || _a === void 0 ? void 0 : _a.dataMimeType) !== null && _b !== void 0 ? _b : \"application/octet-stream\",\n\t metadataMimeType: (_d = (_c = config.setup) === null || _c === void 0 ? void 0 : _c.metadataMimeType) !== null && _d !== void 0 ? _d : \"application/octet-stream\",\n\t keepAlive: (_f = (_e = config.setup) === null || _e === void 0 ? void 0 : _e.keepAlive) !== null && _f !== void 0 ? _f : 60000,\n\t lifetime: (_h = (_g = config.setup) === null || _g === void 0 ? void 0 : _g.lifetime) !== null && _h !== void 0 ? _h : 300000,\n\t metadata: (_k = (_j = config.setup) === null || _j === void 0 ? void 0 : _j.payload) === null || _k === void 0 ? void 0 : _k.metadata,\n\t data: (_m = (_l = config.setup) === null || _l === void 0 ? void 0 : _l.payload) === null || _m === void 0 ? void 0 : _m.data,\n\t resumeToken: (_p = (_o = config.resume) === null || _o === void 0 ? void 0 : _o.tokenGenerator()) !== null && _p !== void 0 ? _p : null,\n\t streamId: 0,\n\t majorVersion: 1,\n\t minorVersion: 0,\n\t flags: (((_r = (_q = config.setup) === null || _q === void 0 ? void 0 : _q.payload) === null || _r === void 0 ? void 0 : _r.metadata) ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE) |\n\t (config.lease ? Frames_1.Flags.LEASE : Frames_1.Flags.NONE) |\n\t (config.resume ? Frames_1.Flags.RESUME_ENABLE : Frames_1.Flags.NONE),\n\t };\n\t return [4 /*yield*/, config.transport.connect(function (outbound) {\n\t return config.resume\n\t ? new ClientServerMultiplexerDemultiplexer_1.ResumableClientServerInputMultiplexerDemultiplexer(ClientServerMultiplexerDemultiplexer_1.StreamIdGenerator.create(-1), outbound, outbound, new Resume_1.FrameStore(), // TODO: add size control\n\t setupFrame.resumeToken.toString(), function (self, frameStore) { return __awaiter(_this, void 0, void 0, function () {\n\t var multiplexerDemultiplexerProvider, reconnectionAttempts, reconnector;\n\t return __generator(this, function (_a) {\n\t switch (_a.label) {\n\t case 0:\n\t multiplexerDemultiplexerProvider = function (outbound) {\n\t outbound.send({\n\t type: Frames_1.FrameTypes.RESUME,\n\t streamId: 0,\n\t flags: Frames_1.Flags.NONE,\n\t clientPosition: frameStore.firstAvailableFramePosition,\n\t serverPosition: frameStore.lastReceivedFramePosition,\n\t majorVersion: setupFrame.minorVersion,\n\t minorVersion: setupFrame.majorVersion,\n\t resumeToken: setupFrame.resumeToken,\n\t });\n\t return new ClientServerMultiplexerDemultiplexer_1.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer(outbound, outbound, self);\n\t };\n\t reconnectionAttempts = -1;\n\t reconnector = function () {\n\t reconnectionAttempts++;\n\t return config.resume\n\t .reconnectFunction(reconnectionAttempts)\n\t .then(function () {\n\t return config.transport\n\t .connect(multiplexerDemultiplexerProvider)\n\t .catch(reconnector);\n\t });\n\t };\n\t return [4 /*yield*/, reconnector()];\n\t case 1:\n\t _a.sent();\n\t return [2 /*return*/];\n\t }\n\t });\n\t }); })\n\t : new ClientServerMultiplexerDemultiplexer_1.ClientServerInputMultiplexerDemultiplexer(ClientServerMultiplexerDemultiplexer_1.StreamIdGenerator.create(-1), outbound, outbound);\n\t })];\n\t case 1:\n\t connection = _w.sent();\n\t keepAliveSender = new RSocketSupport_1.KeepAliveSender(connection.multiplexerDemultiplexer.connectionOutbound, setupFrame.keepAlive);\n\t keepAliveHandler = new RSocketSupport_1.KeepAliveHandler(connection, setupFrame.lifetime);\n\t leaseHandler = config.lease\n\t ? new RSocketSupport_1.LeaseHandler((_s = config.lease.maxPendingRequests) !== null && _s !== void 0 ? _s : 256, connection.multiplexerDemultiplexer)\n\t : undefined;\n\t responder = (_t = config.responder) !== null && _t !== void 0 ? _t : {};\n\t connectionFrameHandler = new RSocketSupport_1.DefaultConnectionFrameHandler(connection, keepAliveHandler, keepAliveSender, leaseHandler, responder);\n\t streamsHandler = new RSocketSupport_1.DefaultStreamRequestHandler(responder, 0);\n\t connection.onClose(function (e) {\n\t keepAliveSender.close();\n\t keepAliveHandler.close();\n\t connectionFrameHandler.close(e);\n\t });\n\t connection.multiplexerDemultiplexer.connectionInbound(connectionFrameHandler);\n\t connection.multiplexerDemultiplexer.handleRequestStream(streamsHandler);\n\t connection.multiplexerDemultiplexer.connectionOutbound.send(setupFrame);\n\t keepAliveHandler.start();\n\t keepAliveSender.start();\n\t return [2 /*return*/, new RSocketSupport_1.RSocketRequester(connection, (_v = (_u = config.fragmentation) === null || _u === void 0 ? void 0 : _u.maxOutboundFragmentSize) !== null && _v !== void 0 ? _v : 0, leaseHandler)];\n\t }\n\t });\n\t });\n\t };\n\t return RSocketConnector;\n\t}());\n\tRSocketConnector.RSocketConnector = RSocketConnector$1;\n\t\n\treturn RSocketConnector;\n}\n\nvar RSocketServer = {};\n\nvar hasRequiredRSocketServer;\n\nfunction requireRSocketServer () {\n\tif (hasRequiredRSocketServer) return RSocketServer;\n\thasRequiredRSocketServer = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __awaiter = (RSocketServer && RSocketServer.__awaiter) || function (thisArg, _arguments, P, generator) {\n\t function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n\t return new (P || (P = Promise))(function (resolve, reject) {\n\t function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n\t function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n\t function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n\t step((generator = generator.apply(thisArg, _arguments || [])).next());\n\t });\n\t};\n\tvar __generator = (RSocketServer && RSocketServer.__generator) || function (thisArg, body) {\n\t var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n\t return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n\t function verb(n) { return function (v) { return step([n, v]); }; }\n\t function step(op) {\n\t if (f) throw new TypeError(\"Generator is already executing.\");\n\t while (_) try {\n\t if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n\t if (y = 0, t) op = [op[0] & 2, t.value];\n\t switch (op[0]) {\n\t case 0: case 1: t = op; break;\n\t case 4: _.label++; return { value: op[1], done: false };\n\t case 5: _.label++; y = op[1]; op = [0]; continue;\n\t case 7: op = _.ops.pop(); _.trys.pop(); continue;\n\t default:\n\t if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n\t if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n\t if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n\t if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n\t if (t[2]) _.ops.pop();\n\t _.trys.pop(); continue;\n\t }\n\t op = body.call(thisArg, _);\n\t } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n\t if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n\t }\n\t};\n\tObject.defineProperty(RSocketServer, \"__esModule\", { value: true });\n\tRSocketServer.RSocketServer = void 0;\n\tvar ClientServerMultiplexerDemultiplexer_1 = requireClientServerMultiplexerDemultiplexer();\n\tvar Errors_1 = requireErrors();\n\tvar Frames_1 = requireFrames();\n\tvar RSocketSupport_1 = requireRSocketSupport();\n\tvar Resume_1 = requireResume();\n\tvar RSocketServer$1 = /** @class */ (function () {\n\t function RSocketServer(config) {\n\t var _a, _b;\n\t this.acceptor = config.acceptor;\n\t this.transport = config.transport;\n\t this.lease = config.lease;\n\t this.serverSideKeepAlive = config.serverSideKeepAlive;\n\t this.sessionStore = config.resume ? {} : undefined;\n\t this.sessionTimeout = (_b = (_a = config.resume) === null || _a === void 0 ? void 0 : _a.sessionTimeout) !== null && _b !== void 0 ? _b : undefined;\n\t }\n\t RSocketServer.prototype.bind = function () {\n\t return __awaiter(this, void 0, void 0, function () {\n\t var _this = this;\n\t return __generator(this, function (_a) {\n\t switch (_a.label) {\n\t case 0: return [4 /*yield*/, this.transport.bind(function (frame, connection) { return __awaiter(_this, void 0, void 0, function () {\n\t var _a, error, error, leaseHandler, requester, responder, keepAliveHandler_1, keepAliveSender_1, connectionFrameHandler_1, streamsHandler, e_1;\n\t var _b, _c, _d, _e;\n\t return __generator(this, function (_f) {\n\t switch (_f.label) {\n\t case 0:\n\t _a = frame.type;\n\t switch (_a) {\n\t case Frames_1.FrameTypes.SETUP: return [3 /*break*/, 1];\n\t case Frames_1.FrameTypes.RESUME: return [3 /*break*/, 5];\n\t }\n\t return [3 /*break*/, 6];\n\t case 1:\n\t _f.trys.push([1, 3, , 4]);\n\t if (this.lease && !Frames_1.Flags.hasLease(frame.flags)) {\n\t error = new Errors_1.RSocketError(Errors_1.ErrorCodes.REJECTED_SETUP, \"Lease has to be enabled\");\n\t connection.multiplexerDemultiplexer.connectionOutbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t flags: Frames_1.Flags.NONE,\n\t code: error.code,\n\t message: error.message,\n\t });\n\t connection.close(error);\n\t return [2 /*return*/];\n\t }\n\t if (Frames_1.Flags.hasLease(frame.flags) && !this.lease) {\n\t error = new Errors_1.RSocketError(Errors_1.ErrorCodes.REJECTED_SETUP, \"Lease has to be disabled\");\n\t connection.multiplexerDemultiplexer.connectionOutbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t flags: Frames_1.Flags.NONE,\n\t code: error.code,\n\t message: error.message,\n\t });\n\t connection.close(error);\n\t return [2 /*return*/];\n\t }\n\t leaseHandler = Frames_1.Flags.hasLease(frame.flags)\n\t ? new RSocketSupport_1.LeaseHandler((_b = this.lease.maxPendingRequests) !== null && _b !== void 0 ? _b : 256, connection.multiplexerDemultiplexer)\n\t : undefined;\n\t requester = new RSocketSupport_1.RSocketRequester(connection, (_d = (_c = this.fragmentation) === null || _c === void 0 ? void 0 : _c.maxOutboundFragmentSize) !== null && _d !== void 0 ? _d : 0, leaseHandler);\n\t return [4 /*yield*/, this.acceptor.accept({\n\t data: frame.data,\n\t dataMimeType: frame.dataMimeType,\n\t metadata: frame.metadata,\n\t metadataMimeType: frame.metadataMimeType,\n\t flags: frame.flags,\n\t keepAliveMaxLifetime: frame.lifetime,\n\t keepAliveInterval: frame.keepAlive,\n\t resumeToken: frame.resumeToken,\n\t }, requester)];\n\t case 2:\n\t responder = _f.sent();\n\t keepAliveHandler_1 = new RSocketSupport_1.KeepAliveHandler(connection, frame.lifetime);\n\t keepAliveSender_1 = this.serverSideKeepAlive\n\t ? new RSocketSupport_1.KeepAliveSender(connection.multiplexerDemultiplexer.connectionOutbound, frame.keepAlive)\n\t : undefined;\n\t connectionFrameHandler_1 = new RSocketSupport_1.DefaultConnectionFrameHandler(connection, keepAliveHandler_1, keepAliveSender_1, leaseHandler, responder);\n\t streamsHandler = new RSocketSupport_1.DefaultStreamRequestHandler(responder, 0);\n\t connection.onClose(function (e) {\n\t keepAliveSender_1 === null || keepAliveSender_1 === void 0 ? void 0 : keepAliveSender_1.close();\n\t keepAliveHandler_1.close();\n\t connectionFrameHandler_1.close(e);\n\t });\n\t connection.multiplexerDemultiplexer.connectionInbound(connectionFrameHandler_1);\n\t connection.multiplexerDemultiplexer.handleRequestStream(streamsHandler);\n\t keepAliveHandler_1.start();\n\t keepAliveSender_1 === null || keepAliveSender_1 === void 0 ? void 0 : keepAliveSender_1.start();\n\t return [3 /*break*/, 4];\n\t case 3:\n\t e_1 = _f.sent();\n\t connection.multiplexerDemultiplexer.connectionOutbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t code: Errors_1.ErrorCodes.REJECTED_SETUP,\n\t message: (_e = e_1.message) !== null && _e !== void 0 ? _e : \"\",\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t connection.close(e_1 instanceof Errors_1.RSocketError\n\t ? e_1\n\t : new Errors_1.RSocketError(Errors_1.ErrorCodes.REJECTED_SETUP, e_1.message));\n\t return [3 /*break*/, 4];\n\t case 4: return [2 /*return*/];\n\t case 5:\n\t {\n\t // frame should be handled earlier\n\t return [2 /*return*/];\n\t }\n\t case 6:\n\t {\n\t connection.multiplexerDemultiplexer.connectionOutbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t code: Errors_1.ErrorCodes.UNSUPPORTED_SETUP,\n\t message: \"Unsupported setup\",\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t connection.close(new Errors_1.RSocketError(Errors_1.ErrorCodes.UNSUPPORTED_SETUP));\n\t }\n\t _f.label = 7;\n\t case 7: return [2 /*return*/];\n\t }\n\t });\n\t }); }, function (frame, outbound) {\n\t if (frame.type === Frames_1.FrameTypes.RESUME) {\n\t if (_this.sessionStore) {\n\t var multiplexerDemultiplexer = _this.sessionStore[frame.resumeToken.toString()];\n\t if (!multiplexerDemultiplexer) {\n\t outbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t code: Errors_1.ErrorCodes.REJECTED_RESUME,\n\t message: \"No session found for the given resume token\",\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t outbound.close();\n\t return;\n\t }\n\t multiplexerDemultiplexer.resume(frame, outbound, outbound);\n\t return multiplexerDemultiplexer;\n\t }\n\t outbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t code: Errors_1.ErrorCodes.REJECTED_RESUME,\n\t message: \"Resume is not enabled\",\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t outbound.close();\n\t return;\n\t }\n\t else if (frame.type === Frames_1.FrameTypes.SETUP) {\n\t if (Frames_1.Flags.hasResume(frame.flags)) {\n\t if (!_this.sessionStore) {\n\t var error = new Errors_1.RSocketError(Errors_1.ErrorCodes.REJECTED_SETUP, \"No resume support\");\n\t outbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t flags: Frames_1.Flags.NONE,\n\t code: error.code,\n\t message: error.message,\n\t });\n\t outbound.close(error);\n\t return;\n\t }\n\t var multiplexerDumiltiplexer = new ClientServerMultiplexerDemultiplexer_1.ResumableClientServerInputMultiplexerDemultiplexer(ClientServerMultiplexerDemultiplexer_1.StreamIdGenerator.create(0), outbound, outbound, new Resume_1.FrameStore(), // TODO: add size parameter\n\t frame.resumeToken.toString(), _this.sessionStore, _this.sessionTimeout);\n\t _this.sessionStore[frame.resumeToken.toString()] =\n\t multiplexerDumiltiplexer;\n\t return multiplexerDumiltiplexer;\n\t }\n\t }\n\t return new ClientServerMultiplexerDemultiplexer_1.ClientServerInputMultiplexerDemultiplexer(ClientServerMultiplexerDemultiplexer_1.StreamIdGenerator.create(0), outbound, outbound);\n\t })];\n\t case 1: return [2 /*return*/, _a.sent()];\n\t }\n\t });\n\t });\n\t };\n\t return RSocketServer;\n\t}());\n\tRSocketServer.RSocketServer = RSocketServer$1;\n\t\n\treturn RSocketServer;\n}\n\nvar Transport = {};\n\nvar hasRequiredTransport;\n\nfunction requireTransport () {\n\tif (hasRequiredTransport) return Transport;\n\thasRequiredTransport = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tObject.defineProperty(Transport, \"__esModule\", { value: true });\n\t\n\treturn Transport;\n}\n\nvar hasRequiredDist;\n\nfunction requireDist () {\n\tif (hasRequiredDist) return dist;\n\thasRequiredDist = 1;\n\t(function (exports$1) {\n\t\t/*\n\t\t * Copyright 2021-2022 the original author or authors.\n\t\t *\n\t\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t\t * you may not use this file except in compliance with the License.\n\t\t * You may obtain a copy of the License at\n\t\t *\n\t\t * http://www.apache.org/licenses/LICENSE-2.0\n\t\t *\n\t\t * Unless required by applicable law or agreed to in writing, software\n\t\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t\t * See the License for the specific language governing permissions and\n\t\t * limitations under the License.\n\t\t */\n\t\tvar __createBinding = (dist && dist.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n\t\t if (k2 === undefined) k2 = k;\n\t\t Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n\t\t}) : (function(o, m, k, k2) {\n\t\t if (k2 === undefined) k2 = k;\n\t\t o[k2] = m[k];\n\t\t}));\n\t\tvar __exportStar = (dist && dist.__exportStar) || function(m, exports$1) {\n\t\t for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);\n\t\t};\n\t\tObject.defineProperty(exports$1, \"__esModule\", { value: true });\n\t\t__exportStar(requireCodecs(), exports$1);\n\t\t__exportStar(requireCommon(), exports$1);\n\t\t__exportStar(requireDeferred(), exports$1);\n\t\t__exportStar(requireErrors(), exports$1);\n\t\t__exportStar(requireFrames(), exports$1);\n\t\t__exportStar(requireRSocket(), exports$1);\n\t\t__exportStar(requireRSocketConnector(), exports$1);\n\t\t__exportStar(requireRSocketServer(), exports$1);\n\t\t__exportStar(requireTransport(), exports$1);\n\t\t\n\t} (dist));\n\treturn dist;\n}\n\nvar distExports = requireDist();\n\nvar version = \"1.47.0\";\nvar PACKAGE = {\n\tversion: version};\n\nconst DEFAULT_PRESSURE_LIMITS = {\n highWater: 10,\n lowWater: 0\n};\n/**\n * A very basic implementation of a data stream with backpressure support which does not use\n * native JS streams or async iterators.\n * This is handy for environments such as React Native which need polyfills for the above.\n */\nclass DataStream extends BaseObserver {\n options;\n dataQueue;\n isClosed;\n processingPromise;\n notifyDataAdded;\n logger;\n mapLine;\n constructor(options) {\n super();\n this.options = options;\n this.processingPromise = null;\n this.isClosed = false;\n this.dataQueue = [];\n this.mapLine = options?.mapLine ?? ((line) => line);\n this.logger = options?.logger ?? Logger.get('DataStream');\n if (options?.closeOnError) {\n const l = this.registerListener({\n error: (ex) => {\n l?.();\n this.close();\n }\n });\n }\n }\n get highWatermark() {\n return this.options?.pressure?.highWaterMark ?? DEFAULT_PRESSURE_LIMITS.highWater;\n }\n get lowWatermark() {\n return this.options?.pressure?.lowWaterMark ?? DEFAULT_PRESSURE_LIMITS.lowWater;\n }\n get closed() {\n return this.isClosed;\n }\n async close() {\n this.isClosed = true;\n await this.processingPromise;\n this.iterateListeners((l) => l.closed?.());\n // Discard any data in the queue\n this.dataQueue = [];\n this.listeners.clear();\n }\n /**\n * Enqueues data for the consumers to read\n */\n enqueueData(data) {\n if (this.isClosed) {\n throw new Error('Cannot enqueue data into closed stream.');\n }\n this.dataQueue.push(data);\n this.notifyDataAdded?.();\n this.processQueue();\n }\n /**\n * Reads data once from the data stream\n * @returns a Data payload or Null if the stream closed.\n */\n async read() {\n if (this.closed) {\n return null;\n }\n // Wait for any pending processing to complete first.\n // This ensures we register our listener before calling processQueue(),\n // avoiding a race where processQueue() sees no reader and returns early.\n if (this.processingPromise) {\n await this.processingPromise;\n }\n // Re-check after await - stream may have closed while we were waiting\n if (this.closed) {\n return null;\n }\n return new Promise((resolve, reject) => {\n const l = this.registerListener({\n data: async (data) => {\n resolve(data);\n // Remove the listener\n l?.();\n },\n closed: () => {\n resolve(null);\n l?.();\n },\n error: (ex) => {\n reject(ex);\n l?.();\n }\n });\n this.processQueue();\n });\n }\n /**\n * Executes a callback for each data item in the stream\n */\n forEach(callback) {\n if (this.dataQueue.length <= this.lowWatermark) {\n this.iterateAsyncErrored(async (l) => l.lowWater?.());\n }\n return this.registerListener({\n data: callback\n });\n }\n processQueue() {\n if (this.processingPromise) {\n return;\n }\n const promise = (this.processingPromise = this._processQueue());\n promise.finally(() => {\n this.processingPromise = null;\n });\n return promise;\n }\n hasDataReader() {\n return Array.from(this.listeners.values()).some((l) => !!l.data);\n }\n async _processQueue() {\n /**\n * Allow listeners to mutate the queue before processing.\n * This allows for operations such as dropping or compressing data\n * on high water or requesting more data on low water.\n */\n if (this.dataQueue.length >= this.highWatermark) {\n await this.iterateAsyncErrored(async (l) => l.highWater?.());\n }\n if (this.isClosed || !this.hasDataReader()) {\n return;\n }\n if (this.dataQueue.length) {\n const data = this.dataQueue.shift();\n const mapped = this.mapLine(data);\n await this.iterateAsyncErrored(async (l) => l.data?.(mapped));\n }\n if (this.dataQueue.length <= this.lowWatermark) {\n const dataAdded = new Promise((resolve) => {\n this.notifyDataAdded = resolve;\n });\n await Promise.race([this.iterateAsyncErrored(async (l) => l.lowWater?.()), dataAdded]);\n this.notifyDataAdded = null;\n }\n if (this.dataQueue.length > 0) {\n setTimeout(() => this.processQueue());\n }\n }\n async iterateAsyncErrored(cb) {\n // Important: We need to copy the listeners, as calling a listener could result in adding another\n // listener, resulting in infinite loops.\n const listeners = Array.from(this.listeners.values());\n for (let i of listeners) {\n try {\n await cb(i);\n }\n catch (ex) {\n this.logger.error(ex);\n this.iterateListeners((l) => l.error?.(ex));\n }\n }\n }\n}\n\nvar WebsocketDuplexConnection = {};\n\nvar hasRequiredWebsocketDuplexConnection;\n\nfunction requireWebsocketDuplexConnection () {\n\tif (hasRequiredWebsocketDuplexConnection) return WebsocketDuplexConnection;\n\thasRequiredWebsocketDuplexConnection = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __extends = (WebsocketDuplexConnection && WebsocketDuplexConnection.__extends) || (function () {\n\t var extendStatics = function (d, b) {\n\t extendStatics = Object.setPrototypeOf ||\n\t ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n\t function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n\t return extendStatics(d, b);\n\t };\n\t return function (d, b) {\n\t if (typeof b !== \"function\" && b !== null)\n\t throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n\t extendStatics(d, b);\n\t function __() { this.constructor = d; }\n\t d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n\t };\n\t})();\n\tObject.defineProperty(WebsocketDuplexConnection, \"__esModule\", { value: true });\n\tWebsocketDuplexConnection.WebsocketDuplexConnection = void 0;\n\tvar rsocket_core_1 = requireDist();\n\tvar WebsocketDuplexConnection$1 = /** @class */ (function (_super) {\n\t __extends(WebsocketDuplexConnection, _super);\n\t function WebsocketDuplexConnection(websocket, deserializer, multiplexerDemultiplexerFactory) {\n\t var _this = _super.call(this) || this;\n\t _this.websocket = websocket;\n\t _this.deserializer = deserializer;\n\t _this.handleClosed = function (e) {\n\t _this.close(new Error(e.reason || \"WebsocketDuplexConnection: Socket closed unexpectedly.\"));\n\t };\n\t _this.handleError = function (e) {\n\t _this.close(e.error);\n\t };\n\t _this.handleMessage = function (message) {\n\t try {\n\t var buffer = bufferExports.Buffer.from(message.data);\n\t var frame = _this.deserializer.deserializeFrame(buffer);\n\t _this.multiplexerDemultiplexer.handle(frame);\n\t }\n\t catch (error) {\n\t _this.close(error);\n\t }\n\t };\n\t websocket.addEventListener(\"close\", _this.handleClosed);\n\t websocket.addEventListener(\"error\", _this.handleError);\n\t websocket.addEventListener(\"message\", _this.handleMessage);\n\t _this.multiplexerDemultiplexer = multiplexerDemultiplexerFactory(_this);\n\t return _this;\n\t }\n\t Object.defineProperty(WebsocketDuplexConnection.prototype, \"availability\", {\n\t get: function () {\n\t return this.done ? 0 : 1;\n\t },\n\t enumerable: false,\n\t configurable: true\n\t });\n\t WebsocketDuplexConnection.prototype.close = function (error) {\n\t if (this.done) {\n\t _super.prototype.close.call(this, error);\n\t return;\n\t }\n\t this.websocket.removeEventListener(\"close\", this.handleClosed);\n\t this.websocket.removeEventListener(\"error\", this.handleError);\n\t this.websocket.removeEventListener(\"message\", this.handleMessage);\n\t this.websocket.close();\n\t delete this.websocket;\n\t _super.prototype.close.call(this, error);\n\t };\n\t WebsocketDuplexConnection.prototype.send = function (frame) {\n\t if (this.done) {\n\t return;\n\t }\n\t var buffer = (0, rsocket_core_1.serializeFrame)(frame);\n\t this.websocket.send(buffer);\n\t };\n\t return WebsocketDuplexConnection;\n\t}(rsocket_core_1.Deferred));\n\tWebsocketDuplexConnection.WebsocketDuplexConnection = WebsocketDuplexConnection$1;\n\t\n\treturn WebsocketDuplexConnection;\n}\n\nvar WebsocketDuplexConnectionExports = requireWebsocketDuplexConnection();\n\n/**\n * Adapted from rsocket-websocket-client\n * https://github.com/rsocket/rsocket-js/blob/e224cf379e747c4f1ddc4f2fa111854626cc8575/packages/rsocket-websocket-client/src/WebsocketClientTransport.ts#L17\n * This adds additional error handling for React Native iOS.\n * This particularly adds a close listener to handle cases where the WebSocket\n * connection closes immediately after opening without emitting an error.\n */\nclass WebsocketClientTransport {\n url;\n factory;\n constructor(options) {\n this.url = options.url;\n this.factory = options.wsCreator ?? ((url) => new WebSocket(url));\n }\n connect(multiplexerDemultiplexerFactory) {\n return new Promise((resolve, reject) => {\n const websocket = this.factory(this.url);\n websocket.binaryType = 'arraybuffer';\n let removeListeners;\n const openListener = () => {\n removeListeners();\n resolve(new WebsocketDuplexConnectionExports.WebsocketDuplexConnection(websocket, new distExports.Deserializer(), multiplexerDemultiplexerFactory));\n };\n const errorListener = (ev) => {\n removeListeners();\n // We add a default error in that case.\n if (ev.error != null) {\n // undici typically provides an error object\n reject(ev.error);\n }\n else if (ev.message != null) {\n // React Native typically does not provide an error object, but does provide a message\n reject(new Error(`Failed to create websocket connection: ${ev.message}`));\n }\n else {\n // Browsers often provide no details at all\n reject(new Error(`Failed to create websocket connection to ${this.url}`));\n }\n };\n /**\n * In some cases, such as React Native iOS, the WebSocket connection may close immediately after opening\n * without and error. In such cases, we need to handle the close event to reject the promise.\n */\n const closeListener = () => {\n removeListeners();\n reject(new Error('WebSocket connection closed while opening'));\n };\n removeListeners = () => {\n websocket.removeEventListener('open', openListener);\n websocket.removeEventListener('error', errorListener);\n websocket.removeEventListener('close', closeListener);\n };\n websocket.addEventListener('open', openListener);\n websocket.addEventListener('error', errorListener);\n websocket.addEventListener('close', closeListener);\n });\n }\n}\n\nconst POWERSYNC_TRAILING_SLASH_MATCH = /\\/+$/;\nconst POWERSYNC_JS_VERSION = PACKAGE.version;\nconst SYNC_QUEUE_REQUEST_LOW_WATER = 5;\n// Keep alive message is sent every period\nconst KEEP_ALIVE_MS = 20_000;\n// One message of any type must be received in this period.\nconst SOCKET_TIMEOUT_MS = 30_000;\n// One keepalive message must be received in this period.\n// If there is a backlog of messages (for example on slow connections), keepalive messages could be delayed\n// significantly. Therefore this is longer than the socket timeout.\nconst KEEP_ALIVE_LIFETIME_MS = 90_000;\nconst DEFAULT_REMOTE_LOGGER = Logger.get('PowerSyncRemote');\nvar FetchStrategy;\n(function (FetchStrategy) {\n /**\n * Queues multiple sync events before processing, reducing round-trips.\n * This comes at the cost of more processing overhead, which may cause ACK timeouts on older/weaker devices for big enough datasets.\n */\n FetchStrategy[\"Buffered\"] = \"buffered\";\n /**\n * Processes each sync event immediately before requesting the next.\n * This reduces processing overhead and improves real-time responsiveness.\n */\n FetchStrategy[\"Sequential\"] = \"sequential\";\n})(FetchStrategy || (FetchStrategy = {}));\n/**\n * Class wrapper for providing a fetch implementation.\n * The class wrapper is used to distinguish the fetchImplementation\n * option in [AbstractRemoteOptions] from the general fetch method\n * which is typeof \"function\"\n */\nclass FetchImplementationProvider {\n getFetch() {\n throw new Error('Unspecified fetch implementation');\n }\n}\nconst DEFAULT_REMOTE_OPTIONS = {\n socketUrlTransformer: (url) => url.replace(/^https?:\\/\\//, function (match) {\n return match === 'https://' ? 'wss://' : 'ws://';\n }),\n fetchImplementation: new FetchImplementationProvider(),\n fetchOptions: {}\n};\nclass AbstractRemote {\n connector;\n logger;\n credentials = null;\n options;\n constructor(connector, logger = DEFAULT_REMOTE_LOGGER, options) {\n this.connector = connector;\n this.logger = logger;\n this.options = {\n ...DEFAULT_REMOTE_OPTIONS,\n ...(options ?? {})\n };\n }\n /**\n * @returns a fetch implementation (function)\n * which can be called to perform fetch requests\n */\n get fetch() {\n const { fetchImplementation } = this.options;\n return fetchImplementation instanceof FetchImplementationProvider\n ? fetchImplementation.getFetch()\n : fetchImplementation;\n }\n /**\n * Get credentials currently cached, or fetch new credentials if none are\n * available.\n *\n * These credentials may have expired already.\n */\n async getCredentials() {\n if (this.credentials) {\n return this.credentials;\n }\n return this.prefetchCredentials();\n }\n /**\n * Fetch a new set of credentials and cache it.\n *\n * Until this call succeeds, `getCredentials` will still return the\n * old credentials.\n *\n * This may be called before the current credentials have expired.\n */\n async prefetchCredentials() {\n this.credentials = await this.fetchCredentials();\n return this.credentials;\n }\n /**\n * Get credentials for PowerSync.\n *\n * This should always fetch a fresh set of credentials - don't use cached\n * values.\n */\n async fetchCredentials() {\n const credentials = await this.connector.fetchCredentials();\n if (credentials?.endpoint.match(POWERSYNC_TRAILING_SLASH_MATCH)) {\n throw new Error(`A trailing forward slash \"/\" was found in the fetchCredentials endpoint: \"${credentials.endpoint}\". Remove the trailing forward slash \"/\" to fix this error.`);\n }\n return credentials;\n }\n /***\n * Immediately invalidate credentials.\n *\n * This may be called when the current credentials have expired.\n */\n invalidateCredentials() {\n this.credentials = null;\n this.connector.invalidateCredentials?.();\n }\n getUserAgent() {\n return `powersync-js/${POWERSYNC_JS_VERSION}`;\n }\n async buildRequest(path) {\n const credentials = await this.getCredentials();\n if (credentials != null && (credentials.endpoint == null || credentials.endpoint == '')) {\n throw new Error('PowerSync endpoint not configured');\n }\n else if (credentials?.token == null || credentials?.token == '') {\n const error = new Error(`Not signed in`);\n error.status = 401;\n throw error;\n }\n const userAgent = this.getUserAgent();\n return {\n url: credentials.endpoint + path,\n headers: {\n 'content-type': 'application/json',\n Authorization: `Token ${credentials.token}`,\n 'x-user-agent': userAgent\n }\n };\n }\n async post(path, data, headers = {}) {\n const request = await this.buildRequest(path);\n const res = await this.fetch(request.url, {\n method: 'POST',\n headers: {\n ...headers,\n ...request.headers\n },\n body: JSON.stringify(data)\n });\n if (res.status === 401) {\n this.invalidateCredentials();\n }\n if (!res.ok) {\n throw new Error(`Received ${res.status} - ${res.statusText} when posting to ${path}: ${await res.text()}}`);\n }\n return res.json();\n }\n async get(path, headers) {\n const request = await this.buildRequest(path);\n const res = await this.fetch(request.url, {\n method: 'GET',\n headers: {\n ...headers,\n ...request.headers\n }\n });\n if (res.status === 401) {\n this.invalidateCredentials();\n }\n if (!res.ok) {\n throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);\n }\n return res.json();\n }\n /**\n * @returns A text decoder decoding UTF-8. This is a method to allow patching it for Hermes which doesn't support the\n * builtin, without forcing us to bundle a polyfill with `@powersync/common`.\n */\n createTextDecoder() {\n return new TextDecoder();\n }\n createSocket(url) {\n return new WebSocket(url);\n }\n /**\n * Returns a data stream of sync line data.\n *\n * @param map Maps received payload frames to the typed event value.\n * @param bson A BSON encoder and decoder. When set, the data stream will be requested with a BSON payload\n * (required for compatibility with older sync services).\n */\n async socketStreamRaw(options, map, bson) {\n const { path, fetchStrategy = FetchStrategy.Buffered } = options;\n const mimeType = bson == null ? 'application/json' : 'application/bson';\n function toBuffer(js) {\n let contents;\n if (bson != null) {\n contents = bson.serialize(js);\n }\n else {\n contents = JSON.stringify(js);\n }\n return bufferExports.Buffer.from(contents);\n }\n const syncQueueRequestSize = fetchStrategy == FetchStrategy.Buffered ? 10 : 1;\n const request = await this.buildRequest(path);\n // Add the user agent in the setup payload - we can't set custom\n // headers with websockets on web. The browser userAgent is however added\n // automatically as a header.\n const userAgent = this.getUserAgent();\n const stream = new DataStream({\n logger: this.logger,\n pressure: {\n lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER\n },\n mapLine: map\n });\n // Handle upstream abort\n if (options.abortSignal?.aborted) {\n throw new AbortOperation('Connection request aborted');\n }\n else {\n options.abortSignal?.addEventListener('abort', () => {\n stream.close();\n }, { once: true });\n }\n let keepAliveTimeout;\n const resetTimeout = () => {\n clearTimeout(keepAliveTimeout);\n keepAliveTimeout = setTimeout(() => {\n this.logger.error(`No data received on WebSocket in ${SOCKET_TIMEOUT_MS}ms, closing connection.`);\n stream.close();\n }, SOCKET_TIMEOUT_MS);\n };\n resetTimeout();\n // Typescript complains about this being `never` if it's not assigned here.\n // This is assigned in `wsCreator`.\n let disposeSocketConnectionTimeout = () => { };\n const url = this.options.socketUrlTransformer(request.url);\n const connector = new distExports.RSocketConnector({\n transport: new WebsocketClientTransport({\n url,\n wsCreator: (url) => {\n const socket = this.createSocket(url);\n disposeSocketConnectionTimeout = stream.registerListener({\n closed: () => {\n // Allow closing the underlying WebSocket if the stream was closed before the\n // RSocket connect completed. This should effectively abort the request.\n socket.close();\n }\n });\n socket.addEventListener('message', (event) => {\n resetTimeout();\n });\n return socket;\n }\n }),\n setup: {\n keepAlive: KEEP_ALIVE_MS,\n lifetime: KEEP_ALIVE_LIFETIME_MS,\n dataMimeType: mimeType,\n metadataMimeType: mimeType,\n payload: {\n data: null,\n metadata: toBuffer({\n token: request.headers.Authorization,\n user_agent: userAgent\n })\n }\n }\n });\n let rsocket;\n try {\n rsocket = await connector.connect();\n // The connection is established, we no longer need to monitor the initial timeout\n disposeSocketConnectionTimeout();\n }\n catch (ex) {\n this.logger.error(`Failed to connect WebSocket`, ex);\n clearTimeout(keepAliveTimeout);\n if (!stream.closed) {\n await stream.close();\n }\n throw ex;\n }\n resetTimeout();\n let socketIsClosed = false;\n const closeSocket = () => {\n clearTimeout(keepAliveTimeout);\n if (socketIsClosed) {\n return;\n }\n socketIsClosed = true;\n rsocket.close();\n };\n // Helps to prevent double close scenarios\n rsocket.onClose(() => (socketIsClosed = true));\n // We initially request this amount and expect these to arrive eventually\n let pendingEventsCount = syncQueueRequestSize;\n const disposeClosedListener = stream.registerListener({\n closed: () => {\n closeSocket();\n disposeClosedListener();\n }\n });\n const socket = await new Promise((resolve, reject) => {\n let connectionEstablished = false;\n const res = rsocket.requestStream({\n data: toBuffer(options.data),\n metadata: toBuffer({\n path\n })\n }, syncQueueRequestSize, // The initial N amount\n {\n onError: (e) => {\n if (e.message.includes('PSYNC_')) {\n if (e.message.includes('PSYNC_S21')) {\n this.invalidateCredentials();\n }\n }\n else {\n // Possible that connection is with an older service, always invalidate to be safe\n if (e.message !== 'Closed. ') {\n this.invalidateCredentials();\n }\n }\n // Don't log closed as an error\n if (e.message !== 'Closed. ') {\n this.logger.error(e);\n }\n // RSocket will close the RSocket stream automatically\n // Close the downstream stream as well - this will close the RSocket connection and WebSocket\n stream.close();\n // Handles cases where the connection failed e.g. auth error or connection error\n if (!connectionEstablished) {\n reject(e);\n }\n },\n onNext: (payload) => {\n // The connection is active\n if (!connectionEstablished) {\n connectionEstablished = true;\n resolve(res);\n }\n const { data } = payload;\n // Less events are now pending\n pendingEventsCount--;\n if (!data) {\n return;\n }\n stream.enqueueData(data);\n },\n onComplete: () => {\n stream.close();\n },\n onExtension: () => { }\n });\n });\n const l = stream.registerListener({\n lowWater: async () => {\n // Request to fill up the queue\n const required = syncQueueRequestSize - pendingEventsCount;\n if (required > 0) {\n socket.request(syncQueueRequestSize - pendingEventsCount);\n pendingEventsCount = syncQueueRequestSize;\n }\n },\n closed: () => {\n l();\n }\n });\n return stream;\n }\n /**\n * Connects to the sync/stream http endpoint, mapping and emitting each received string line.\n */\n async postStreamRaw(options, mapLine) {\n const { data, path, headers, abortSignal } = options;\n const request = await this.buildRequest(path);\n /**\n * This abort controller will abort pending fetch requests.\n * If the request has resolved, it will be used to close the readable stream.\n * Which will cancel the network request.\n *\n * This nested controller is required since:\n * Aborting the active fetch request while it is being consumed seems to throw\n * an unhandled exception on the window level.\n */\n if (abortSignal?.aborted) {\n throw new AbortOperation('Abort request received before making postStreamRaw request');\n }\n const controller = new AbortController();\n let requestResolved = false;\n abortSignal?.addEventListener('abort', () => {\n if (!requestResolved) {\n // Only abort via the abort controller if the request has not resolved yet\n controller.abort(abortSignal.reason ??\n new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.'));\n }\n });\n const res = await this.fetch(request.url, {\n method: 'POST',\n headers: { ...headers, ...request.headers },\n body: JSON.stringify(data),\n signal: controller.signal,\n cache: 'no-store',\n ...(this.options.fetchOptions ?? {}),\n ...options.fetchOptions\n }).catch((ex) => {\n if (ex.name == 'AbortError') {\n throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);\n }\n throw ex;\n });\n if (!res) {\n throw new Error('Fetch request was aborted');\n }\n requestResolved = true;\n if (!res.ok || !res.body) {\n const text = await res.text();\n this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);\n const error = new Error(`HTTP ${res.statusText}: ${text}`);\n error.status = res.status;\n throw error;\n }\n // Create a new stream splitting the response at line endings while also handling cancellations\n // by closing the reader.\n const reader = res.body.getReader();\n let readerReleased = false;\n // This will close the network request and read stream\n const closeReader = async () => {\n try {\n readerReleased = true;\n await reader.cancel();\n }\n catch (ex) {\n // an error will throw if the reader hasn't been used yet\n }\n reader.releaseLock();\n };\n const stream = new DataStream({\n logger: this.logger,\n mapLine: mapLine,\n pressure: {\n highWaterMark: 20,\n lowWaterMark: 10\n }\n });\n abortSignal?.addEventListener('abort', () => {\n closeReader();\n stream.close();\n });\n const decoder = this.createTextDecoder();\n let buffer = '';\n const consumeStream = async () => {\n while (!stream.closed && !abortSignal?.aborted && !readerReleased) {\n const { done, value } = await reader.read();\n if (done) {\n const remaining = buffer.trim();\n if (remaining.length != 0) {\n stream.enqueueData(remaining);\n }\n stream.close();\n await closeReader();\n return;\n }\n const data = decoder.decode(value, { stream: true });\n buffer += data;\n const lines = buffer.split('\\n');\n for (var i = 0; i < lines.length - 1; i++) {\n var l = lines[i].trim();\n if (l.length > 0) {\n stream.enqueueData(l);\n }\n }\n buffer = lines[lines.length - 1];\n // Implement backpressure by waiting for the low water mark to be reached\n if (stream.dataQueue.length > stream.highWatermark) {\n await new Promise((resolve) => {\n const dispose = stream.registerListener({\n lowWater: async () => {\n resolve();\n dispose();\n },\n closed: () => {\n resolve();\n dispose();\n }\n });\n });\n }\n }\n };\n consumeStream().catch(ex => this.logger.error('Error consuming stream', ex));\n const l = stream.registerListener({\n closed: () => {\n closeReader();\n l?.();\n }\n });\n return stream;\n }\n}\n\nfunction priorityToJs(status) {\n return {\n priority: status.priority,\n hasSynced: status.has_synced ?? undefined,\n lastSyncedAt: status.last_synced_at != null ? new Date(status.last_synced_at * 1000) : undefined\n };\n}\nfunction coreStatusToJs(status) {\n const coreCompleteSync = status.priority_status.find((s) => s.priority == FULL_SYNC_PRIORITY);\n const completeSync = coreCompleteSync != null ? priorityToJs(coreCompleteSync) : null;\n return {\n connected: status.connected,\n connecting: status.connecting,\n dataFlow: {\n // We expose downloading as a boolean field, the core extension reports download information as a nullable\n // download status. When that status is non-null, a download is in progress.\n downloading: status.downloading != null,\n downloadProgress: status.downloading?.buckets,\n internalStreamSubscriptions: status.streams\n },\n lastSyncedAt: completeSync?.lastSyncedAt,\n hasSynced: completeSync?.hasSynced,\n priorityStatusEntries: status.priority_status.map(priorityToJs)\n };\n}\n\nfunction isStreamingSyncData(line) {\n return line.data != null;\n}\nfunction isStreamingKeepalive(line) {\n return line.token_expires_in != null;\n}\nfunction isStreamingSyncCheckpoint(line) {\n return line.checkpoint != null;\n}\nfunction isStreamingSyncCheckpointComplete(line) {\n return line.checkpoint_complete != null;\n}\nfunction isStreamingSyncCheckpointPartiallyComplete(line) {\n return line.partial_checkpoint_complete != null;\n}\nfunction isStreamingSyncCheckpointDiff(line) {\n return line.checkpoint_diff != null;\n}\nfunction isContinueCheckpointRequest(request) {\n return (Array.isArray(request.buckets) &&\n typeof request.checkpoint_token == 'string');\n}\nfunction isSyncNewCheckpointRequest(request) {\n return typeof request.request_checkpoint == 'object';\n}\n\nvar LockType;\n(function (LockType) {\n LockType[\"CRUD\"] = \"crud\";\n LockType[\"SYNC\"] = \"sync\";\n})(LockType || (LockType = {}));\nvar SyncStreamConnectionMethod;\n(function (SyncStreamConnectionMethod) {\n SyncStreamConnectionMethod[\"HTTP\"] = \"http\";\n SyncStreamConnectionMethod[\"WEB_SOCKET\"] = \"web-socket\";\n})(SyncStreamConnectionMethod || (SyncStreamConnectionMethod = {}));\nvar SyncClientImplementation;\n(function (SyncClientImplementation) {\n /**\n * Decodes and handles sync lines received from the sync service in JavaScript.\n *\n * This is the default option.\n *\n * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with\n * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future\n * version of the PowerSync SDK.\n */\n SyncClientImplementation[\"JAVASCRIPT\"] = \"js\";\n /**\n * This implementation offloads the sync line decoding and handling into the PowerSync\n * core extension.\n *\n * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the\n * recommended client implementation for all apps.\n *\n * ## Compatibility warning\n *\n * The Rust sync client stores sync data in a format that is slightly different than the one used\n * by the old {@link JAVASCRIPT} implementation. When adopting the {@link RUST} client on existing\n * databases, the PowerSync SDK will migrate the format automatically.\n * Further, the {@link JAVASCRIPT} client in recent versions of the PowerSync JS SDK (starting from\n * the version introducing {@link RUST} as an option) also supports the new format, so you can switch\n * back to {@link JAVASCRIPT} later.\n *\n * __However__: Upgrading the SDK version, then adopting {@link RUST} as a sync client and later\n * downgrading the SDK to an older version (necessarily using the JavaScript-based implementation then)\n * can lead to sync issues.\n */\n SyncClientImplementation[\"RUST\"] = \"rust\";\n})(SyncClientImplementation || (SyncClientImplementation = {}));\n/**\n * The default {@link SyncClientImplementation} to use, {@link SyncClientImplementation.RUST}.\n */\nconst DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.RUST;\nconst DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;\nconst DEFAULT_RETRY_DELAY_MS = 5000;\nconst DEFAULT_STREAMING_SYNC_OPTIONS = {\n retryDelayMs: DEFAULT_RETRY_DELAY_MS,\n crudUploadThrottleMs: DEFAULT_CRUD_UPLOAD_THROTTLE_MS\n};\nconst DEFAULT_STREAM_CONNECTION_OPTIONS = {\n appMetadata: {},\n connectionMethod: SyncStreamConnectionMethod.WEB_SOCKET,\n clientImplementation: DEFAULT_SYNC_CLIENT_IMPLEMENTATION,\n fetchStrategy: FetchStrategy.Buffered,\n params: {},\n serializedSchema: undefined,\n includeDefaultStreams: true\n};\n// The priority we assume when we receive checkpoint lines where no priority is set.\n// This is the default priority used by the sync service, but can be set to an arbitrary\n// value since sync services without priorities also won't send partial sync completion\n// messages.\nconst FALLBACK_PRIORITY = 3;\nclass AbstractStreamingSyncImplementation extends BaseObserver {\n _lastSyncedAt;\n options;\n abortController;\n // In rare cases, mostly for tests, uploads can be triggered without being properly connected.\n // This allows ensuring that all upload processes can be aborted.\n uploadAbortController;\n crudUpdateListener;\n streamingSyncPromise;\n logger;\n activeStreams;\n isUploadingCrud = false;\n notifyCompletedUploads;\n handleActiveStreamsChange;\n syncStatus;\n triggerCrudUpload;\n constructor(options) {\n super();\n this.options = options;\n this.activeStreams = options.subscriptions;\n this.logger = options.logger ?? Logger.get('PowerSyncStream');\n this.syncStatus = new SyncStatus({\n connected: false,\n connecting: false,\n lastSyncedAt: undefined,\n dataFlow: {\n uploading: false,\n downloading: false\n }\n });\n this.abortController = null;\n this.triggerCrudUpload = throttleLeadingTrailing(() => {\n if (!this.syncStatus.connected || this.isUploadingCrud) {\n return;\n }\n this.isUploadingCrud = true;\n this._uploadAllCrud().finally(() => {\n this.notifyCompletedUploads?.();\n this.isUploadingCrud = false;\n });\n }, this.options.crudUploadThrottleMs);\n }\n async waitForReady() { }\n waitForStatus(status) {\n return this.waitUntilStatusMatches((currentStatus) => {\n /**\n * Match only the partial status options provided in the\n * matching status\n */\n const matchPartialObject = (compA, compB) => {\n return Object.entries(compA).every(([key, value]) => {\n const comparisonBValue = compB[key];\n if (typeof value == 'object' && typeof comparisonBValue == 'object') {\n return matchPartialObject(value, comparisonBValue);\n }\n return value == comparisonBValue;\n });\n };\n return matchPartialObject(status, currentStatus);\n });\n }\n waitUntilStatusMatches(predicate) {\n return new Promise((resolve) => {\n if (predicate(this.syncStatus)) {\n resolve();\n return;\n }\n const l = this.registerListener({\n statusChanged: (updatedStatus) => {\n if (predicate(updatedStatus)) {\n resolve();\n l?.();\n }\n }\n });\n });\n }\n get lastSyncedAt() {\n const lastSynced = this.syncStatus.lastSyncedAt;\n return lastSynced && new Date(lastSynced);\n }\n get isConnected() {\n return this.syncStatus.connected;\n }\n async dispose() {\n super.dispose();\n this.crudUpdateListener?.();\n this.crudUpdateListener = undefined;\n this.uploadAbortController?.abort();\n }\n async hasCompletedSync() {\n return this.options.adapter.hasCompletedSync();\n }\n async getWriteCheckpoint() {\n const clientId = await this.options.adapter.getClientId();\n let path = `/write-checkpoint2.json?client_id=${clientId}`;\n const response = await this.options.remote.get(path);\n const checkpoint = response['data']['write_checkpoint'];\n this.logger.debug(`Created write checkpoint: ${checkpoint}`);\n return checkpoint;\n }\n async _uploadAllCrud() {\n return this.obtainLock({\n type: LockType.CRUD,\n callback: async () => {\n /**\n * Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.\n */\n let checkedCrudItem;\n const controller = new AbortController();\n this.uploadAbortController = controller;\n this.abortController?.signal.addEventListener('abort', () => {\n controller.abort();\n }, { once: true });\n while (!controller.signal.aborted) {\n try {\n /**\n * This is the first item in the FIFO CRUD queue.\n */\n const nextCrudItem = await this.options.adapter.nextCrudItem();\n if (nextCrudItem) {\n this.updateSyncStatus({\n dataFlow: {\n uploading: true\n }\n });\n if (nextCrudItem.clientId == checkedCrudItem?.clientId) {\n // This will force a higher log level than exceptions which are caught here.\n this.logger.warn(`Potentially previously uploaded CRUD entries are still present in the upload queue.\nMake sure to handle uploads and complete CRUD transactions or batches by calling and awaiting their [.complete()] method.\nThe next upload iteration will be delayed.`);\n throw new Error('Delaying due to previously encountered CRUD item.');\n }\n checkedCrudItem = nextCrudItem;\n await this.options.uploadCrud();\n this.updateSyncStatus({\n dataFlow: {\n uploadError: undefined\n }\n });\n }\n else {\n // Uploading is completed\n const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());\n if (neededUpdate == false && checkedCrudItem != null) {\n // Only log this if there was something to upload\n this.logger.debug('Upload complete, no write checkpoint needed.');\n }\n break;\n }\n }\n catch (ex) {\n checkedCrudItem = undefined;\n this.updateSyncStatus({\n dataFlow: {\n uploading: false,\n uploadError: ex\n }\n });\n await this.delayRetry(controller.signal);\n if (!this.isConnected) {\n // Exit the upload loop if the sync stream is no longer connected\n break;\n }\n this.logger.debug(`Caught exception when uploading. Upload will retry after a delay. Exception: ${ex.message}`);\n }\n finally {\n this.updateSyncStatus({\n dataFlow: {\n uploading: false\n }\n });\n }\n }\n this.uploadAbortController = null;\n }\n });\n }\n async connect(options) {\n if (this.abortController) {\n await this.disconnect();\n }\n const controller = new AbortController();\n this.abortController = controller;\n this.streamingSyncPromise = this.streamingSync(this.abortController.signal, options);\n // Return a promise that resolves when the connection status is updated to indicate that we're connected.\n return new Promise((resolve) => {\n const disposer = this.registerListener({\n statusChanged: (status) => {\n if (status.dataFlowStatus.downloadError != null) {\n this.logger.warn('Initial connect attempt did not successfully connect to server');\n }\n else if (status.connecting) {\n // Still connecting.\n return;\n }\n disposer();\n resolve();\n }\n });\n });\n }\n async disconnect() {\n if (!this.abortController) {\n return;\n }\n // This might be called multiple times\n if (!this.abortController.signal.aborted) {\n this.abortController.abort(new AbortOperation('Disconnect has been requested'));\n }\n // Await any pending operations before completing the disconnect operation\n try {\n await this.streamingSyncPromise;\n }\n catch (ex) {\n // The operation might have failed, all we care about is if it has completed\n this.logger.warn(ex);\n }\n this.streamingSyncPromise = undefined;\n this.abortController = null;\n this.updateSyncStatus({ connected: false, connecting: false });\n }\n /**\n * @deprecated use [connect instead]\n */\n async streamingSync(signal, options) {\n if (!signal) {\n this.abortController = new AbortController();\n signal = this.abortController.signal;\n }\n /**\n * Listen for CRUD updates and trigger upstream uploads\n */\n this.crudUpdateListener = this.options.adapter.registerListener({\n crudUpdate: () => this.triggerCrudUpload()\n });\n /**\n * Create a new abort controller which aborts items downstream.\n * This is needed to close any previous connections on exception.\n */\n let nestedAbortController = new AbortController();\n signal.addEventListener('abort', () => {\n /**\n * A request for disconnect was received upstream. Relay the request\n * to the nested abort controller.\n */\n nestedAbortController.abort(signal?.reason ?? new AbortOperation('Received command to disconnect from upstream'));\n this.crudUpdateListener?.();\n this.crudUpdateListener = undefined;\n this.updateSyncStatus({\n connected: false,\n connecting: false,\n dataFlow: {\n downloading: false,\n downloadProgress: null\n }\n });\n });\n /**\n * This loops runs until [retry] is false or the abort signal is set to aborted.\n * Aborting the nestedAbortController will:\n * - Abort any pending fetch requests\n * - Close any sync stream ReadableStreams (which will also close any established network requests)\n */\n while (true) {\n this.updateSyncStatus({ connecting: true });\n let shouldDelayRetry = true;\n let result = null;\n try {\n if (signal?.aborted) {\n break;\n }\n result = await this.streamingSyncIteration(nestedAbortController.signal, options);\n // Continue immediately, streamingSyncIteration will wait before completing if necessary.\n }\n catch (ex) {\n /**\n * Either:\n * - A network request failed with a failed connection or not OKAY response code.\n * - There was a sync processing error.\n * - The connection was aborted.\n * This loop will retry after a delay if the connection was not aborted.\n * The nested abort controller will cleanup any open network requests and streams.\n * The WebRemote should only abort pending fetch requests or close active Readable streams.\n */\n if (ex instanceof AbortOperation) {\n this.logger.warn(ex);\n shouldDelayRetry = false;\n // A disconnect was requested, we should not delay since there is no explicit retry\n }\n else {\n this.logger.error(ex);\n }\n this.updateSyncStatus({\n dataFlow: {\n downloadError: ex\n }\n });\n }\n finally {\n this.notifyCompletedUploads = undefined;\n if (!signal.aborted) {\n nestedAbortController.abort(new AbortOperation('Closing sync stream network requests before retry.'));\n nestedAbortController = new AbortController();\n }\n if (result?.immediateRestart != true) {\n this.updateSyncStatus({\n connected: false,\n connecting: true // May be unnecessary\n });\n // On error, wait a little before retrying\n if (shouldDelayRetry) {\n await this.delayRetry(nestedAbortController.signal);\n }\n }\n }\n }\n // Mark as disconnected if here\n this.updateSyncStatus({ connected: false, connecting: false });\n }\n async collectLocalBucketState() {\n const bucketEntries = await this.options.adapter.getBucketStates();\n const req = bucketEntries.map((entry) => ({\n name: entry.bucket,\n after: entry.op_id\n }));\n const localDescriptions = new Map();\n for (const entry of bucketEntries) {\n localDescriptions.set(entry.bucket, null);\n }\n return [req, localDescriptions];\n }\n /**\n * Older versions of the JS SDK used to encode subkeys as JSON in {@link OplogEntry.toJSON}.\n * Because subkeys are always strings, this leads to quotes being added around them in `ps_oplog`.\n * While this is not a problem as long as it's done consistently, it causes issues when a database\n * created by the JS SDK is used with other SDKs, or (more likely) when the new Rust sync client\n * is enabled.\n *\n * So, we add a migration from the old key format (with quotes) to the new one (no quotes). The\n * migration is only triggered when necessary (for now). The function returns whether the new format\n * should be used, so that the JS SDK is able to write to updated databases.\n *\n * @param requireFixedKeyFormat Whether we require the new format or also support the old one.\n * The Rust client requires the new subkey format.\n * @returns Whether the database is now using the new, fixed subkey format.\n */\n async requireKeyFormat(requireFixedKeyFormat) {\n const hasMigrated = await this.options.adapter.hasMigratedSubkeys();\n if (requireFixedKeyFormat && !hasMigrated) {\n await this.options.adapter.migrateToFixedSubkeys();\n return true;\n }\n else {\n return hasMigrated;\n }\n }\n streamingSyncIteration(signal, options) {\n return this.obtainLock({\n type: LockType.SYNC,\n signal,\n callback: async () => {\n const resolvedOptions = {\n ...DEFAULT_STREAM_CONNECTION_OPTIONS,\n ...(options ?? {})\n };\n // Validate app metadata\n const invalidMetadata = Object.entries(resolvedOptions.appMetadata).filter(([_, value]) => typeof value != 'string');\n if (invalidMetadata.length > 0) {\n throw new Error(`Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`);\n }\n const clientImplementation = resolvedOptions.clientImplementation;\n this.updateSyncStatus({ clientImplementation });\n if (clientImplementation == SyncClientImplementation.JAVASCRIPT) {\n await this.legacyStreamingSyncIteration(signal, resolvedOptions);\n return null;\n }\n else {\n await this.requireKeyFormat(true);\n return await this.rustSyncIteration(signal, resolvedOptions);\n }\n }\n });\n }\n async legacyStreamingSyncIteration(signal, resolvedOptions) {\n const rawTables = resolvedOptions.serializedSchema?.raw_tables;\n if (rawTables != null && rawTables.length) {\n this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');\n }\n if (this.activeStreams.length) {\n this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');\n }\n this.logger.debug('Streaming sync iteration started');\n this.options.adapter.startSession();\n let [req, bucketMap] = await this.collectLocalBucketState();\n let targetCheckpoint = null;\n // A checkpoint that has been validated but not applied (e.g. due to pending local writes)\n let pendingValidatedCheckpoint = null;\n const clientId = await this.options.adapter.getClientId();\n const usingFixedKeyFormat = await this.requireKeyFormat(false);\n this.logger.debug('Requesting stream from server');\n const syncOptions = {\n path: '/sync/stream',\n abortSignal: signal,\n data: {\n buckets: req,\n include_checksum: true,\n raw_data: true,\n parameters: resolvedOptions.params,\n app_metadata: resolvedOptions.appMetadata,\n client_id: clientId\n }\n };\n let stream;\n if (resolvedOptions?.connectionMethod == SyncStreamConnectionMethod.HTTP) {\n stream = await this.options.remote.postStreamRaw(syncOptions, (line) => {\n if (typeof line == 'string') {\n return JSON.parse(line);\n }\n else {\n // Directly enqueued by us\n return line;\n }\n });\n }\n else {\n const bson = await this.options.remote.getBSON();\n stream = await this.options.remote.socketStreamRaw({\n ...syncOptions,\n ...{ fetchStrategy: resolvedOptions.fetchStrategy }\n }, (payload) => {\n if (payload instanceof Uint8Array) {\n return bson.deserialize(payload);\n }\n else {\n // Directly enqueued by us\n return payload;\n }\n }, bson);\n }\n this.logger.debug('Stream established. Processing events');\n this.notifyCompletedUploads = () => {\n if (!stream.closed) {\n stream.enqueueData({ crud_upload_completed: null });\n }\n };\n while (!stream.closed) {\n const line = await stream.read();\n if (!line) {\n // The stream has closed while waiting\n return;\n }\n if ('crud_upload_completed' in line) {\n if (pendingValidatedCheckpoint != null) {\n const { applied, endIteration } = await this.applyCheckpoint(pendingValidatedCheckpoint);\n if (applied) {\n pendingValidatedCheckpoint = null;\n }\n else if (endIteration) {\n break;\n }\n }\n continue;\n }\n // A connection is active and messages are being received\n if (!this.syncStatus.connected) {\n // There is a connection now\n Promise.resolve().then(() => this.triggerCrudUpload());\n this.updateSyncStatus({\n connected: true\n });\n }\n if (isStreamingSyncCheckpoint(line)) {\n targetCheckpoint = line.checkpoint;\n // New checkpoint - existing validated checkpoint is no longer valid\n pendingValidatedCheckpoint = null;\n const bucketsToDelete = new Set(bucketMap.keys());\n const newBuckets = new Map();\n for (const checksum of line.checkpoint.buckets) {\n newBuckets.set(checksum.bucket, {\n name: checksum.bucket,\n priority: checksum.priority ?? FALLBACK_PRIORITY\n });\n bucketsToDelete.delete(checksum.bucket);\n }\n if (bucketsToDelete.size > 0) {\n this.logger.debug('Removing buckets', [...bucketsToDelete]);\n }\n bucketMap = newBuckets;\n await this.options.adapter.removeBuckets([...bucketsToDelete]);\n await this.options.adapter.setTargetCheckpoint(targetCheckpoint);\n await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);\n }\n else if (isStreamingSyncCheckpointComplete(line)) {\n const result = await this.applyCheckpoint(targetCheckpoint);\n if (result.endIteration) {\n return;\n }\n else if (!result.applied) {\n // \"Could not apply checkpoint due to local data\". We need to retry after\n // finishing uploads.\n pendingValidatedCheckpoint = targetCheckpoint;\n }\n else {\n // Nothing to retry later. This would likely already be null from the last\n // checksum or checksum_diff operation, but we make sure.\n pendingValidatedCheckpoint = null;\n }\n }\n else if (isStreamingSyncCheckpointPartiallyComplete(line)) {\n const priority = line.partial_checkpoint_complete.priority;\n this.logger.debug('Partial checkpoint complete', priority);\n const result = await this.options.adapter.syncLocalDatabase(targetCheckpoint, priority);\n if (!result.checkpointValid) {\n // This means checksums failed. Start again with a new checkpoint.\n // TODO: better back-off\n await new Promise((resolve) => setTimeout(resolve, 50));\n return;\n }\n else if (!result.ready) ;\n else {\n // We'll keep on downloading, but can report that this priority is synced now.\n this.logger.debug('partial checkpoint validation succeeded');\n // All states with a higher priority can be deleted since this partial sync includes them.\n const priorityStates = this.syncStatus.priorityStatusEntries.filter((s) => s.priority <= priority);\n priorityStates.push({\n priority,\n lastSyncedAt: new Date(),\n hasSynced: true\n });\n this.updateSyncStatus({\n connected: true,\n priorityStatusEntries: priorityStates\n });\n }\n }\n else if (isStreamingSyncCheckpointDiff(line)) {\n // TODO: It may be faster to just keep track of the diff, instead of the entire checkpoint\n if (targetCheckpoint == null) {\n throw new Error('Checkpoint diff without previous checkpoint');\n }\n // New checkpoint - existing validated checkpoint is no longer valid\n pendingValidatedCheckpoint = null;\n const diff = line.checkpoint_diff;\n const newBuckets = new Map();\n for (const checksum of targetCheckpoint.buckets) {\n newBuckets.set(checksum.bucket, checksum);\n }\n for (const checksum of diff.updated_buckets) {\n newBuckets.set(checksum.bucket, checksum);\n }\n for (const bucket of diff.removed_buckets) {\n newBuckets.delete(bucket);\n }\n const newCheckpoint = {\n last_op_id: diff.last_op_id,\n buckets: [...newBuckets.values()],\n write_checkpoint: diff.write_checkpoint\n };\n targetCheckpoint = newCheckpoint;\n await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);\n bucketMap = new Map();\n newBuckets.forEach((checksum, name) => bucketMap.set(name, {\n name: checksum.bucket,\n priority: checksum.priority ?? FALLBACK_PRIORITY\n }));\n const bucketsToDelete = diff.removed_buckets;\n if (bucketsToDelete.length > 0) {\n this.logger.debug('Remove buckets', bucketsToDelete);\n }\n await this.options.adapter.removeBuckets(bucketsToDelete);\n await this.options.adapter.setTargetCheckpoint(targetCheckpoint);\n }\n else if (isStreamingSyncData(line)) {\n const { data } = line;\n const previousProgress = this.syncStatus.dataFlowStatus.downloadProgress;\n let updatedProgress = null;\n if (previousProgress) {\n updatedProgress = { ...previousProgress };\n const progressForBucket = updatedProgress[data.bucket];\n if (progressForBucket) {\n updatedProgress[data.bucket] = {\n ...progressForBucket,\n since_last: progressForBucket.since_last + data.data.length\n };\n }\n }\n this.updateSyncStatus({\n dataFlow: {\n downloading: true,\n downloadProgress: updatedProgress\n }\n });\n await this.options.adapter.saveSyncData({ buckets: [SyncDataBucket.fromRow(data)] }, usingFixedKeyFormat);\n }\n else if (isStreamingKeepalive(line)) {\n const remaining_seconds = line.token_expires_in;\n if (remaining_seconds == 0) {\n // Connection would be closed automatically right after this\n this.logger.debug('Token expiring; reconnect');\n /**\n * For a rare case where the backend connector does not update the token\n * (uses the same one), this should have some delay.\n */\n await this.delayRetry();\n return;\n }\n else if (remaining_seconds < 30) {\n this.logger.debug('Token will expire soon; reconnect');\n // Pre-emptively refresh the token\n this.options.remote.invalidateCredentials();\n return;\n }\n this.triggerCrudUpload();\n }\n else {\n this.logger.debug('Received unknown sync line', line);\n }\n }\n this.logger.debug('Stream input empty');\n // Connection closed. Likely due to auth issue.\n return;\n }\n async rustSyncIteration(signal, resolvedOptions) {\n const syncImplementation = this;\n const adapter = this.options.adapter;\n const remote = this.options.remote;\n let receivingLines = null;\n let hadSyncLine = false;\n let hideDisconnectOnRestart = false;\n if (signal.aborted) {\n throw new AbortOperation('Connection request has been aborted');\n }\n const abortController = new AbortController();\n signal.addEventListener('abort', () => abortController.abort());\n // Pending sync lines received from the service, as well as local events that trigger a powersync_control\n // invocation (local events include refreshed tokens and completed uploads).\n // This is a single data stream so that we can handle all control calls from a single place.\n let controlInvocations = null;\n async function connect(instr) {\n const syncOptions = {\n path: '/sync/stream',\n abortSignal: abortController.signal,\n data: instr.request\n };\n if (resolvedOptions.connectionMethod == SyncStreamConnectionMethod.HTTP) {\n controlInvocations = await remote.postStreamRaw(syncOptions, (line) => {\n if (typeof line == 'string') {\n return {\n command: PowerSyncControlCommand.PROCESS_TEXT_LINE,\n payload: line\n };\n }\n else {\n // Directly enqueued by us\n return line;\n }\n });\n }\n else {\n controlInvocations = await remote.socketStreamRaw({\n ...syncOptions,\n fetchStrategy: resolvedOptions.fetchStrategy\n }, (payload) => {\n if (payload instanceof Uint8Array) {\n return {\n command: PowerSyncControlCommand.PROCESS_BSON_LINE,\n payload: payload\n };\n }\n else {\n // Directly enqueued by us\n return payload;\n }\n });\n }\n // The rust client will set connected: true after the first sync line because that's when it gets invoked, but\n // we're already connected here and can report that.\n syncImplementation.updateSyncStatus({ connected: true });\n try {\n while (!controlInvocations.closed) {\n const line = await controlInvocations.read();\n if (line == null) {\n return;\n }\n await control(line.command, line.payload);\n if (!hadSyncLine) {\n syncImplementation.triggerCrudUpload();\n hadSyncLine = true;\n }\n }\n }\n finally {\n const activeInstructions = controlInvocations;\n // We concurrently add events to the active data stream when e.g. a CRUD upload is completed or a token is\n // refreshed. That would throw after closing (and we can't handle those events either way), so set this back\n // to null.\n controlInvocations = null;\n await activeInstructions.close();\n }\n }\n async function stop() {\n await control(PowerSyncControlCommand.STOP);\n }\n async function control(op, payload) {\n const rawResponse = await adapter.control(op, payload ?? null);\n const logger = syncImplementation.logger;\n logger.trace('powersync_control', op, payload == null || typeof payload == 'string' ? payload : '<bytes>', rawResponse);\n await handleInstructions(JSON.parse(rawResponse));\n }\n async function handleInstruction(instruction) {\n if ('LogLine' in instruction) {\n switch (instruction.LogLine.severity) {\n case 'DEBUG':\n syncImplementation.logger.debug(instruction.LogLine.line);\n break;\n case 'INFO':\n syncImplementation.logger.info(instruction.LogLine.line);\n break;\n case 'WARNING':\n syncImplementation.logger.warn(instruction.LogLine.line);\n break;\n }\n }\n else if ('UpdateSyncStatus' in instruction) {\n syncImplementation.updateSyncStatus(coreStatusToJs(instruction.UpdateSyncStatus.status));\n }\n else if ('EstablishSyncStream' in instruction) {\n if (receivingLines != null) {\n // Already connected, this shouldn't happen during a single iteration.\n throw 'Unexpected request to establish sync stream, already connected';\n }\n receivingLines = connect(instruction.EstablishSyncStream);\n }\n else if ('FetchCredentials' in instruction) {\n if (instruction.FetchCredentials.did_expire) {\n remote.invalidateCredentials();\n }\n else {\n remote.invalidateCredentials();\n // Restart iteration after the credentials have been refreshed.\n remote.fetchCredentials().then((_) => {\n controlInvocations?.enqueueData({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });\n }, (err) => {\n syncImplementation.logger.warn('Could not prefetch credentials', err);\n });\n }\n }\n else if ('CloseSyncStream' in instruction) {\n abortController.abort();\n hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;\n }\n else if ('FlushFileSystem' in instruction) ;\n else if ('DidCompleteSync' in instruction) {\n syncImplementation.updateSyncStatus({\n dataFlow: {\n downloadError: undefined\n }\n });\n }\n }\n async function handleInstructions(instructions) {\n for (const instr of instructions) {\n await handleInstruction(instr);\n }\n }\n try {\n const options = {\n parameters: resolvedOptions.params,\n app_metadata: resolvedOptions.appMetadata,\n active_streams: this.activeStreams,\n include_defaults: resolvedOptions.includeDefaultStreams\n };\n if (resolvedOptions.serializedSchema) {\n options.schema = resolvedOptions.serializedSchema;\n }\n await control(PowerSyncControlCommand.START, JSON.stringify(options));\n this.notifyCompletedUploads = () => {\n if (controlInvocations && !controlInvocations?.closed) {\n controlInvocations.enqueueData({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });\n }\n };\n this.handleActiveStreamsChange = () => {\n if (controlInvocations && !controlInvocations?.closed) {\n controlInvocations.enqueueData({\n command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,\n payload: JSON.stringify(this.activeStreams)\n });\n }\n };\n await receivingLines;\n }\n finally {\n this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;\n await stop();\n }\n return { immediateRestart: hideDisconnectOnRestart };\n }\n async updateSyncStatusForStartingCheckpoint(checkpoint) {\n const localProgress = await this.options.adapter.getBucketOperationProgress();\n const progress = {};\n let invalidated = false;\n for (const bucket of checkpoint.buckets) {\n const savedProgress = localProgress[bucket.bucket];\n const atLast = savedProgress?.atLast ?? 0;\n const sinceLast = savedProgress?.sinceLast ?? 0;\n progress[bucket.bucket] = {\n // The fallback priority doesn't matter here, but 3 is the one newer versions of the sync service\n // will use by default.\n priority: bucket.priority ?? 3,\n at_last: atLast,\n since_last: sinceLast,\n target_count: bucket.count ?? 0\n };\n if (bucket.count != null && bucket.count < atLast + sinceLast) {\n // Either due to a defrag / sync rule deploy or a compaction operation, the size\n // of the bucket shrank so much that the local ops exceed the ops in the updated\n // bucket. We can't prossibly report progress in this case (it would overshoot 100%).\n invalidated = true;\n }\n }\n if (invalidated) {\n for (const bucket in progress) {\n const bucketProgress = progress[bucket];\n bucketProgress.at_last = 0;\n bucketProgress.since_last = 0;\n }\n }\n this.updateSyncStatus({\n dataFlow: {\n downloading: true,\n downloadProgress: progress\n }\n });\n }\n async applyCheckpoint(checkpoint) {\n let result = await this.options.adapter.syncLocalDatabase(checkpoint);\n if (!result.checkpointValid) {\n this.logger.debug(`Checksum mismatch in checkpoint ${checkpoint.last_op_id}, will reconnect`);\n // This means checksums failed. Start again with a new checkpoint.\n // TODO: better back-off\n await new Promise((resolve) => setTimeout(resolve, 50));\n return { applied: false, endIteration: true };\n }\n else if (!result.ready) {\n this.logger.debug(`Could not apply checkpoint ${checkpoint.last_op_id} due to local data. We will retry applying the checkpoint after that upload is completed.`);\n return { applied: false, endIteration: false };\n }\n this.logger.debug(`Applied checkpoint ${checkpoint.last_op_id}`, checkpoint);\n this.updateSyncStatus({\n connected: true,\n lastSyncedAt: new Date(),\n dataFlow: {\n downloading: false,\n downloadProgress: null,\n downloadError: undefined\n }\n });\n return { applied: true, endIteration: false };\n }\n updateSyncStatus(options) {\n const updatedStatus = new SyncStatus({\n connected: options.connected ?? this.syncStatus.connected,\n connecting: !options.connected && (options.connecting ?? this.syncStatus.connecting),\n lastSyncedAt: options.lastSyncedAt ?? this.syncStatus.lastSyncedAt,\n dataFlow: {\n ...this.syncStatus.dataFlowStatus,\n ...options.dataFlow\n },\n priorityStatusEntries: options.priorityStatusEntries ?? this.syncStatus.priorityStatusEntries,\n clientImplementation: options.clientImplementation ?? this.syncStatus.clientImplementation\n });\n if (!this.syncStatus.isEqual(updatedStatus)) {\n this.syncStatus = updatedStatus;\n // Only trigger this is there was a change\n this.iterateListeners((cb) => cb.statusChanged?.(updatedStatus));\n }\n // trigger this for all updates\n this.iterateListeners((cb) => cb.statusUpdated?.(options));\n }\n async delayRetry(signal) {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n // If the signal is already aborted, resolve immediately\n resolve();\n return;\n }\n const { retryDelayMs } = this.options;\n let timeoutId;\n const endDelay = () => {\n resolve();\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n }\n signal?.removeEventListener('abort', endDelay);\n };\n signal?.addEventListener('abort', endDelay, { once: true });\n timeoutId = setTimeout(endDelay, retryDelayMs);\n });\n }\n updateSubscriptions(subscriptions) {\n this.activeStreams = subscriptions;\n this.handleActiveStreamsChange?.();\n }\n}\n\nconst CLAIM_STORE = new Map();\n/**\n * @internal\n * @experimental\n */\nconst MEMORY_TRIGGER_CLAIM_MANAGER = {\n async obtainClaim(identifier) {\n if (CLAIM_STORE.has(identifier)) {\n throw new Error(`A claim is already present for ${identifier}`);\n }\n const release = async () => {\n CLAIM_STORE.delete(identifier);\n };\n CLAIM_STORE.set(identifier, release);\n return release;\n },\n async checkClaim(identifier) {\n return CLAIM_STORE.has(identifier);\n }\n};\n\n/**\n * SQLite operations to track changes for with {@link TriggerManager}\n * @experimental\n */\nvar DiffTriggerOperation;\n(function (DiffTriggerOperation) {\n DiffTriggerOperation[\"INSERT\"] = \"INSERT\";\n DiffTriggerOperation[\"UPDATE\"] = \"UPDATE\";\n DiffTriggerOperation[\"DELETE\"] = \"DELETE\";\n})(DiffTriggerOperation || (DiffTriggerOperation = {}));\n\nconst DEFAULT_TRIGGER_MANAGER_CONFIGURATION = {\n useStorageByDefault: false\n};\nconst TRIGGER_CLEANUP_INTERVAL_MS = 120_000; // 2 minutes\n/**\n * @internal\n * @experimental\n */\nclass TriggerManagerImpl {\n options;\n schema;\n defaultConfig;\n cleanupTimeout;\n isDisposed;\n constructor(options) {\n this.options = options;\n this.schema = options.schema;\n options.db.registerListener({\n schemaChanged: (schema) => {\n this.schema = schema;\n }\n });\n this.isDisposed = false;\n /**\n * Configure a cleanup to run on an interval.\n * The interval is configured using setTimeout to take the async\n * execution time of the callback into account.\n */\n this.defaultConfig = DEFAULT_TRIGGER_MANAGER_CONFIGURATION;\n const cleanupCallback = async () => {\n this.cleanupTimeout = null;\n if (this.isDisposed) {\n return;\n }\n try {\n await this.cleanupResources();\n }\n catch (ex) {\n this.db.logger.error(`Caught error while attempting to cleanup triggers`, ex);\n }\n finally {\n // if not closed, set another timeout\n if (this.isDisposed) {\n return;\n }\n this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);\n }\n };\n this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);\n }\n get db() {\n return this.options.db;\n }\n async getUUID() {\n const { id: uuid } = await this.db.get(/* sql */ `\n SELECT\n uuid () as id\n `);\n // Replace dashes with underscores for SQLite table/trigger name compatibility\n return uuid.replace(/-/g, '_');\n }\n async removeTriggers(tx, triggerIds) {\n for (const triggerId of triggerIds) {\n await tx.execute(/* sql */ `DROP TRIGGER IF EXISTS ${triggerId}; `);\n }\n }\n dispose() {\n this.isDisposed = true;\n if (this.cleanupTimeout) {\n clearTimeout(this.cleanupTimeout);\n }\n }\n /**\n * Updates default config settings for platform specific use-cases.\n */\n updateDefaults(config) {\n this.defaultConfig = {\n ...this.defaultConfig,\n ...config\n };\n }\n generateTriggerName(operation, destinationTable, triggerId) {\n return `__ps_temp_trigger_${operation.toLowerCase()}__${destinationTable}__${triggerId}`;\n }\n /**\n * Cleanup any SQLite triggers or tables that are no longer in use.\n */\n async cleanupResources() {\n // we use the database here since cleanupResources is called during the PowerSyncDatabase initialization\n await this.db.database.writeLock(async (ctx) => {\n /**\n * Note: We only cleanup persisted triggers. These are tracked in the sqlite_master table.\n * temporary triggers will not be affected by this.\n * Query all triggers that match our naming pattern\n */\n const triggers = await ctx.getAll(/* sql */ `\n SELECT\n name\n FROM\n sqlite_master\n WHERE\n type = 'trigger'\n AND name LIKE '__ps_temp_trigger_%'\n `);\n /** Use regex to extract table names and IDs from trigger names\n * Trigger naming convention: __ps_temp_trigger_<operation>__<destination_table>__<id>\n */\n const triggerPattern = /^__ps_temp_trigger_(?:insert|update|delete)__(.+)__([a-f0-9_]{36})$/i;\n const trackedItems = new Map();\n for (const trigger of triggers) {\n const match = trigger.name.match(triggerPattern);\n if (match) {\n const [, table, id] = match;\n // Collect all trigger names for each id combo\n const existing = trackedItems.get(id);\n if (existing) {\n existing.triggerNames.push(trigger.name);\n }\n else {\n trackedItems.set(id, { table, id, triggerNames: [trigger.name] });\n }\n }\n }\n for (const trackedItem of trackedItems.values()) {\n // check if there is anything holding on to this item\n const hasClaim = await this.options.claimManager.checkClaim(trackedItem.id);\n if (hasClaim) {\n // This does not require cleanup\n continue;\n }\n this.db.logger.debug(`Clearing resources for trigger ${trackedItem.id} with table ${trackedItem.table}`);\n // We need to delete the triggers and table\n for (const triggerName of trackedItem.triggerNames) {\n await ctx.execute(`DROP TRIGGER IF EXISTS ${triggerName}`);\n }\n await ctx.execute(`DROP TABLE IF EXISTS ${trackedItem.table}`);\n }\n });\n }\n async createDiffTrigger(options) {\n await this.db.waitForReady();\n const { source, destination, columns, when, hooks, \n // Fall back to the provided default if not given on this level\n useStorage = this.defaultConfig.useStorageByDefault } = options;\n const operations = Object.keys(when);\n if (operations.length == 0) {\n throw new Error('At least one WHEN operation must be specified for the trigger.');\n }\n /**\n * The clause to use when executing\n * CREATE ${tableTriggerTypeClause} TABLE\n * OR\n * CREATE ${tableTriggerTypeClause} TRIGGER\n */\n const tableTriggerTypeClause = !useStorage ? 'TEMP' : '';\n const whenClauses = Object.fromEntries(Object.entries(when).map(([operation, filter]) => [operation, `WHEN ${filter}`]));\n /**\n * Allow specifying the View name as the source.\n * We can lookup the internal table name from the schema.\n */\n const sourceDefinition = this.schema.tables.find((table) => table.viewName == source);\n if (!sourceDefinition) {\n throw new Error(`Source table or view \"${source}\" not found in the schema.`);\n }\n const replicatedColumns = columns ?? sourceDefinition.columns.map((col) => col.name);\n const internalSource = sourceDefinition.internalName;\n const triggerIds = [];\n const id = await this.getUUID();\n const releaseStorageClaim = useStorage ? await this.options.claimManager.obtainClaim(id) : null;\n /**\n * We default to replicating all columns if no columns array is provided.\n */\n const jsonFragment = (source = 'NEW') => {\n if (columns == null) {\n // Track all columns\n return `${source}.data`;\n }\n else if (columns.length == 0) {\n // Don't track any columns except for the id\n return `'{}'`;\n }\n else {\n // Filter the data by the replicated columns\n return `json_object(${replicatedColumns.map((col) => `'${col}', json_extract(${source}.data, '$.${col}')`).join(', ')})`;\n }\n };\n const disposeWarningListener = this.db.registerListener({\n schemaChanged: () => {\n this.db.logger.warn(`The PowerSync schema has changed while previously configured triggers are still operational. This might cause unexpected results.`);\n }\n });\n /**\n * Declare the cleanup function early since if any of the init steps fail,\n * we need to ensure we can cleanup the created resources.\n * We unfortunately cannot rely on transaction rollback.\n */\n const cleanup = async () => {\n disposeWarningListener();\n return this.db.writeLock(async (tx) => {\n await this.removeTriggers(tx, triggerIds);\n await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);\n await releaseStorageClaim?.();\n });\n };\n const setup = async (tx) => {\n // Allow user code to execute in this lock context before the trigger is created.\n await hooks?.beforeCreate?.(tx);\n await tx.execute(/* sql */ `\n CREATE ${tableTriggerTypeClause} TABLE ${destination} (\n operation_id INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT,\n operation TEXT,\n timestamp TEXT,\n value TEXT,\n previous_value TEXT\n )\n `);\n if (operations.includes(DiffTriggerOperation.INSERT)) {\n const insertTriggerId = this.generateTriggerName(DiffTriggerOperation.INSERT, destination, id);\n triggerIds.push(insertTriggerId);\n await tx.execute(/* sql */ `\n CREATE ${tableTriggerTypeClause} TRIGGER ${insertTriggerId} AFTER INSERT ON ${internalSource} ${whenClauses[DiffTriggerOperation.INSERT]} BEGIN\n INSERT INTO\n ${destination} (id, operation, timestamp, value)\n VALUES\n (\n NEW.id,\n 'INSERT',\n strftime ('%Y-%m-%dT%H:%M:%fZ', 'now'),\n ${jsonFragment('NEW')}\n );\n\n END\n `);\n }\n if (operations.includes(DiffTriggerOperation.UPDATE)) {\n const updateTriggerId = this.generateTriggerName(DiffTriggerOperation.UPDATE, destination, id);\n triggerIds.push(updateTriggerId);\n await tx.execute(/* sql */ `\n CREATE ${tableTriggerTypeClause} TRIGGER ${updateTriggerId} AFTER\n UPDATE ON ${internalSource} ${whenClauses[DiffTriggerOperation.UPDATE]} BEGIN\n INSERT INTO\n ${destination} (id, operation, timestamp, value, previous_value)\n VALUES\n (\n NEW.id,\n 'UPDATE',\n strftime ('%Y-%m-%dT%H:%M:%fZ', 'now'),\n ${jsonFragment('NEW')},\n ${jsonFragment('OLD')}\n );\n\n END;\n `);\n }\n if (operations.includes(DiffTriggerOperation.DELETE)) {\n const deleteTriggerId = this.generateTriggerName(DiffTriggerOperation.DELETE, destination, id);\n triggerIds.push(deleteTriggerId);\n // Create delete trigger for basic JSON\n await tx.execute(/* sql */ `\n CREATE ${tableTriggerTypeClause} TRIGGER ${deleteTriggerId} AFTER DELETE ON ${internalSource} ${whenClauses[DiffTriggerOperation.DELETE]} BEGIN\n INSERT INTO\n ${destination} (id, operation, timestamp, value)\n VALUES\n (\n OLD.id,\n 'DELETE',\n strftime ('%Y-%m-%dT%H:%M:%fZ', 'now'),\n ${jsonFragment('OLD')}\n );\n\n END;\n `);\n }\n };\n try {\n await this.db.writeLock(setup);\n return cleanup;\n }\n catch (error) {\n try {\n await cleanup();\n }\n catch (cleanupError) {\n throw new AggregateError([error, cleanupError], 'Error during operation and cleanup');\n }\n throw error;\n }\n }\n async trackTableDiff(options) {\n const { source, when, columns, hooks, throttleMs = DEFAULT_WATCH_THROTTLE_MS } = options;\n await this.db.waitForReady();\n /**\n * Allow specifying the View name as the source.\n * We can lookup the internal table name from the schema.\n */\n const sourceDefinition = this.schema.tables.find((table) => table.viewName == source);\n if (!sourceDefinition) {\n throw new Error(`Source table or view \"${source}\" not found in the schema.`);\n }\n // The columns to present in the onChange context methods.\n // If no array is provided, we use all columns from the source table.\n const contextColumns = columns ?? sourceDefinition.columns.map((col) => col.name);\n const id = await this.getUUID();\n const destination = `__ps_temp_track_${source}_${id}`;\n // register an onChange before the trigger is created\n const abortController = new AbortController();\n const abortOnChange = () => abortController.abort();\n this.db.onChange({\n // Note that the onChange events here have their execution scheduled.\n // Callbacks are throttled and are sequential.\n onChange: async () => {\n if (abortController.signal.aborted)\n return;\n // Run the handler in a write lock to keep the state of the\n // destination table consistent.\n await this.db.writeTransaction(async (tx) => {\n const callbackResult = await options.onChange({\n ...tx,\n destinationTable: destination,\n withDiff: async (query, params, options) => {\n // Wrap the query to expose the destination table\n const operationIdSelect = options?.castOperationIdAsText\n ? 'id, operation, CAST(operation_id AS TEXT) as operation_id, timestamp, value, previous_value'\n : '*';\n const wrappedQuery = /* sql */ `\n WITH\n DIFF AS (\n SELECT\n ${operationIdSelect}\n FROM\n ${destination}\n ORDER BY\n operation_id ASC\n ) ${query}\n `;\n return tx.getAll(wrappedQuery, params);\n },\n withExtractedDiff: async (query, params) => {\n // Wrap the query to expose the destination table\n const wrappedQuery = /* sql */ `\n WITH\n DIFF AS (\n SELECT\n id,\n ${contextColumns.length > 0\n ? `${contextColumns.map((col) => `json_extract(value, '$.${col}') as ${col}`).join(', ')},`\n : ''} operation_id as __operation_id,\n operation as __operation,\n timestamp as __timestamp,\n previous_value as __previous_value\n FROM\n ${destination}\n ORDER BY\n __operation_id ASC\n ) ${query}\n `;\n return tx.getAll(wrappedQuery, params);\n }\n });\n // Clear the destination table after processing\n await tx.execute(/* sql */ `DELETE FROM ${destination};`);\n return callbackResult;\n });\n }\n }, { tables: [destination], signal: abortController.signal, throttleMs });\n try {\n const removeTrigger = await this.createDiffTrigger({\n source,\n destination,\n columns: contextColumns,\n when,\n hooks\n });\n return async () => {\n abortOnChange();\n await removeTrigger();\n };\n }\n catch (error) {\n try {\n abortOnChange();\n }\n catch (cleanupError) {\n throw new AggregateError([error, cleanupError], 'Error during operation and cleanup');\n }\n throw error;\n }\n }\n}\n\nconst POWERSYNC_TABLE_MATCH = /(^ps_data__|^ps_data_local__)/;\nconst DEFAULT_DISCONNECT_CLEAR_OPTIONS = {\n clearLocal: true\n};\nconst DEFAULT_POWERSYNC_CLOSE_OPTIONS = {\n disconnect: true\n};\nconst DEFAULT_POWERSYNC_DB_OPTIONS = {\n retryDelayMs: 5000,\n crudUploadThrottleMs: DEFAULT_CRUD_UPLOAD_THROTTLE_MS\n};\nconst DEFAULT_CRUD_BATCH_LIMIT = 100;\n/**\n * Requesting nested or recursive locks can block the application in some circumstances.\n * This default lock timeout will act as a failsafe to throw an error if a lock cannot\n * be obtained.\n */\nconst DEFAULT_LOCK_TIMEOUT_MS = 120_000; // 2 mins\n/**\n * Tests if the input is a {@link PowerSyncDatabaseOptionsWithSettings}\n * @internal\n */\nconst isPowerSyncDatabaseOptionsWithSettings = (test) => {\n return typeof test == 'object' && isSQLOpenOptions(test.database);\n};\nclass AbstractPowerSyncDatabase extends BaseObserver {\n options;\n /**\n * Returns true if the connection is closed.\n */\n closed;\n ready;\n /**\n * Current connection status.\n */\n currentStatus;\n sdkVersion;\n bucketStorageAdapter;\n _isReadyPromise;\n connectionManager;\n subscriptions;\n get syncStreamImplementation() {\n return this.connectionManager.syncStreamImplementation;\n }\n /**\n * The connector used to connect to the PowerSync service.\n *\n * @returns The connector used to connect to the PowerSync service or null if `connect()` has not been called.\n */\n get connector() {\n return this.connectionManager.connector;\n }\n /**\n * The resolved connection options used to connect to the PowerSync service.\n *\n * @returns The resolved connection options used to connect to the PowerSync service or null if `connect()` has not been called.\n */\n get connectionOptions() {\n return this.connectionManager.connectionOptions;\n }\n _schema;\n _database;\n runExclusiveMutex;\n /**\n * @experimental\n * Allows creating SQLite triggers which can be used to track various operations on SQLite tables.\n */\n triggers;\n triggersImpl;\n logger;\n constructor(options) {\n super();\n this.options = options;\n const { database, schema } = options;\n if (typeof schema?.toJSON != 'function') {\n throw new Error('The `schema` option should be provided and should be an instance of `Schema`.');\n }\n if (isDBAdapter(database)) {\n this._database = database;\n }\n else if (isSQLOpenFactory(database)) {\n this._database = database.openDB();\n }\n else if (isPowerSyncDatabaseOptionsWithSettings(options)) {\n this._database = this.openDBAdapter(options);\n }\n else {\n throw new Error('The provided `database` option is invalid.');\n }\n this.logger = options.logger ?? Logger.get(`PowerSyncDatabase[${this._database.name}]`);\n this.bucketStorageAdapter = this.generateBucketStorageAdapter();\n this.closed = false;\n this.currentStatus = new SyncStatus({});\n this.options = { ...DEFAULT_POWERSYNC_DB_OPTIONS, ...options };\n this._schema = schema;\n this.ready = false;\n this.sdkVersion = '';\n this.runExclusiveMutex = new Mutex();\n // Start async init\n this.subscriptions = {\n firstStatusMatching: (predicate, abort) => this.waitForStatus(predicate, abort),\n resolveOfflineSyncStatus: () => this.resolveOfflineSyncStatus(),\n rustSubscriptionsCommand: async (payload) => {\n await this.writeTransaction((tx) => {\n return tx.execute('select powersync_control(?,?)', ['subscriptions', JSON.stringify(payload)]);\n });\n }\n };\n this.connectionManager = new ConnectionManager({\n createSyncImplementation: async (connector, options) => {\n await this.waitForReady();\n return this.runExclusive(async () => {\n const sync = this.generateSyncStreamImplementation(connector, this.resolvedConnectionOptions(options));\n const onDispose = sync.registerListener({\n statusChanged: (status) => {\n this.currentStatus = new SyncStatus({\n ...status.toJSON(),\n hasSynced: this.currentStatus?.hasSynced || !!status.lastSyncedAt\n });\n this.iterateListeners((cb) => cb.statusChanged?.(this.currentStatus));\n }\n });\n await sync.waitForReady();\n return {\n sync,\n onDispose\n };\n });\n },\n logger: this.logger\n });\n this._isReadyPromise = this.initialize();\n this.triggers = this.triggersImpl = new TriggerManagerImpl({\n db: this,\n schema: this.schema,\n ...this.generateTriggerManagerConfig()\n });\n }\n /**\n * Schema used for the local database.\n */\n get schema() {\n return this._schema;\n }\n /**\n * The underlying database.\n *\n * For the most part, behavior is the same whether querying on the underlying database, or on {@link AbstractPowerSyncDatabase}.\n */\n get database() {\n return this._database;\n }\n /**\n * Whether a connection to the PowerSync service is currently open.\n */\n get connected() {\n return this.currentStatus?.connected || false;\n }\n get connecting() {\n return this.currentStatus?.connecting || false;\n }\n /**\n * Generates a base configuration for {@link TriggerManagerImpl}.\n * Implementations should override this if necessary.\n */\n generateTriggerManagerConfig() {\n return {\n claimManager: MEMORY_TRIGGER_CLAIM_MANAGER\n };\n }\n /**\n * @returns A promise which will resolve once initialization is completed.\n */\n async waitForReady() {\n if (this.ready) {\n return;\n }\n await this._isReadyPromise;\n }\n /**\n * Wait for the first sync operation to complete.\n *\n * @param request Either an abort signal (after which the promise will complete regardless of\n * whether a full sync was completed) or an object providing an abort signal and a priority target.\n * When a priority target is set, the promise may complete when all buckets with the given (or higher)\n * priorities have been synchronized. This can be earlier than a complete sync.\n * @returns A promise which will resolve once the first full sync has completed.\n */\n async waitForFirstSync(request) {\n const signal = request instanceof AbortSignal ? request : request?.signal;\n const priority = request && 'priority' in request ? request.priority : undefined;\n const statusMatches = priority === undefined\n ? (status) => status.hasSynced\n : (status) => status.statusForPriority(priority).hasSynced;\n return this.waitForStatus(statusMatches, signal);\n }\n /**\n * Waits for the first sync status for which the `status` callback returns a truthy value.\n */\n async waitForStatus(predicate, signal) {\n if (predicate(this.currentStatus)) {\n return;\n }\n return new Promise((resolve) => {\n const dispose = this.registerListener({\n statusChanged: (status) => {\n if (predicate(status)) {\n abort();\n }\n }\n });\n function abort() {\n dispose();\n resolve();\n }\n if (signal?.aborted) {\n abort();\n }\n else {\n signal?.addEventListener('abort', abort);\n }\n });\n }\n /**\n * Entry point for executing initialization logic.\n * This is to be automatically executed in the constructor.\n */\n async initialize() {\n await this._initialize();\n await this.bucketStorageAdapter.init();\n await this.loadVersion();\n await this.updateSchema(this.options.schema);\n await this.resolveOfflineSyncStatus();\n await this.database.execute('PRAGMA RECURSIVE_TRIGGERS=TRUE');\n await this.triggersImpl.cleanupResources();\n this.ready = true;\n this.iterateListeners((cb) => cb.initialized?.());\n }\n async loadVersion() {\n try {\n const { version } = await this.database.get('SELECT powersync_rs_version() as version');\n this.sdkVersion = version;\n }\n catch (e) {\n throw new Error(`The powersync extension is not loaded correctly. Details: ${e.message}`);\n }\n let versionInts;\n try {\n versionInts = this.sdkVersion.split(/[.\\/]/)\n .slice(0, 3)\n .map((n) => parseInt(n));\n }\n catch (e) {\n throw new Error(`Unsupported powersync extension version. Need >=0.4.10 <1.0.0, got: ${this.sdkVersion}. Details: ${e.message}`);\n }\n // Validate >=0.4.10 <1.0.0\n if (versionInts[0] != 0 || versionInts[1] < 4 || (versionInts[1] == 4 && versionInts[2] < 10)) {\n throw new Error(`Unsupported powersync extension version. Need >=0.4.10 <1.0.0, got: ${this.sdkVersion}`);\n }\n }\n async resolveOfflineSyncStatus() {\n const result = await this.database.get('SELECT powersync_offline_sync_status() as r');\n const parsed = JSON.parse(result.r);\n const updatedStatus = new SyncStatus({\n ...this.currentStatus.toJSON(),\n ...coreStatusToJs(parsed)\n });\n if (!updatedStatus.isEqual(this.currentStatus)) {\n this.currentStatus = updatedStatus;\n this.iterateListeners((l) => l.statusChanged?.(this.currentStatus));\n }\n }\n /**\n * Replace the schema with a new version. This is for advanced use cases - typically the schema should just be specified once in the constructor.\n *\n * Cannot be used while connected - this should only be called before {@link AbstractPowerSyncDatabase.connect}.\n */\n async updateSchema(schema) {\n if (this.syncStreamImplementation) {\n throw new Error('Cannot update schema while connected');\n }\n /**\n * TODO\n * Validations only show a warning for now.\n * The next major release should throw an exception.\n */\n try {\n schema.validate();\n }\n catch (ex) {\n this.logger.warn('Schema validation failed. Unexpected behaviour could occur', ex);\n }\n this._schema = schema;\n await this.database.execute('SELECT powersync_replace_schema(?)', [JSON.stringify(this.schema.toJSON())]);\n await this.database.refreshSchema();\n this.iterateListeners(async (cb) => cb.schemaChanged?.(schema));\n }\n /**\n * Wait for initialization to complete.\n * While initializing is automatic, this helps to catch and report initialization errors.\n */\n async init() {\n return this.waitForReady();\n }\n // Use the options passed in during connect, or fallback to the options set during database creation or fallback to the default options\n resolvedConnectionOptions(options) {\n return {\n ...options,\n retryDelayMs: options?.retryDelayMs ?? this.options.retryDelayMs ?? this.options.retryDelay ?? DEFAULT_RETRY_DELAY_MS,\n crudUploadThrottleMs: options?.crudUploadThrottleMs ?? this.options.crudUploadThrottleMs ?? DEFAULT_CRUD_UPLOAD_THROTTLE_MS\n };\n }\n /**\n * @deprecated Use {@link AbstractPowerSyncDatabase#close} instead.\n * Clears all listeners registered by {@link AbstractPowerSyncDatabase#registerListener}.\n */\n dispose() {\n return super.dispose();\n }\n /**\n * Locking mechanism for exclusively running critical portions of connect/disconnect operations.\n * Locking here is mostly only important on web for multiple tab scenarios.\n */\n runExclusive(callback) {\n return this.runExclusiveMutex.runExclusive(callback);\n }\n /**\n * Connects to stream of events from the PowerSync instance.\n */\n async connect(connector, options) {\n const resolvedOptions = options ?? {};\n resolvedOptions.serializedSchema = this.schema.toJSON();\n return this.connectionManager.connect(connector, resolvedOptions);\n }\n /**\n * Close the sync connection.\n *\n * Use {@link connect} to connect again.\n */\n async disconnect() {\n return this.connectionManager.disconnect();\n }\n /**\n * Disconnect and clear the database.\n * Use this when logging out.\n * The database can still be queried after this is called, but the tables\n * would be empty.\n *\n * To preserve data in local-only tables, set clearLocal to false.\n */\n async disconnectAndClear(options = DEFAULT_DISCONNECT_CLEAR_OPTIONS) {\n await this.disconnect();\n await this.waitForReady();\n const { clearLocal } = options;\n await this.database.writeTransaction(async (tx) => {\n await tx.execute('SELECT powersync_clear(?)', [clearLocal ? 1 : 0]);\n });\n // The data has been deleted - reset the sync status\n this.currentStatus = new SyncStatus({});\n this.iterateListeners((l) => l.statusChanged?.(this.currentStatus));\n }\n /**\n * Create a sync stream to query its status or to subscribe to it.\n *\n * @param name The name of the stream to subscribe to.\n * @param params Optional parameters for the stream subscription.\n * @returns A {@link SyncStream} instance that can be subscribed to.\n * @experimental Sync streams are currently in alpha.\n */\n syncStream(name, params) {\n return this.connectionManager.stream(this.subscriptions, name, params ?? null);\n }\n /**\n * Close the database, releasing resources.\n *\n * Also disconnects any active connection.\n *\n * Once close is called, this connection cannot be used again - a new one\n * must be constructed.\n */\n async close(options = DEFAULT_POWERSYNC_CLOSE_OPTIONS) {\n await this.waitForReady();\n if (this.closed) {\n return;\n }\n this.triggersImpl.dispose();\n await this.iterateAsyncListeners(async (cb) => cb.closing?.());\n const { disconnect } = options;\n if (disconnect) {\n await this.disconnect();\n }\n await this.connectionManager.close();\n await this.database.close();\n this.closed = true;\n await this.iterateAsyncListeners(async (cb) => cb.closed?.());\n }\n /**\n * Get upload queue size estimate and count.\n */\n async getUploadQueueStats(includeSize) {\n return this.readTransaction(async (tx) => {\n if (includeSize) {\n const result = await tx.execute(`SELECT SUM(cast(data as blob) + 20) as size, count(*) as count FROM ${PSInternalTable.CRUD}`);\n const row = result.rows.item(0);\n return new UploadQueueStats(row?.count ?? 0, row?.size ?? 0);\n }\n else {\n const result = await tx.execute(`SELECT count(*) as count FROM ${PSInternalTable.CRUD}`);\n const row = result.rows.item(0);\n return new UploadQueueStats(row?.count ?? 0);\n }\n });\n }\n /**\n * Get a batch of CRUD data to upload.\n *\n * Returns null if there is no data to upload.\n *\n * Use this from the {@link PowerSyncBackendConnector.uploadData} callback.\n *\n * Once the data have been successfully uploaded, call {@link CrudBatch.complete} before\n * requesting the next batch.\n *\n * Use {@link limit} to specify the maximum number of updates to return in a single\n * batch.\n *\n * This method does include transaction ids in the result, but does not group\n * data by transaction. One batch may contain data from multiple transactions,\n * and a single transaction may be split over multiple batches.\n *\n * @param limit Maximum number of CRUD entries to include in the batch\n * @returns A batch of CRUD operations to upload, or null if there are none\n */\n async getCrudBatch(limit = DEFAULT_CRUD_BATCH_LIMIT) {\n const result = await this.getAll(`SELECT id, tx_id, data FROM ${PSInternalTable.CRUD} ORDER BY id ASC LIMIT ?`, [limit + 1]);\n const all = result.map((row) => CrudEntry.fromRow(row)) ?? [];\n let haveMore = false;\n if (all.length > limit) {\n all.pop();\n haveMore = true;\n }\n if (all.length == 0) {\n return null;\n }\n const last = all[all.length - 1];\n return new CrudBatch(all, haveMore, async (writeCheckpoint) => this.handleCrudCheckpoint(last.clientId, writeCheckpoint));\n }\n /**\n * Get the next recorded transaction to upload.\n *\n * Returns null if there is no data to upload.\n *\n * Use this from the {@link PowerSyncBackendConnector.uploadData} callback.\n *\n * Once the data have been successfully uploaded, call {@link CrudTransaction.complete} before\n * requesting the next transaction.\n *\n * Unlike {@link getCrudBatch}, this only returns data from a single transaction at a time.\n * All data for the transaction is loaded into memory.\n *\n * @returns A transaction of CRUD operations to upload, or null if there are none\n */\n async getNextCrudTransaction() {\n const iterator = this.getCrudTransactions()[symbolAsyncIterator]();\n return (await iterator.next()).value;\n }\n /**\n * Returns an async iterator of completed transactions with local writes against the database.\n *\n * This is typically used from the {@link PowerSyncBackendConnector.uploadData} callback. Each entry emitted by the\n * returned iterator is a full transaction containing all local writes made while that transaction was active.\n *\n * Unlike {@link getNextCrudTransaction}, which always returns the oldest transaction that hasn't been\n * {@link CrudTransaction.complete}d yet, this iterator can be used to receive multiple transactions. Calling\n * {@link CrudTransaction.complete} will mark that and all prior transactions emitted by the iterator as completed.\n *\n * This can be used to upload multiple transactions in a single batch, e.g with:\n *\n * ```JavaScript\n * let lastTransaction = null;\n * let batch = [];\n *\n * for await (const transaction of database.getCrudTransactions()) {\n * batch.push(...transaction.crud);\n * lastTransaction = transaction;\n *\n * if (batch.length > 10) {\n * break;\n * }\n * }\n * ```\n *\n * If there is no local data to upload, the async iterator complete without emitting any items.\n *\n * Note that iterating over async iterables requires a [polyfill](https://github.com/powersync-ja/powersync-js/tree/main/packages/react-native#babel-plugins-watched-queries)\n * for React Native.\n */\n getCrudTransactions() {\n return {\n [symbolAsyncIterator]: () => {\n let lastCrudItemId = -1;\n const sql = `\nWITH RECURSIVE crud_entries AS (\n SELECT id, tx_id, data FROM ps_crud WHERE id = (SELECT min(id) FROM ps_crud WHERE id > ?)\n UNION ALL\n SELECT ps_crud.id, ps_crud.tx_id, ps_crud.data FROM ps_crud\n INNER JOIN crud_entries ON crud_entries.id + 1 = rowid\n WHERE crud_entries.tx_id = ps_crud.tx_id\n)\nSELECT * FROM crud_entries;\n `;\n return {\n next: async () => {\n const nextTransaction = await this.database.getAll(sql, [lastCrudItemId]);\n if (nextTransaction.length == 0) {\n return { done: true, value: null };\n }\n const items = nextTransaction.map((row) => CrudEntry.fromRow(row));\n const last = items[items.length - 1];\n const txId = last.transactionId;\n lastCrudItemId = last.clientId;\n return {\n done: false,\n value: new CrudTransaction(items, async (writeCheckpoint) => this.handleCrudCheckpoint(last.clientId, writeCheckpoint), txId)\n };\n }\n };\n }\n };\n }\n /**\n * Get an unique client id for this database.\n *\n * The id is not reset when the database is cleared, only when the database is deleted.\n *\n * @returns A unique identifier for the database instance\n */\n async getClientId() {\n return this.bucketStorageAdapter.getClientId();\n }\n async handleCrudCheckpoint(lastClientId, writeCheckpoint) {\n return this.writeTransaction(async (tx) => {\n await tx.execute(`DELETE FROM ${PSInternalTable.CRUD} WHERE id <= ?`, [lastClientId]);\n if (writeCheckpoint) {\n const check = await tx.execute(`SELECT 1 FROM ${PSInternalTable.CRUD} LIMIT 1`);\n if (!check.rows?.length) {\n await tx.execute(`UPDATE ${PSInternalTable.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`, [\n writeCheckpoint\n ]);\n }\n }\n else {\n await tx.execute(`UPDATE ${PSInternalTable.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`, [\n this.bucketStorageAdapter.getMaxOpId()\n ]);\n }\n });\n }\n /**\n * Execute a SQL write (INSERT/UPDATE/DELETE) query\n * and optionally return results.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @returns The query result as an object with structured key-value pairs\n */\n async execute(sql, parameters) {\n return this.writeLock((tx) => tx.execute(sql, parameters));\n }\n /**\n * Execute a SQL write (INSERT/UPDATE/DELETE) query directly on the database without any PowerSync processing.\n * This bypasses certain PowerSync abstractions and is useful for accessing the raw database results.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @returns The raw query result from the underlying database as a nested array of raw values, where each row is\n * represented as an array of column values without field names.\n */\n async executeRaw(sql, parameters) {\n await this.waitForReady();\n return this.database.executeRaw(sql, parameters);\n }\n /**\n * Execute a write query (INSERT/UPDATE/DELETE) multiple times with each parameter set\n * and optionally return results.\n * This is faster than executing separately with each parameter set.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional 2D array of parameter sets, where each inner array is a set of parameters for one execution\n * @returns The query result\n */\n async executeBatch(sql, parameters) {\n await this.waitForReady();\n return this.database.executeBatch(sql, parameters);\n }\n /**\n * Execute a read-only query and return results.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @returns An array of results\n */\n async getAll(sql, parameters) {\n await this.waitForReady();\n return this.database.getAll(sql, parameters);\n }\n /**\n * Execute a read-only query and return the first result, or null if the ResultSet is empty.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @returns The first result if found, or null if no results are returned\n */\n async getOptional(sql, parameters) {\n await this.waitForReady();\n return this.database.getOptional(sql, parameters);\n }\n /**\n * Execute a read-only query and return the first result, error if the ResultSet is empty.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @returns The first result matching the query\n * @throws Error if no rows are returned\n */\n async get(sql, parameters) {\n await this.waitForReady();\n return this.database.get(sql, parameters);\n }\n /**\n * Takes a read lock, without starting a transaction.\n * In most cases, {@link readTransaction} should be used instead.\n */\n async readLock(callback) {\n await this.waitForReady();\n return this.database.readLock(callback);\n }\n /**\n * Takes a global lock, without starting a transaction.\n * In most cases, {@link writeTransaction} should be used instead.\n */\n async writeLock(callback) {\n await this.waitForReady();\n return this.database.writeLock(callback);\n }\n /**\n * Open a read-only transaction.\n * Read transactions can run concurrently to a write transaction.\n * Changes from any write transaction are not visible to read transactions started before it.\n *\n * @param callback Function to execute within the transaction\n * @param lockTimeout Time in milliseconds to wait for a lock before throwing an error\n * @returns The result of the callback\n * @throws Error if the lock cannot be obtained within the timeout period\n */\n async readTransaction(callback, lockTimeout = DEFAULT_LOCK_TIMEOUT_MS) {\n await this.waitForReady();\n return this.database.readTransaction(async (tx) => {\n const res = await callback({ ...tx });\n await tx.rollback();\n return res;\n }, { timeoutMs: lockTimeout });\n }\n /**\n * Open a read-write transaction.\n * This takes a global lock - only one write transaction can execute against the database at a time.\n * Statements within the transaction must be done on the provided {@link Transaction} interface.\n *\n * @param callback Function to execute within the transaction\n * @param lockTimeout Time in milliseconds to wait for a lock before throwing an error\n * @returns The result of the callback\n * @throws Error if the lock cannot be obtained within the timeout period\n */\n async writeTransaction(callback, lockTimeout = DEFAULT_LOCK_TIMEOUT_MS) {\n await this.waitForReady();\n return this.database.writeTransaction(async (tx) => {\n const res = await callback(tx);\n await tx.commit();\n return res;\n }, { timeoutMs: lockTimeout });\n }\n watch(sql, parameters, handlerOrOptions, maybeOptions) {\n if (handlerOrOptions && typeof handlerOrOptions === 'object' && 'onResult' in handlerOrOptions) {\n const handler = handlerOrOptions;\n const options = maybeOptions;\n return this.watchWithCallback(sql, parameters, handler, options);\n }\n const options = handlerOrOptions;\n return this.watchWithAsyncGenerator(sql, parameters, options);\n }\n /**\n * Allows defining a query which can be used to build a {@link WatchedQuery}.\n * The defined query will be executed with {@link AbstractPowerSyncDatabase#getAll}.\n * An optional mapper function can be provided to transform the results.\n *\n * @example\n * ```javascript\n * const watchedTodos = powersync.query({\n * sql: `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,\n * parameters: [],\n * mapper: (row) => ({\n * ...row,\n * created_at: new Date(row.created_at as string)\n * })\n * })\n * .watch()\n * // OR use .differentialWatch() for fine-grained watches.\n * ```\n */\n query(query) {\n const { sql, parameters = [], mapper } = query;\n const compatibleQuery = {\n compile: () => ({\n sql,\n parameters\n }),\n execute: async ({ sql, parameters }) => {\n const result = await this.getAll(sql, parameters);\n return mapper ? result.map(mapper) : result;\n }\n };\n return this.customQuery(compatibleQuery);\n }\n /**\n * Allows building a {@link WatchedQuery} using an existing {@link WatchCompatibleQuery}.\n * The watched query will use the provided {@link WatchCompatibleQuery.execute} method to query results.\n *\n * @example\n * ```javascript\n *\n * // Potentially a query from an ORM like Drizzle\n * const query = db.select().from(lists);\n *\n * const watchedTodos = powersync.customQuery(query)\n * .watch()\n * // OR use .differentialWatch() for fine-grained watches.\n * ```\n */\n customQuery(query) {\n return new CustomQuery({\n db: this,\n query\n });\n }\n /**\n * Execute a read query every time the source tables are modified.\n * Use {@link SQLWatchOptions.throttleMs} to specify the minimum interval between queries.\n * Source tables are automatically detected using `EXPLAIN QUERY PLAN`.\n *\n * Note that the `onChange` callback member of the handler is required.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @param handler Callbacks for handling results and errors\n * @param options Options for configuring watch behavior\n */\n watchWithCallback(sql, parameters, handler, options) {\n const { onResult, onError = (e) => this.logger.error(e) } = handler ?? {};\n if (!onResult) {\n throw new Error('onResult is required');\n }\n const { comparator } = options ?? {};\n // This API yields a QueryResult type.\n // This is not a standard Array result, which makes it incompatible with the .query API.\n const watchedQuery = new OnChangeQueryProcessor({\n db: this,\n comparator,\n placeholderData: null,\n watchOptions: {\n query: {\n compile: () => ({\n sql: sql,\n parameters: parameters ?? []\n }),\n execute: () => this.executeReadOnly(sql, parameters)\n },\n reportFetching: false,\n throttleMs: options?.throttleMs ?? DEFAULT_WATCH_THROTTLE_MS,\n triggerOnTables: options?.tables\n }\n });\n const dispose = watchedQuery.registerListener({\n onData: (data) => {\n if (!data) {\n // This should not happen. We only use null for the initial data.\n return;\n }\n onResult(data);\n },\n onError: (error) => {\n onError(error);\n }\n });\n options?.signal?.addEventListener('abort', () => {\n dispose();\n watchedQuery.close();\n });\n }\n /**\n * Execute a read query every time the source tables are modified.\n * Use {@link SQLWatchOptions.throttleMs} to specify the minimum interval between queries.\n * Source tables are automatically detected using `EXPLAIN QUERY PLAN`.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @param options Options for configuring watch behavior\n * @returns An AsyncIterable that yields QueryResults whenever the data changes\n */\n watchWithAsyncGenerator(sql, parameters, options) {\n return new domExports.EventIterator((eventOptions) => {\n const handler = {\n onResult: (result) => {\n eventOptions.push(result);\n },\n onError: (error) => {\n eventOptions.fail(error);\n }\n };\n this.watchWithCallback(sql, parameters, handler, options);\n options?.signal?.addEventListener('abort', () => {\n eventOptions.stop();\n });\n });\n }\n /**\n * Resolves the list of tables that are used in a SQL query.\n * If tables are specified in the options, those are used directly.\n * Otherwise, analyzes the query using EXPLAIN to determine which tables are accessed.\n *\n * @param sql The SQL query to analyze\n * @param parameters Optional parameters for the SQL query\n * @param options Optional watch options that may contain explicit table list\n * @returns Array of table names that the query depends on\n */\n async resolveTables(sql, parameters, options) {\n const resolvedTables = options?.tables ? [...options.tables] : [];\n if (!options?.tables) {\n const explained = await this.getAll(`EXPLAIN ${sql}`, parameters);\n const rootPages = explained\n .filter((row) => row.opcode == 'OpenRead' && row.p3 == 0 && typeof row.p2 == 'number')\n .map((row) => row.p2);\n const tables = await this.getAll(`SELECT DISTINCT tbl_name FROM sqlite_master WHERE rootpage IN (SELECT json_each.value FROM json_each(?))`, [JSON.stringify(rootPages)]);\n for (const table of tables) {\n resolvedTables.push(table.tbl_name.replace(POWERSYNC_TABLE_MATCH, ''));\n }\n }\n return resolvedTables;\n }\n onChange(handlerOrOptions, maybeOptions) {\n if (handlerOrOptions && typeof handlerOrOptions === 'object' && 'onChange' in handlerOrOptions) {\n const handler = handlerOrOptions;\n const options = maybeOptions;\n return this.onChangeWithCallback(handler, options);\n }\n const options = handlerOrOptions;\n return this.onChangeWithAsyncGenerator(options);\n }\n /**\n * Invoke the provided callback on any changes to any of the specified tables.\n *\n * This is preferred over {@link watchWithCallback} when multiple queries need to be performed\n * together when data is changed.\n *\n * Note that the `onChange` callback member of the handler is required.\n *\n * @param handler Callbacks for handling change events and errors\n * @param options Options for configuring watch behavior\n * @returns A dispose function to stop watching for changes\n */\n onChangeWithCallback(handler, options) {\n const { onChange, onError = (e) => this.logger.error(e) } = handler ?? {};\n if (!onChange) {\n throw new Error('onChange is required');\n }\n const resolvedOptions = options ?? {};\n const watchedTables = new Set((resolvedOptions?.tables ?? []).flatMap((table) => [table, `ps_data__${table}`, `ps_data_local__${table}`]));\n const changedTables = new Set();\n const throttleMs = resolvedOptions.throttleMs ?? DEFAULT_WATCH_THROTTLE_MS;\n const executor = new ControlledExecutor(async (e) => {\n await onChange(e);\n });\n const flushTableUpdates = throttleTrailing(() => this.handleTableChanges(changedTables, watchedTables, (intersection) => {\n if (resolvedOptions?.signal?.aborted)\n return;\n executor.schedule({ changedTables: intersection });\n }), throttleMs);\n if (options?.triggerImmediate) {\n executor.schedule({ changedTables: [] });\n }\n const dispose = this.database.registerListener({\n tablesUpdated: async (update) => {\n try {\n this.processTableUpdates(update, changedTables);\n flushTableUpdates();\n }\n catch (error) {\n onError?.(error);\n }\n }\n });\n resolvedOptions.signal?.addEventListener('abort', () => {\n executor.dispose();\n dispose();\n });\n return () => dispose();\n }\n /**\n * Create a Stream of changes to any of the specified tables.\n *\n * This is preferred over {@link watchWithAsyncGenerator} when multiple queries need to be performed\n * together when data is changed.\n *\n * Note: do not declare this as `async *onChange` as it will not work in React Native.\n *\n * @param options Options for configuring watch behavior\n * @returns An AsyncIterable that yields change events whenever the specified tables change\n */\n onChangeWithAsyncGenerator(options) {\n const resolvedOptions = options ?? {};\n return new domExports.EventIterator((eventOptions) => {\n const dispose = this.onChangeWithCallback({\n onChange: (event) => {\n eventOptions.push(event);\n },\n onError: (error) => {\n eventOptions.fail(error);\n }\n }, options);\n resolvedOptions.signal?.addEventListener('abort', () => {\n eventOptions.stop();\n // Maybe fail?\n });\n return () => dispose();\n });\n }\n handleTableChanges(changedTables, watchedTables, onDetectedChanges) {\n if (changedTables.size > 0) {\n const intersection = Array.from(changedTables.values()).filter((change) => watchedTables.has(change));\n if (intersection.length) {\n onDetectedChanges(intersection);\n }\n }\n changedTables.clear();\n }\n processTableUpdates(updateNotification, changedTables) {\n const tables = isBatchedUpdateNotification(updateNotification)\n ? updateNotification.tables\n : [updateNotification.table];\n for (const table of tables) {\n changedTables.add(table);\n }\n }\n /**\n * @ignore\n */\n async executeReadOnly(sql, params) {\n await this.waitForReady();\n return this.database.readLock((tx) => tx.execute(sql, params));\n }\n}\n\nclass AbstractPowerSyncDatabaseOpenFactory {\n options;\n constructor(options) {\n this.options = options;\n options.logger = options.logger ?? Logger.get(`PowerSync ${this.options.dbFilename}`);\n }\n /**\n * Schema used for the local database.\n */\n get schema() {\n return this.options.schema;\n }\n generateOptions() {\n return {\n database: this.openDB(),\n ...this.options\n };\n }\n getInstance() {\n const options = this.generateOptions();\n return this.generateInstance(options);\n }\n}\n\nfunction runOnSchemaChange(callback, db, options) {\n const triggerWatchedQuery = () => {\n const abortController = new AbortController();\n let disposeSchemaListener = null;\n const stopWatching = () => {\n abortController.abort('Abort triggered');\n disposeSchemaListener?.();\n disposeSchemaListener = null;\n // Stop listening to upstream abort for this watch\n options?.signal?.removeEventListener('abort', stopWatching);\n };\n options?.signal?.addEventListener('abort', stopWatching);\n disposeSchemaListener = db.registerListener({\n schemaChanged: async () => {\n stopWatching();\n // Re trigger the watched query (recursively), setTimeout ensures that we don't modify the list of listeners while iterating through them\n setTimeout(() => triggerWatchedQuery(), 0);\n }\n });\n callback(abortController.signal);\n };\n triggerWatchedQuery();\n}\n\nfunction compilableQueryWatch(db, query, handler, options) {\n const { onResult, onError = (e) => { } } = handler ?? {};\n if (!onResult) {\n throw new Error('onResult is required');\n }\n const watchQuery = async (abortSignal) => {\n try {\n const toSql = query.compile();\n const resolvedTables = await db.resolveTables(toSql.sql, toSql.parameters, options);\n // Fetch initial data\n const result = await query.execute();\n onResult(result);\n db.onChangeWithCallback({\n onChange: async () => {\n try {\n const result = await query.execute();\n onResult(result);\n }\n catch (error) {\n onError(error);\n }\n },\n onError\n }, {\n ...(options ?? {}),\n tables: resolvedTables,\n // Override the abort signal since we intercept it\n signal: abortSignal\n });\n }\n catch (error) {\n onError(error);\n }\n };\n runOnSchemaChange(watchQuery, db, options);\n}\n\nconst MAX_OP_ID = '9223372036854775807';\n\nclass SqliteBucketStorage extends BaseObserver {\n db;\n logger;\n tableNames;\n _hasCompletedSync;\n updateListener;\n _clientId;\n constructor(db, logger = Logger.get('SqliteBucketStorage')) {\n super();\n this.db = db;\n this.logger = logger;\n this._hasCompletedSync = false;\n this.tableNames = new Set();\n this.updateListener = db.registerListener({\n tablesUpdated: (update) => {\n const tables = extractTableUpdates(update);\n if (tables.includes(PSInternalTable.CRUD)) {\n this.iterateListeners((l) => l.crudUpdate?.());\n }\n }\n });\n }\n async init() {\n this._hasCompletedSync = false;\n const existingTableRows = await this.db.getAll(`SELECT name FROM sqlite_master WHERE type='table' AND name GLOB 'ps_data_*'`);\n for (const row of existingTableRows ?? []) {\n this.tableNames.add(row.name);\n }\n }\n async dispose() {\n this.updateListener?.();\n }\n async _getClientId() {\n const row = await this.db.get('SELECT powersync_client_id() as client_id');\n return row['client_id'];\n }\n getClientId() {\n if (this._clientId == null) {\n this._clientId = this._getClientId();\n }\n return this._clientId;\n }\n getMaxOpId() {\n return MAX_OP_ID;\n }\n /**\n * Reset any caches.\n */\n startSession() { }\n async getBucketStates() {\n const result = await this.db.getAll(\"SELECT name as bucket, cast(last_op as TEXT) as op_id FROM ps_buckets WHERE pending_delete = 0 AND name != '$local'\");\n return result;\n }\n async getBucketOperationProgress() {\n const rows = await this.db.getAll('SELECT name, count_at_last, count_since_last FROM ps_buckets');\n return Object.fromEntries(rows.map((r) => [r.name, { atLast: r.count_at_last, sinceLast: r.count_since_last }]));\n }\n async saveSyncData(batch, fixedKeyFormat = false) {\n await this.writeTransaction(async (tx) => {\n for (const b of batch.buckets) {\n await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', [\n 'save',\n JSON.stringify({ buckets: [b.toJSON(fixedKeyFormat)] })\n ]);\n this.logger.debug(`Saved batch of data for bucket: ${b.bucket}, operations: ${b.data.length}`);\n }\n });\n }\n async removeBuckets(buckets) {\n for (const bucket of buckets) {\n await this.deleteBucket(bucket);\n }\n }\n /**\n * Mark a bucket for deletion.\n */\n async deleteBucket(bucket) {\n await this.writeTransaction(async (tx) => {\n await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', ['delete_bucket', bucket]);\n });\n this.logger.debug(`Done deleting bucket ${bucket}`);\n }\n async hasCompletedSync() {\n if (this._hasCompletedSync) {\n return true;\n }\n const r = await this.db.get(`SELECT powersync_last_synced_at() as synced_at`);\n const completed = r.synced_at != null;\n if (completed) {\n this._hasCompletedSync = true;\n }\n return completed;\n }\n async syncLocalDatabase(checkpoint, priority) {\n const r = await this.validateChecksums(checkpoint, priority);\n if (!r.checkpointValid) {\n this.logger.error('Checksums failed for', r.checkpointFailures);\n for (const b of r.checkpointFailures ?? []) {\n await this.deleteBucket(b);\n }\n return { ready: false, checkpointValid: false, checkpointFailures: r.checkpointFailures };\n }\n if (priority == null) {\n this.logger.debug(`Validated checksums checkpoint ${checkpoint.last_op_id}`);\n }\n else {\n this.logger.debug(`Validated checksums for partial checkpoint ${checkpoint.last_op_id}, priority ${priority}`);\n }\n let buckets = checkpoint.buckets;\n if (priority !== undefined) {\n buckets = buckets.filter((b) => hasMatchingPriority(priority, b));\n }\n const bucketNames = buckets.map((b) => b.bucket);\n await this.writeTransaction(async (tx) => {\n await tx.execute(`UPDATE ps_buckets SET last_op = ? WHERE name IN (SELECT json_each.value FROM json_each(?))`, [\n checkpoint.last_op_id,\n JSON.stringify(bucketNames)\n ]);\n if (priority == null && checkpoint.write_checkpoint) {\n await tx.execute(\"UPDATE ps_buckets SET last_op = ? WHERE name = '$local'\", [checkpoint.write_checkpoint]);\n }\n });\n const valid = await this.updateObjectsFromBuckets(checkpoint, priority);\n if (!valid) {\n return { ready: false, checkpointValid: true };\n }\n return {\n ready: true,\n checkpointValid: true\n };\n }\n /**\n * Atomically update the local state to the current checkpoint.\n *\n * This includes creating new tables, dropping old tables, and copying data over from the oplog.\n */\n async updateObjectsFromBuckets(checkpoint, priority) {\n let arg = '';\n if (priority !== undefined) {\n const affectedBuckets = [];\n for (const desc of checkpoint.buckets) {\n if (hasMatchingPriority(priority, desc)) {\n affectedBuckets.push(desc.bucket);\n }\n }\n arg = JSON.stringify({ priority, buckets: affectedBuckets });\n }\n return this.writeTransaction(async (tx) => {\n const { insertId: result } = await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', [\n 'sync_local',\n arg\n ]);\n if (result == 1) {\n if (priority == null) {\n const bucketToCount = Object.fromEntries(checkpoint.buckets.map((b) => [b.bucket, b.count]));\n // The two parameters could be replaced with one, but: https://github.com/powersync-ja/better-sqlite3/pull/6\n const jsonBucketCount = JSON.stringify(bucketToCount);\n await tx.execute(\"UPDATE ps_buckets SET count_since_last = 0, count_at_last = ?->name WHERE name != '$local' AND ?->name IS NOT NULL\", [jsonBucketCount, jsonBucketCount]);\n }\n return true;\n }\n else {\n return false;\n }\n });\n }\n async validateChecksums(checkpoint, priority) {\n if (priority !== undefined) {\n // Only validate the buckets within the priority we care about\n const newBuckets = checkpoint.buckets.filter((cs) => hasMatchingPriority(priority, cs));\n checkpoint = { ...checkpoint, buckets: newBuckets };\n }\n const rs = await this.db.execute('SELECT powersync_validate_checkpoint(?) as result', [\n JSON.stringify({ ...checkpoint })\n ]);\n const resultItem = rs.rows?.item(0);\n if (!resultItem) {\n return {\n checkpointValid: false,\n ready: false,\n checkpointFailures: []\n };\n }\n const result = JSON.parse(resultItem['result']);\n if (result['valid']) {\n return { ready: true, checkpointValid: true };\n }\n else {\n return {\n checkpointValid: false,\n ready: false,\n checkpointFailures: result['failed_buckets']\n };\n }\n }\n async updateLocalTarget(cb) {\n const rs1 = await this.db.getAll(\"SELECT target_op FROM ps_buckets WHERE name = '$local' AND target_op = CAST(? as INTEGER)\", [MAX_OP_ID]);\n if (!rs1.length) {\n // Nothing to update\n return false;\n }\n const rs = await this.db.getAll(\"SELECT seq FROM main.sqlite_sequence WHERE name = 'ps_crud'\");\n if (!rs.length) {\n // Nothing to update\n return false;\n }\n const seqBefore = rs[0]['seq'];\n const opId = await cb();\n return this.writeTransaction(async (tx) => {\n const anyData = await tx.execute('SELECT 1 FROM ps_crud LIMIT 1');\n if (anyData.rows?.length) {\n // if isNotEmpty\n this.logger.debug(`New data uploaded since write checkpoint ${opId} - need new write checkpoint`);\n return false;\n }\n const rs = await tx.execute(\"SELECT seq FROM main.sqlite_sequence WHERE name = 'ps_crud'\");\n if (!rs.rows?.length) {\n // assert isNotEmpty\n throw new Error('SQLite Sequence should not be empty');\n }\n const seqAfter = rs.rows?.item(0)['seq'];\n if (seqAfter != seqBefore) {\n this.logger.debug(`New data uploaded since write checpoint ${opId} - need new write checkpoint (sequence updated)`);\n // New crud data may have been uploaded since we got the checkpoint. Abort.\n return false;\n }\n this.logger.debug(`Updating target write checkpoint to ${opId}`);\n await tx.execute(\"UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'\", [opId]);\n return true;\n });\n }\n async nextCrudItem() {\n const next = await this.db.getOptional('SELECT * FROM ps_crud ORDER BY id ASC LIMIT 1');\n if (!next) {\n return;\n }\n return CrudEntry.fromRow(next);\n }\n async hasCrud() {\n const anyData = await this.db.getOptional('SELECT 1 FROM ps_crud LIMIT 1');\n return !!anyData;\n }\n /**\n * Get a batch of objects to send to the server.\n * When the objects are successfully sent to the server, call .complete()\n */\n async getCrudBatch(limit = 100) {\n if (!(await this.hasCrud())) {\n return null;\n }\n const crudResult = await this.db.getAll('SELECT * FROM ps_crud ORDER BY id ASC LIMIT ?', [limit]);\n const all = [];\n for (const row of crudResult) {\n all.push(CrudEntry.fromRow(row));\n }\n if (all.length === 0) {\n return null;\n }\n const last = all[all.length - 1];\n return {\n crud: all,\n haveMore: true,\n complete: async (writeCheckpoint) => {\n return this.writeTransaction(async (tx) => {\n await tx.execute('DELETE FROM ps_crud WHERE id <= ?', [last.clientId]);\n if (writeCheckpoint) {\n const crudResult = await tx.execute('SELECT 1 FROM ps_crud LIMIT 1');\n if (crudResult.rows?.length) {\n await tx.execute(\"UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'\", [\n writeCheckpoint\n ]);\n }\n }\n else {\n await tx.execute(\"UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'\", [\n this.getMaxOpId()\n ]);\n }\n });\n }\n };\n }\n async writeTransaction(callback, options) {\n return this.db.writeTransaction(callback, options);\n }\n /**\n * Set a target checkpoint.\n */\n async setTargetCheckpoint(checkpoint) {\n // No-op for now\n }\n async control(op, payload) {\n return await this.writeTransaction(async (tx) => {\n const [[raw]] = await tx.executeRaw('SELECT powersync_control(?, ?)', [op, payload]);\n return raw;\n });\n }\n async hasMigratedSubkeys() {\n const { r } = await this.db.get('SELECT EXISTS(SELECT * FROM ps_kv WHERE key = ?) as r', [\n SqliteBucketStorage._subkeyMigrationKey\n ]);\n return r != 0;\n }\n async migrateToFixedSubkeys() {\n await this.writeTransaction(async (tx) => {\n await tx.execute('UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);');\n await tx.execute('INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);', [\n SqliteBucketStorage._subkeyMigrationKey,\n '1'\n ]);\n });\n }\n static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';\n}\nfunction hasMatchingPriority(priority, bucket) {\n return bucket.priority != null && bucket.priority <= priority;\n}\n\n// TODO JSON\nclass SyncDataBatch {\n buckets;\n static fromJSON(json) {\n return new SyncDataBatch(json.buckets.map((bucket) => SyncDataBucket.fromRow(bucket)));\n }\n constructor(buckets) {\n this.buckets = buckets;\n }\n}\n\n/**\n * Thrown when an underlying database connection is closed.\n * This is particularly relevant when worker connections are marked as closed while\n * operations are still in progress.\n */\nclass ConnectionClosedError extends Error {\n static NAME = 'ConnectionClosedError';\n static MATCHES(input) {\n /**\n * If there are weird package issues which cause multiple versions of classes to be present, the instanceof\n * check might fail. This also performs a failsafe check.\n * This might also happen if the Error is serialized and parsed over a bridging channel like a MessagePort.\n */\n return (input instanceof ConnectionClosedError || (input instanceof Error && input.name == ConnectionClosedError.NAME));\n }\n constructor(message) {\n super(message);\n this.name = ConnectionClosedError.NAME;\n }\n}\n\n/**\n * Instructs PowerSync to sync data into a \"raw\" table.\n *\n * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow\n * using client-side table and column constraints.\n *\n * To collect local writes to raw tables with PowerSync, custom triggers are required. See\n * {@link https://docs.powersync.com/usage/use-case-examples/raw-tables the documentation} for details and an example on\n * using raw tables.\n *\n * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.\n *\n * @experimental Please note that this feature is experimental at the moment, and not covered by PowerSync semver or\n * stability guarantees.\n */\nclass RawTable {\n /**\n * The name of the table.\n *\n * This does not have to match the actual table name in the schema - {@link put} and {@link delete} are free to use\n * another table. Instead, this name is used by the sync client to recognize that operations on this table (as it\n * appears in the source / backend database) are to be handled specially.\n */\n name;\n put;\n delete;\n constructor(name, type) {\n this.name = name;\n this.put = type.put;\n this.delete = type.delete;\n }\n}\n\n/**\n * A schema is a collection of tables. It is used to define the structure of a database.\n */\nclass Schema {\n /*\n Only available when constructing with mapped typed definition columns\n */\n types;\n props;\n tables;\n rawTables;\n constructor(tables) {\n if (Array.isArray(tables)) {\n /*\n We need to validate that the tables have a name here because a user could pass in an array\n of Tables that don't have a name because they are using the V2 syntax.\n Therefore, 'convertToClassicTables' won't be called on the tables resulting in a runtime error.\n */\n for (const table of tables) {\n if (table.name === '') {\n throw new Error(\"It appears you are trying to create a new Schema with an array instead of an object. Passing in an object instead of an array into 'new Schema()' may resolve your issue.\");\n }\n }\n this.tables = tables;\n }\n else {\n // Update the table entries with the provided table name key\n this.props = Object.fromEntries(Object.entries(tables).map(([tableName, table]) => [tableName, table.copyWithName(tableName)]));\n this.tables = Object.values(this.props);\n }\n this.rawTables = [];\n }\n /**\n * Adds raw tables to this schema. Raw tables are identified by their name, but entirely managed by the application\n * developer instead of automatically by PowerSync.\n * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow\n * using client-side table and column constraints.\n * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.\n *\n * @param tables An object of (table name, raw table definition) entries.\n * @experimental Note that the raw tables API is still experimental and may change in the future.\n */\n withRawTables(tables) {\n for (const [name, rawTableDefinition] of Object.entries(tables)) {\n this.rawTables.push(new RawTable(name, rawTableDefinition));\n }\n }\n validate() {\n for (const table of this.tables) {\n table.validate();\n }\n }\n toJSON() {\n return {\n tables: this.tables.map((t) => t.toJSON()),\n raw_tables: this.rawTables\n };\n }\n}\n\n/**\n Generate a new table from the columns and indexes\n @deprecated You should use {@link Table} instead as it now allows TableV2 syntax.\n This will be removed in the next major release.\n*/\nclass TableV2 extends Table {\n}\n\nfunction sanitizeString(input) {\n return `'${input.replace(/'/g, \"''\")}'`;\n}\n/**\n * Helper function for sanitizing UUID input strings.\n * Typically used with {@link sanitizeSQL}.\n */\nfunction sanitizeUUID(uuid) {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n const isValid = uuidRegex.test(uuid);\n if (!isValid) {\n throw new Error(`${uuid} is not a valid UUID`);\n }\n return uuid;\n}\n/**\n * SQL string template function for {@link TrackDiffOptions#when} and {@link CreateDiffTriggerOptions#when}.\n *\n * This function performs basic string interpolation for SQLite WHEN clauses.\n *\n * **String placeholders:**\n * - All string values passed as placeholders are automatically wrapped in single quotes (`'`).\n * - Do not manually wrap placeholders in single quotes in your template string; the function will handle quoting and escaping for you.\n * - Any single quotes within the string value are escaped by doubling them (`''`), as required by SQL syntax.\n *\n * **Other types:**\n * - `null` and `undefined` are converted to SQL `NULL`.\n * - Objects are stringified using `JSON.stringify()` and wrapped in single quotes, with any single quotes inside the stringified value escaped.\n * - Numbers and other primitive types are inserted directly.\n *\n * **Usage example:**\n * ```typescript\n * const myID = \"O'Reilly\";\n * const clause = sanitizeSQL`New.id = ${myID}`;\n * // Result: \"New.id = 'O''Reilly'\"\n * ```\n *\n * Avoid manually quoting placeholders:\n * ```typescript\n * // Incorrect:\n * sanitizeSQL`New.id = '${myID}'` // Produces double quotes: New.id = ''O''Reilly''\n * ```\n */\nfunction sanitizeSQL(strings, ...values) {\n let result = '';\n strings.forEach((str, i) => {\n result += str;\n if (i < values.length) {\n // For SQL, escape single quotes in string values\n const value = values[i];\n if (typeof value == 'string') {\n result += sanitizeString(value);\n }\n else if (value == null) {\n result += 'NULL';\n }\n else if (typeof value == 'object') {\n // Stringify the object and escape single quotes in the result\n const stringified = JSON.stringify(value);\n result += sanitizeString(stringified);\n }\n else {\n result += value;\n }\n }\n });\n return result;\n}\n\n/**\n * Performs a {@link AbstractPowerSyncDatabase.getAll} operation for a watched query.\n */\nclass GetAllQuery {\n options;\n constructor(options) {\n this.options = options;\n }\n compile() {\n return {\n sql: this.options.sql,\n parameters: this.options.parameters ?? []\n };\n }\n async execute(options) {\n const { db } = options;\n const { sql, parameters = [] } = this.compile();\n const rawResult = await db.getAll(sql, [...parameters]);\n if (this.options.mapper) {\n return rawResult.map(this.options.mapper);\n }\n return rawResult;\n }\n}\n\nconst TypedLogger = Logger;\nconst LogLevel = {\n TRACE: TypedLogger.TRACE,\n DEBUG: TypedLogger.DEBUG,\n INFO: TypedLogger.INFO,\n TIME: TypedLogger.TIME,\n WARN: TypedLogger.WARN,\n ERROR: TypedLogger.ERROR,\n OFF: TypedLogger.OFF\n};\n/**\n * Retrieves the base (default) logger instance.\n *\n * This base logger controls the default logging configuration and is shared\n * across all loggers created with `createLogger`. Adjusting settings on this\n * base logger affects all loggers derived from it unless explicitly overridden.\n *\n */\nfunction createBaseLogger() {\n return Logger;\n}\n/**\n * Creates and configures a new named logger based on the base logger.\n *\n * Named loggers allow specific modules or areas of your application to have\n * their own logging levels and behaviors. These loggers inherit configuration\n * from the base logger by default but can override settings independently.\n */\nfunction createLogger(name, options = {}) {\n const logger = Logger.get(name);\n if (options.logLevel) {\n logger.setLevel(options.logLevel);\n }\n return logger;\n}\n\nconst parseQuery = (query, parameters) => {\n let sqlStatement;\n if (typeof query == 'string') {\n sqlStatement = query;\n }\n else {\n const hasAdditionalParameters = parameters.length > 0;\n if (hasAdditionalParameters) {\n throw new Error('You cannot pass parameters to a compiled query.');\n }\n const compiled = query.compile();\n sqlStatement = compiled.sql;\n parameters = compiled.parameters;\n }\n return { sqlStatement, parameters: parameters };\n};\n\nexport { ATTACHMENT_TABLE, AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, AttachmentContext, AttachmentQueue, AttachmentService, AttachmentState, AttachmentTable, BaseObserver, Column, ColumnType, ConnectionClosedError, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_PRESSURE_LIMITS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DataStream, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, EncodingType, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, MEMORY_TRIGGER_CLAIM_MANAGER, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RawTable, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, SyncingService, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, attachmentFromSql, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, mutexRunExclusive, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID };\n//# sourceMappingURL=bundle.mjs.map\n","import * as SQLite from '@journeyapps/wa-sqlite';\nimport { BaseObserver } from '@powersync/common';\nimport { Mutex } from 'async-mutex';\n/**\n * List of currently tested virtual filesystems\n */\nexport var WASQLiteVFS;\n(function (WASQLiteVFS) {\n WASQLiteVFS[\"IDBBatchAtomicVFS\"] = \"IDBBatchAtomicVFS\";\n WASQLiteVFS[\"OPFSCoopSyncVFS\"] = \"OPFSCoopSyncVFS\";\n WASQLiteVFS[\"AccessHandlePoolVFS\"] = \"AccessHandlePoolVFS\";\n})(WASQLiteVFS || (WASQLiteVFS = {}));\n/**\n * @internal\n */\nexport const AsyncWASQLiteModuleFactory = async () => {\n const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');\n return factory();\n};\n/**\n * @internal\n */\nexport const MultiCipherAsyncWASQLiteModuleFactory = async () => {\n const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs');\n return factory();\n};\n/**\n * @internal\n */\nexport const SyncWASQLiteModuleFactory = async () => {\n const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite.mjs');\n return factory();\n};\n/**\n * @internal\n */\nexport const MultiCipherSyncWASQLiteModuleFactory = async () => {\n const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs');\n return factory();\n};\n/**\n * @internal\n */\nexport const DEFAULT_MODULE_FACTORIES = {\n [WASQLiteVFS.IDBBatchAtomicVFS]: async (options) => {\n let module;\n if (options.encryptionKey) {\n module = await MultiCipherAsyncWASQLiteModuleFactory();\n }\n else {\n module = await AsyncWASQLiteModuleFactory();\n }\n const { IDBBatchAtomicVFS } = await import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');\n return {\n module,\n // @ts-expect-error The types for this static method are missing upstream\n vfs: await IDBBatchAtomicVFS.create(options.dbFileName, module, { lockPolicy: 'exclusive' })\n };\n },\n [WASQLiteVFS.AccessHandlePoolVFS]: async (options) => {\n let module;\n if (options.encryptionKey) {\n module = await MultiCipherSyncWASQLiteModuleFactory();\n }\n else {\n module = await SyncWASQLiteModuleFactory();\n }\n // @ts-expect-error The types for this static method are missing upstream\n const { AccessHandlePoolVFS } = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');\n return {\n module,\n vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)\n };\n },\n [WASQLiteVFS.OPFSCoopSyncVFS]: async (options) => {\n let module;\n if (options.encryptionKey) {\n module = await MultiCipherSyncWASQLiteModuleFactory();\n }\n else {\n module = await SyncWASQLiteModuleFactory();\n }\n // @ts-expect-error The types for this static method are missing upstream\n const { OPFSCoopSyncVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');\n const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);\n return {\n module,\n vfs\n };\n }\n};\n/**\n * @internal\n * WA-SQLite connection which directly interfaces with WA-SQLite.\n * This is usually instantiated inside a worker.\n */\nexport class WASqliteConnection extends BaseObserver {\n options;\n _sqliteAPI = null;\n _dbP = null;\n _moduleFactory;\n updatedTables;\n updateTimer;\n statementMutex;\n broadcastChannel;\n /**\n * Unique id for this specific connection. This is used to prevent broadcast table change\n * notification loops.\n */\n connectionId;\n _holdCounter;\n _holdId;\n constructor(options) {\n super();\n this.options = options;\n this.updatedTables = new Set();\n this.updateTimer = null;\n this.broadcastChannel = null;\n this.connectionId = new Date().valueOf() + Math.random();\n this.statementMutex = new Mutex();\n this._moduleFactory = DEFAULT_MODULE_FACTORIES[this.options.vfs];\n this._holdCounter = 0;\n this._holdId = null;\n }\n /**\n * Gets the id for the current hold.\n * This can be used to check for invalid states.\n */\n get currentHoldId() {\n return this._holdId;\n }\n get sqliteAPI() {\n if (!this._sqliteAPI) {\n throw new Error(`Initialization has not completed`);\n }\n return this._sqliteAPI;\n }\n get dbP() {\n if (!this._dbP) {\n throw new Error(`Initialization has not completed`);\n }\n return this._dbP;\n }\n /**\n * Checks if the database connection is in autocommit mode.\n * @returns true if in autocommit mode, false if in a transaction\n */\n async isAutoCommit() {\n return this.sqliteAPI.get_autocommit(this.dbP) != 0;\n }\n async markHold() {\n const previousHoldId = this._holdId;\n this._holdId = `${++this._holdCounter}`;\n if (previousHoldId) {\n await this.iterateAsyncListeners(async (cb) => cb.holdOverwritten?.(previousHoldId));\n }\n return this._holdId;\n }\n async releaseHold(holdId) {\n if (holdId != this._holdId) {\n throw new Error(`Invalid hold state, expected ${this._holdId} but got ${holdId}`);\n }\n this._holdId = null;\n }\n async openDB() {\n this._dbP = await this.sqliteAPI.open_v2(this.options.dbFilename);\n return this._dbP;\n }\n async executeEncryptionPragma() {\n if (this.options.encryptionKey) {\n await this.executeSingleStatement(`PRAGMA key = \"${this.options.encryptionKey}\"`);\n }\n return;\n }\n async openSQLiteAPI() {\n const { module, vfs } = await this._moduleFactory({\n dbFileName: this.options.dbFilename,\n encryptionKey: this.options.encryptionKey\n });\n const sqlite3 = SQLite.Factory(module);\n sqlite3.vfs_register(vfs, true);\n /**\n * Register the PowerSync core SQLite extension\n */\n module.ccall('powersync_init_static', 'int', []);\n /**\n * Create the multiple cipher vfs if an encryption key is provided\n */\n if (this.options.encryptionKey) {\n const createResult = module.ccall('sqlite3mc_vfs_create', 'int', ['string', 'int'], [this.options.dbFilename, 1]);\n if (createResult !== 0) {\n throw new Error('Failed to create multiple cipher vfs, Database encryption will not work');\n }\n }\n return sqlite3;\n }\n registerBroadcastListeners() {\n this.broadcastChannel = new BroadcastChannel(`${this.options.dbFilename}-table-updates`);\n this.broadcastChannel.addEventListener('message', (event) => {\n const data = event.data;\n if (this.connectionId == data.connectionId) {\n // Ignore messages from the same connection\n return;\n }\n // Ensuring that we don't rebroadcast the same message\n this.queueTableUpdate(data.changedTables, false);\n });\n }\n queueTableUpdate(tableNames, shouldBroadcast = true) {\n tableNames.forEach((tableName) => this.updatedTables.add(tableName));\n if (this.updateTimer == null) {\n this.updateTimer = setTimeout(() => this.fireUpdates(shouldBroadcast), 0);\n }\n }\n async init() {\n this._sqliteAPI = await this.openSQLiteAPI();\n await this.openDB();\n this.registerBroadcastListeners();\n await this.executeSingleStatement(`PRAGMA temp_store = ${this.options.temporaryStorage};`);\n await this.executeEncryptionPragma();\n await this.executeSingleStatement(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);\n this.sqliteAPI.update_hook(this.dbP, (updateType, dbName, tableName) => {\n if (!tableName) {\n return;\n }\n const changedTables = new Set([tableName]);\n this.queueTableUpdate(changedTables);\n });\n }\n async getConfig() {\n return this.options;\n }\n fireUpdates(shouldBroadcast = true) {\n this.updateTimer = null;\n const event = { tables: [...this.updatedTables], groupedUpdates: {}, rawUpdates: [] };\n // Share to other connections\n if (shouldBroadcast) {\n this.broadcastChannel.postMessage({\n changedTables: this.updatedTables,\n connectionId: this.connectionId\n });\n }\n this.updatedTables.clear();\n this.iterateListeners((cb) => cb.tablesUpdated?.(event));\n }\n /**\n * This executes SQL statements in a batch.\n */\n async executeBatch(sql, bindings) {\n return this.acquireExecuteLock(async () => {\n let affectedRows = 0;\n try {\n await this.executeSingleStatement('BEGIN TRANSACTION');\n const wrappedBindings = bindings ? bindings : [];\n for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {\n if (stmt === null) {\n return {\n rowsAffected: 0,\n rows: { _array: [], length: 0 }\n };\n }\n //Prepare statement once\n for (const binding of wrappedBindings) {\n // TODO not sure why this is needed currently, but booleans break\n for (let i = 0; i < binding.length; i++) {\n const b = binding[i];\n if (typeof b == 'boolean') {\n binding[i] = b ? 1 : 0;\n }\n }\n if (bindings) {\n this.sqliteAPI.bind_collection(stmt, binding);\n }\n const result = await this.sqliteAPI.step(stmt);\n if (result === SQLite.SQLITE_DONE) {\n //The value returned by sqlite3_changes() immediately after an INSERT, UPDATE or DELETE statement run on a view is always zero.\n affectedRows += this.sqliteAPI.changes(this.dbP);\n }\n this.sqliteAPI.reset(stmt);\n }\n }\n await this.executeSingleStatement('COMMIT');\n }\n catch (err) {\n await this.executeSingleStatement('ROLLBACK');\n return {\n rowsAffected: 0,\n rows: { _array: [], length: 0 }\n };\n }\n const result = {\n rowsAffected: affectedRows,\n rows: { _array: [], length: 0 }\n };\n return result;\n });\n }\n /**\n * This executes single SQL statements inside a requested lock.\n */\n async execute(sql, bindings) {\n // Running multiple statements on the same connection concurrently should not be allowed\n return this.acquireExecuteLock(async () => {\n return this.executeSingleStatement(sql, bindings);\n });\n }\n async executeRaw(sql, bindings) {\n return this.acquireExecuteLock(async () => {\n return this.executeSingleStatementRaw(sql, bindings);\n });\n }\n async close() {\n this.broadcastChannel?.close();\n await this.acquireExecuteLock(async () => {\n /**\n * Running the close operation inside the same execute mutex prevents errors like:\n * ```\n * unable to close due to unfinalized statements or unfinished backups\n * ```\n */\n await this.sqliteAPI.close(this.dbP);\n });\n }\n async registerOnTableChange(callback) {\n return this.registerListener({\n tablesUpdated: (event) => callback(event)\n });\n }\n /**\n * This requests a lock for executing statements.\n * Should only be used internally.\n */\n acquireExecuteLock = (callback) => {\n return this.statementMutex.runExclusive(callback);\n };\n /**\n * This executes a single statement using SQLite3.\n */\n async executeSingleStatement(sql, bindings) {\n const results = await this._execute(sql, bindings);\n const rows = [];\n for (const resultSet of results) {\n for (const row of resultSet.rows) {\n const outRow = {};\n resultSet.columns.forEach((key, index) => {\n outRow[key] = row[index];\n });\n rows.push(outRow);\n }\n }\n const result = {\n insertId: this.sqliteAPI.last_insert_id(this.dbP),\n rowsAffected: this.sqliteAPI.changes(this.dbP),\n rows: {\n _array: rows,\n length: rows.length\n }\n };\n return result;\n }\n /**\n * This executes a single statement using SQLite3 and returns the results as an array of arrays.\n */\n async executeSingleStatementRaw(sql, bindings) {\n const results = await this._execute(sql, bindings);\n return results.flatMap((resultset) => resultset.rows.map((row) => resultset.columns.map((_, index) => row[index])));\n }\n async _execute(sql, bindings) {\n const results = [];\n for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {\n let columns;\n const wrappedBindings = bindings ? [bindings] : [[]];\n for (const binding of wrappedBindings) {\n // TODO not sure why this is needed currently, but booleans break\n binding.forEach((b, index, arr) => {\n if (typeof b == 'boolean') {\n arr[index] = b ? 1 : 0;\n }\n });\n this.sqliteAPI.reset(stmt);\n if (bindings) {\n this.sqliteAPI.bind_collection(stmt, binding);\n }\n const rows = [];\n while ((await this.sqliteAPI.step(stmt)) === SQLite.SQLITE_ROW) {\n const row = this.sqliteAPI.row(stmt);\n rows.push(row);\n }\n columns = columns ?? this.sqliteAPI.column_names(stmt);\n if (columns.length) {\n results.push({ columns, rows });\n }\n }\n // When binding parameters, only a single statement is executed.\n if (bindings) {\n break;\n }\n }\n return results;\n }\n}\n","export const getNavigatorLocks = () => {\n if ('locks' in navigator && navigator.locks) {\n return navigator.locks;\n }\n throw new Error('Navigator locks are not available in an insecure context. Use a secure context such as HTTPS or http://localhost.');\n};\n","export class SharedWASQLiteConnection {\n options;\n isClosing;\n // Keeps track if this current hold if the shared connection has a hold\n activeHoldId;\n constructor(options) {\n this.options = options;\n // Add this client ID to the set of known clients\n this.clientIds.add(options.clientId);\n this.isClosing = false;\n this.activeHoldId = null;\n }\n get logger() {\n return this.options.logger;\n }\n get dbEntry() {\n return this.options.dbMap.get(this.options.dbFilename);\n }\n get connection() {\n return this.dbEntry.db;\n }\n get clientIds() {\n return this.dbEntry.clientIds;\n }\n async init() {\n // No-op since the connection is already initialized when it was created\n }\n async markHold() {\n this.activeHoldId = await this.connection.markHold();\n return this.activeHoldId;\n }\n async releaseHold(id) {\n try {\n await this.connection.releaseHold(id);\n }\n finally {\n this.activeHoldId = null;\n }\n }\n async isAutoCommit() {\n return this.connection.isAutoCommit();\n }\n /**\n * Handles closing of a shared connection.\n * The connection is only closed if there are no active clients using it.\n */\n async close() {\n // This prevents further statements on this connection from being executed\n this.isClosing = true;\n const { clientIds, logger } = this;\n const { clientId, dbFilename, dbMap } = this.options;\n logger.debug(`Close requested from client ${clientId} of ${[...clientIds]}`);\n clientIds.delete(clientId);\n if (this.activeHoldId) {\n // We can't cleanup here since we're not in a lock context.\n // The cleanup will occur once a new hold is acquired.\n this.logger.info(`Hold ${this.activeHoldId} was still active when the connection was closed. Cleanup will occur once a new hold is acquired.`);\n }\n if (clientIds.size == 0) {\n logger.debug(`Closing connection to ${this.options}.`);\n const connection = this.connection;\n dbMap.delete(dbFilename);\n await connection.close();\n return;\n }\n logger.debug(`Connection to ${dbFilename} not closed yet due to active clients.`);\n return;\n }\n async withClosing(action) {\n if (this.isClosing) {\n throw new Error('Connection is closing');\n }\n return action();\n }\n async execute(sql, params) {\n return this.withClosing(() => this.connection.execute(sql, params));\n }\n async executeRaw(sql, params) {\n return this.withClosing(() => this.connection.executeRaw(sql, params));\n }\n executeBatch(sql, params) {\n return this.withClosing(() => this.connection.executeBatch(sql, params));\n }\n registerOnTableChange(callback) {\n return this.connection.registerOnTableChange(callback);\n }\n getConfig() {\n return this.connection.getConfig();\n }\n}\n","import * as Comlink from 'comlink';\nimport { WASqliteConnection } from '../../db/adapters/wa-sqlite/WASQLiteConnection.js';\n/**\n * A Small proxy wrapper around the WASqliteConnection.\n * This ensures that certain return types are properly proxied.\n */\nexport class WorkerWASQLiteConnection extends WASqliteConnection {\n async registerOnTableChange(callback) {\n // Proxy the callback remove function\n return Comlink.proxy(await super.registerOnTableChange(callback));\n }\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Check if module exists (development only)\n\tif (__webpack_modules__[moduleId] === undefined) {\n\t\tvar e = new Error(\"Cannot find module '\" + moduleId + \"'\");\n\t\te.code = 'MODULE_NOT_FOUND';\n\t\tthrow e;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"worker/\" + chunkId + \".umd.js\";\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT')\n\t\tscriptUrl = document.currentScript.src;\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) {\n\t\t\tvar i = scripts.length - 1;\n\t\t\twhile (i > -1 && (!scriptUrl || !/^http(s?):/.test(scriptUrl))) scriptUrl = scripts[i--].src;\n\t\t}\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/^blob:/, \"\").replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl + \"../\";","__webpack_require__.b = self.location + \"/../../\";\n\n// object to store loaded chunks\n// \"1\" means \"already loaded\"\nvar installedChunks = {\n\t\"WASQLiteDB\": 1\n};\n\n// importScripts chunk loading\nvar installChunk = (data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\tfor(var moduleId in moreModules) {\n\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t}\n\t}\n\tif(runtime) runtime(__webpack_require__);\n\twhile(chunkIds.length)\n\t\tinstalledChunks[chunkIds.pop()] = 1;\n\tparentChunkLoadingFunction(data);\n};\n__webpack_require__.f.i = (chunkId, promises) => {\n\t// \"1\" is the signal for \"already loaded\"\n\tif(!installedChunks[chunkId]) {\n\t\tif(true) { // all chunks have JS\n\t\t\timportScripts(__webpack_require__.p + __webpack_require__.u(chunkId));\n\t\t}\n\t}\n};\n\nvar chunkLoadingGlobal = self[\"webpackChunksdk_web\"] = self[\"webpackChunksdk_web\"] || [];\nvar parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);\nchunkLoadingGlobal.push = installChunk;\n\n// no HMR\n\n// no HMR manifest","/**\n * Supports both shared and dedicated workers, based on how the worker is constructed (new SharedWorker vs new Worker()).\n */\nimport '@journeyapps/wa-sqlite';\nimport { createBaseLogger, createLogger } from '@powersync/common';\nimport * as Comlink from 'comlink';\nimport { getNavigatorLocks } from '../../shared/navigator.js';\nimport { SharedWASQLiteConnection } from './SharedWASQLiteConnection.js';\nimport { WorkerWASQLiteConnection } from './WorkerWASQLiteConnection.js';\nconst baseLogger = createBaseLogger();\nbaseLogger.useDefaults();\nconst logger = createLogger('db-worker');\nconst DBMap = new Map();\nconst OPEN_DB_LOCK = 'open-wasqlite-db';\nlet nextClientId = 1;\nconst openDBShared = async (options) => {\n // Prevent multiple simultaneous opens from causing race conditions\n return getNavigatorLocks().request(OPEN_DB_LOCK, async () => {\n const clientId = nextClientId++;\n const { dbFilename, logLevel } = options;\n logger.setLevel(logLevel);\n if (!DBMap.has(dbFilename)) {\n const clientIds = new Set();\n // This format returns proxy objects for function callbacks\n const connection = new WorkerWASQLiteConnection(options);\n await connection.init();\n connection.registerListener({\n holdOverwritten: async () => {\n /**\n * The previous hold has been overwritten, without being released.\n * we need to cleanup any resources associated with it.\n * We can perform a rollback to release any potential transactions that were started.\n */\n await connection.execute('ROLLBACK').catch(() => { });\n }\n });\n DBMap.set(dbFilename, {\n clientIds,\n db: connection\n });\n }\n // Associates this clientId with the shared connection entry\n const sharedConnection = new SharedWASQLiteConnection({\n dbMap: DBMap,\n dbFilename,\n clientId,\n logger\n });\n return Comlink.proxy(sharedConnection);\n });\n};\n// Check if we're in a SharedWorker context\nif (typeof SharedWorkerGlobalScope !== 'undefined') {\n const _self = self;\n _self.onconnect = function (event) {\n const port = event.ports[0];\n Comlink.expose(openDBShared, port);\n };\n}\nelse {\n // A dedicated worker can be shared externally\n Comlink.expose(openDBShared);\n}\naddEventListener('unload', () => {\n Array.from(DBMap.values()).forEach(async (dbConnection) => {\n const { db } = dbConnection;\n db.close?.();\n });\n});\n"],"names":[],"ignoreList":[],"sourceRoot":""}
|
|
1
|
+
{"version":3,"file":"worker/WASQLiteDB.umd.js","mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;AClSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACrWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACl7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;AClRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;AChZA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACxicA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACRA;AACA;AACA;AACA;AACA;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACPA;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","sources":["webpack://sdk_web/../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs","webpack://sdk_web/../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs","webpack://sdk_web/../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js","webpack://sdk_web/../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js","webpack://sdk_web/./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js","webpack://sdk_web/./lib/src/shared/navigator.js","webpack://sdk_web/./lib/src/worker/db/SharedWASQLiteConnection.js","webpack://sdk_web/./lib/src/worker/db/WorkerWASQLiteConnection.js","webpack://sdk_web/../common/dist/bundle.mjs","webpack://sdk_web/webpack/bootstrap","webpack://sdk_web/webpack/runtime/define property getters","webpack://sdk_web/webpack/runtime/ensure chunk","webpack://sdk_web/webpack/runtime/get javascript chunk filename","webpack://sdk_web/webpack/runtime/global","webpack://sdk_web/webpack/runtime/hasOwnProperty shorthand","webpack://sdk_web/webpack/runtime/make namespace object","webpack://sdk_web/webpack/runtime/publicPath","webpack://sdk_web/webpack/runtime/importScripts chunk loading","webpack://sdk_web/./lib/src/worker/db/WASQLiteDB.worker.js"],"sourcesContent":["const E_TIMEOUT = new Error('timeout while waiting for mutex to become available');\nconst E_ALREADY_LOCKED = new Error('mutex already locked');\nconst E_CANCELED = new Error('request for lock canceled');\n\nvar __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Semaphore {\n constructor(_value, _cancelError = E_CANCELED) {\n this._value = _value;\n this._cancelError = _cancelError;\n this._queue = [];\n this._weightedWaiters = [];\n }\n acquire(weight = 1, priority = 0) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n return new Promise((resolve, reject) => {\n const task = { resolve, reject, weight, priority };\n const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority);\n if (i === -1 && weight <= this._value) {\n // Needs immediate dispatch, skip the queue\n this._dispatchItem(task);\n }\n else {\n this._queue.splice(i + 1, 0, task);\n }\n });\n }\n runExclusive(callback_1) {\n return __awaiter$2(this, arguments, void 0, function* (callback, weight = 1, priority = 0) {\n const [value, release] = yield this.acquire(weight, priority);\n try {\n return yield callback(value);\n }\n finally {\n release();\n }\n });\n }\n waitForUnlock(weight = 1, priority = 0) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n if (this._couldLockImmediately(weight, priority)) {\n return Promise.resolve();\n }\n else {\n return new Promise((resolve) => {\n if (!this._weightedWaiters[weight - 1])\n this._weightedWaiters[weight - 1] = [];\n insertSorted(this._weightedWaiters[weight - 1], { resolve, priority });\n });\n }\n }\n isLocked() {\n return this._value <= 0;\n }\n getValue() {\n return this._value;\n }\n setValue(value) {\n this._value = value;\n this._dispatchQueue();\n }\n release(weight = 1) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n this._value += weight;\n this._dispatchQueue();\n }\n cancel() {\n this._queue.forEach((entry) => entry.reject(this._cancelError));\n this._queue = [];\n }\n _dispatchQueue() {\n this._drainUnlockWaiters();\n while (this._queue.length > 0 && this._queue[0].weight <= this._value) {\n this._dispatchItem(this._queue.shift());\n this._drainUnlockWaiters();\n }\n }\n _dispatchItem(item) {\n const previousValue = this._value;\n this._value -= item.weight;\n item.resolve([previousValue, this._newReleaser(item.weight)]);\n }\n _newReleaser(weight) {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n this.release(weight);\n };\n }\n _drainUnlockWaiters() {\n if (this._queue.length === 0) {\n for (let weight = this._value; weight > 0; weight--) {\n const waiters = this._weightedWaiters[weight - 1];\n if (!waiters)\n continue;\n waiters.forEach((waiter) => waiter.resolve());\n this._weightedWaiters[weight - 1] = [];\n }\n }\n else {\n const queuedPriority = this._queue[0].priority;\n for (let weight = this._value; weight > 0; weight--) {\n const waiters = this._weightedWaiters[weight - 1];\n if (!waiters)\n continue;\n const i = waiters.findIndex((waiter) => waiter.priority <= queuedPriority);\n (i === -1 ? waiters : waiters.splice(0, i))\n .forEach((waiter => waiter.resolve()));\n }\n }\n }\n _couldLockImmediately(weight, priority) {\n return (this._queue.length === 0 || this._queue[0].priority < priority) &&\n weight <= this._value;\n }\n}\nfunction insertSorted(a, v) {\n const i = findIndexFromEnd(a, (other) => v.priority <= other.priority);\n a.splice(i + 1, 0, v);\n}\nfunction findIndexFromEnd(a, predicate) {\n for (let i = a.length - 1; i >= 0; i--) {\n if (predicate(a[i])) {\n return i;\n }\n }\n return -1;\n}\n\nvar __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Mutex {\n constructor(cancelError) {\n this._semaphore = new Semaphore(1, cancelError);\n }\n acquire() {\n return __awaiter$1(this, arguments, void 0, function* (priority = 0) {\n const [, releaser] = yield this._semaphore.acquire(1, priority);\n return releaser;\n });\n }\n runExclusive(callback, priority = 0) {\n return this._semaphore.runExclusive(() => callback(), 1, priority);\n }\n isLocked() {\n return this._semaphore.isLocked();\n }\n waitForUnlock(priority = 0) {\n return this._semaphore.waitForUnlock(1, priority);\n }\n release() {\n if (this._semaphore.isLocked())\n this._semaphore.release();\n }\n cancel() {\n return this._semaphore.cancel();\n }\n}\n\nvar __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nfunction withTimeout(sync, timeout, timeoutError = E_TIMEOUT) {\n return {\n acquire: (weightOrPriority, priority) => {\n let weight;\n if (isSemaphore(sync)) {\n weight = weightOrPriority;\n }\n else {\n weight = undefined;\n priority = weightOrPriority;\n }\n if (weight !== undefined && weight <= 0) {\n throw new Error(`invalid weight ${weight}: must be positive`);\n }\n return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n let isTimeout = false;\n const handle = setTimeout(() => {\n isTimeout = true;\n reject(timeoutError);\n }, timeout);\n try {\n const ticket = yield (isSemaphore(sync)\n ? sync.acquire(weight, priority)\n : sync.acquire(priority));\n if (isTimeout) {\n const release = Array.isArray(ticket) ? ticket[1] : ticket;\n release();\n }\n else {\n clearTimeout(handle);\n resolve(ticket);\n }\n }\n catch (e) {\n if (!isTimeout) {\n clearTimeout(handle);\n reject(e);\n }\n }\n }));\n },\n runExclusive(callback, weight, priority) {\n return __awaiter(this, void 0, void 0, function* () {\n let release = () => undefined;\n try {\n const ticket = yield this.acquire(weight, priority);\n if (Array.isArray(ticket)) {\n release = ticket[1];\n return yield callback(ticket[0]);\n }\n else {\n release = ticket;\n return yield callback();\n }\n }\n finally {\n release();\n }\n });\n },\n release(weight) {\n sync.release(weight);\n },\n cancel() {\n return sync.cancel();\n },\n waitForUnlock: (weightOrPriority, priority) => {\n let weight;\n if (isSemaphore(sync)) {\n weight = weightOrPriority;\n }\n else {\n weight = undefined;\n priority = weightOrPriority;\n }\n if (weight !== undefined && weight <= 0) {\n throw new Error(`invalid weight ${weight}: must be positive`);\n }\n return new Promise((resolve, reject) => {\n const handle = setTimeout(() => reject(timeoutError), timeout);\n (isSemaphore(sync)\n ? sync.waitForUnlock(weight, priority)\n : sync.waitForUnlock(priority)).then(() => {\n clearTimeout(handle);\n resolve();\n });\n });\n },\n isLocked: () => sync.isLocked(),\n getValue: () => sync.getValue(),\n setValue: (value) => sync.setValue(value),\n };\n}\nfunction isSemaphore(sync) {\n return sync.getValue !== undefined;\n}\n\n// eslint-disable-next-lisne @typescript-eslint/explicit-module-boundary-types\nfunction tryAcquire(sync, alreadyAcquiredError = E_ALREADY_LOCKED) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return withTimeout(sync, 0, alreadyAcquiredError);\n}\n\nexport { E_ALREADY_LOCKED, E_CANCELED, E_TIMEOUT, Mutex, Semaphore, tryAcquire, withTimeout };\n","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nconst proxyMarker = Symbol(\"Comlink.proxy\");\nconst createEndpoint = Symbol(\"Comlink.endpoint\");\nconst releaseProxy = Symbol(\"Comlink.releaseProxy\");\nconst finalizer = Symbol(\"Comlink.finalizer\");\nconst throwMarker = Symbol(\"Comlink.thrown\");\nconst isObject = (val) => (typeof val === \"object\" && val !== null) || typeof val === \"function\";\n/**\n * Internal transfer handle to handle objects marked to proxy.\n */\nconst proxyTransferHandler = {\n canHandle: (val) => isObject(val) && val[proxyMarker],\n serialize(obj) {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port1);\n return [port2, [port2]];\n },\n deserialize(port) {\n port.start();\n return wrap(port);\n },\n};\n/**\n * Internal transfer handler to handle thrown exceptions.\n */\nconst throwTransferHandler = {\n canHandle: (value) => isObject(value) && throwMarker in value,\n serialize({ value }) {\n let serialized;\n if (value instanceof Error) {\n serialized = {\n isError: true,\n value: {\n message: value.message,\n name: value.name,\n stack: value.stack,\n },\n };\n }\n else {\n serialized = { isError: false, value };\n }\n return [serialized, []];\n },\n deserialize(serialized) {\n if (serialized.isError) {\n throw Object.assign(new Error(serialized.value.message), serialized.value);\n }\n throw serialized.value;\n },\n};\n/**\n * Allows customizing the serialization of certain values.\n */\nconst transferHandlers = new Map([\n [\"proxy\", proxyTransferHandler],\n [\"throw\", throwTransferHandler],\n]);\nfunction isAllowedOrigin(allowedOrigins, origin) {\n for (const allowedOrigin of allowedOrigins) {\n if (origin === allowedOrigin || allowedOrigin === \"*\") {\n return true;\n }\n if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {\n return true;\n }\n }\n return false;\n}\nfunction expose(obj, ep = globalThis, allowedOrigins = [\"*\"]) {\n ep.addEventListener(\"message\", function callback(ev) {\n if (!ev || !ev.data) {\n return;\n }\n if (!isAllowedOrigin(allowedOrigins, ev.origin)) {\n console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);\n return;\n }\n const { id, type, path } = Object.assign({ path: [] }, ev.data);\n const argumentList = (ev.data.argumentList || []).map(fromWireValue);\n let returnValue;\n try {\n const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);\n const rawValue = path.reduce((obj, prop) => obj[prop], obj);\n switch (type) {\n case \"GET\" /* MessageType.GET */:\n {\n returnValue = rawValue;\n }\n break;\n case \"SET\" /* MessageType.SET */:\n {\n parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);\n returnValue = true;\n }\n break;\n case \"APPLY\" /* MessageType.APPLY */:\n {\n returnValue = rawValue.apply(parent, argumentList);\n }\n break;\n case \"CONSTRUCT\" /* MessageType.CONSTRUCT */:\n {\n const value = new rawValue(...argumentList);\n returnValue = proxy(value);\n }\n break;\n case \"ENDPOINT\" /* MessageType.ENDPOINT */:\n {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port2);\n returnValue = transfer(port1, [port1]);\n }\n break;\n case \"RELEASE\" /* MessageType.RELEASE */:\n {\n returnValue = undefined;\n }\n break;\n default:\n return;\n }\n }\n catch (value) {\n returnValue = { value, [throwMarker]: 0 };\n }\n Promise.resolve(returnValue)\n .catch((value) => {\n return { value, [throwMarker]: 0 };\n })\n .then((returnValue) => {\n const [wireValue, transferables] = toWireValue(returnValue);\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n if (type === \"RELEASE\" /* MessageType.RELEASE */) {\n // detach and deactive after sending release response above.\n ep.removeEventListener(\"message\", callback);\n closeEndPoint(ep);\n if (finalizer in obj && typeof obj[finalizer] === \"function\") {\n obj[finalizer]();\n }\n }\n })\n .catch((error) => {\n // Send Serialization Error To Caller\n const [wireValue, transferables] = toWireValue({\n value: new TypeError(\"Unserializable return value\"),\n [throwMarker]: 0,\n });\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n });\n });\n if (ep.start) {\n ep.start();\n }\n}\nfunction isMessagePort(endpoint) {\n return endpoint.constructor.name === \"MessagePort\";\n}\nfunction closeEndPoint(endpoint) {\n if (isMessagePort(endpoint))\n endpoint.close();\n}\nfunction wrap(ep, target) {\n const pendingListeners = new Map();\n ep.addEventListener(\"message\", function handleMessage(ev) {\n const { data } = ev;\n if (!data || !data.id) {\n return;\n }\n const resolver = pendingListeners.get(data.id);\n if (!resolver) {\n return;\n }\n try {\n resolver(data);\n }\n finally {\n pendingListeners.delete(data.id);\n }\n });\n return createProxy(ep, pendingListeners, [], target);\n}\nfunction throwIfProxyReleased(isReleased) {\n if (isReleased) {\n throw new Error(\"Proxy has been released and is not useable\");\n }\n}\nfunction releaseEndpoint(ep) {\n return requestResponseMessage(ep, new Map(), {\n type: \"RELEASE\" /* MessageType.RELEASE */,\n }).then(() => {\n closeEndPoint(ep);\n });\n}\nconst proxyCounter = new WeakMap();\nconst proxyFinalizers = \"FinalizationRegistry\" in globalThis &&\n new FinalizationRegistry((ep) => {\n const newCount = (proxyCounter.get(ep) || 0) - 1;\n proxyCounter.set(ep, newCount);\n if (newCount === 0) {\n releaseEndpoint(ep);\n }\n });\nfunction registerProxy(proxy, ep) {\n const newCount = (proxyCounter.get(ep) || 0) + 1;\n proxyCounter.set(ep, newCount);\n if (proxyFinalizers) {\n proxyFinalizers.register(proxy, ep, proxy);\n }\n}\nfunction unregisterProxy(proxy) {\n if (proxyFinalizers) {\n proxyFinalizers.unregister(proxy);\n }\n}\nfunction createProxy(ep, pendingListeners, path = [], target = function () { }) {\n let isProxyReleased = false;\n const proxy = new Proxy(target, {\n get(_target, prop) {\n throwIfProxyReleased(isProxyReleased);\n if (prop === releaseProxy) {\n return () => {\n unregisterProxy(proxy);\n releaseEndpoint(ep);\n pendingListeners.clear();\n isProxyReleased = true;\n };\n }\n if (prop === \"then\") {\n if (path.length === 0) {\n return { then: () => proxy };\n }\n const r = requestResponseMessage(ep, pendingListeners, {\n type: \"GET\" /* MessageType.GET */,\n path: path.map((p) => p.toString()),\n }).then(fromWireValue);\n return r.then.bind(r);\n }\n return createProxy(ep, pendingListeners, [...path, prop]);\n },\n set(_target, prop, rawValue) {\n throwIfProxyReleased(isProxyReleased);\n // FIXME: ES6 Proxy Handler `set` methods are supposed to return a\n // boolean. To show good will, we return true asynchronously ¯\\_(ツ)_/¯\n const [value, transferables] = toWireValue(rawValue);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"SET\" /* MessageType.SET */,\n path: [...path, prop].map((p) => p.toString()),\n value,\n }, transferables).then(fromWireValue);\n },\n apply(_target, _thisArg, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const last = path[path.length - 1];\n if (last === createEndpoint) {\n return requestResponseMessage(ep, pendingListeners, {\n type: \"ENDPOINT\" /* MessageType.ENDPOINT */,\n }).then(fromWireValue);\n }\n // We just pretend that `bind()` didn’t happen.\n if (last === \"bind\") {\n return createProxy(ep, pendingListeners, path.slice(0, -1));\n }\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"APPLY\" /* MessageType.APPLY */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n construct(_target, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"CONSTRUCT\" /* MessageType.CONSTRUCT */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n });\n registerProxy(proxy, ep);\n return proxy;\n}\nfunction myFlat(arr) {\n return Array.prototype.concat.apply([], arr);\n}\nfunction processArguments(argumentList) {\n const processed = argumentList.map(toWireValue);\n return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];\n}\nconst transferCache = new WeakMap();\nfunction transfer(obj, transfers) {\n transferCache.set(obj, transfers);\n return obj;\n}\nfunction proxy(obj) {\n return Object.assign(obj, { [proxyMarker]: true });\n}\nfunction windowEndpoint(w, context = globalThis, targetOrigin = \"*\") {\n return {\n postMessage: (msg, transferables) => w.postMessage(msg, targetOrigin, transferables),\n addEventListener: context.addEventListener.bind(context),\n removeEventListener: context.removeEventListener.bind(context),\n };\n}\nfunction toWireValue(value) {\n for (const [name, handler] of transferHandlers) {\n if (handler.canHandle(value)) {\n const [serializedValue, transferables] = handler.serialize(value);\n return [\n {\n type: \"HANDLER\" /* WireValueType.HANDLER */,\n name,\n value: serializedValue,\n },\n transferables,\n ];\n }\n }\n return [\n {\n type: \"RAW\" /* WireValueType.RAW */,\n value,\n },\n transferCache.get(value) || [],\n ];\n}\nfunction fromWireValue(value) {\n switch (value.type) {\n case \"HANDLER\" /* WireValueType.HANDLER */:\n return transferHandlers.get(value.name).deserialize(value.value);\n case \"RAW\" /* WireValueType.RAW */:\n return value.value;\n }\n}\nfunction requestResponseMessage(ep, pendingListeners, msg, transfers) {\n return new Promise((resolve) => {\n const id = generateUUID();\n pendingListeners.set(id, resolve);\n if (ep.start) {\n ep.start();\n }\n ep.postMessage(Object.assign({ id }, msg), transfers);\n });\n}\nfunction generateUUID() {\n return new Array(4)\n .fill(0)\n .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))\n .join(\"-\");\n}\n\nexport { createEndpoint, expose, finalizer, proxy, proxyMarker, releaseProxy, transfer, transferHandlers, windowEndpoint, wrap };\n//# sourceMappingURL=comlink.mjs.map\n","// Copyright 2021 Roy T. Hashimoto. All Rights Reserved.\n\nimport * as SQLite from './sqlite-constants.js';\nexport * from './sqlite-constants.js';\n\n/**\n * Need to have a serializer for bigint\n * https://github.com/GoogleChromeLabs/jsbi/issues/30\n */\nif (typeof BigInt.prototype['toJSON'] == 'undefined') {\n BigInt.prototype['toJSON'] = function() {\n return this.toString();\n };\n}\n\nconst MAX_INT64 = 0x7fffffffffffffffn;\nconst MIN_INT64 = -0x8000000000000000n;\n\nconst AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;\n\nexport class SQLiteError extends Error {\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\n\nconst async = true;\n\n\n/**\n * Builds a Javascript API from the Emscripten module. This API is still\n * low-level and closely corresponds to the C API exported by the module,\n * but differs in some specifics like throwing exceptions on errors.\n * @param {*} Module SQLite Emscripten module\n * @returns {SQLiteAPI}\n */\nexport function Factory(Module) {\n /** @type {SQLiteAPI} */ const sqlite3 = {};\n\n Module.retryOps = [];\n const sqliteFreeAddress = Module._getSqliteFree();\n\n // Allocate some space for 32-bit returned values.\n const tmp = Module._malloc(8);\n const tmpPtr = [tmp, tmp + 4];\n\n const textEncoder = new TextEncoder();\n // Convert a JS string to a C string. sqlite3_malloc is used to allocate\n // memory (use sqlite3_free to deallocate).\n function createUTF8(s) {\n if (typeof s !== 'string') return 0;\n const utf8 = textEncoder.encode(s);\n const zts = Module._sqlite3_malloc(utf8.byteLength + 1);\n Module.HEAPU8.set(utf8, zts);\n Module.HEAPU8[zts + utf8.byteLength] = 0;\n return zts;\n }\n\n /**\n * Concatenate 32-bit numbers into a 64-bit (signed) BigInt.\n * @param {number} lo32\n * @param {number} hi32\n * @returns {bigint}\n */\n function cvt32x2ToBigInt(lo32, hi32) {\n return (BigInt(hi32) << 32n) | (BigInt(lo32) & 0xffffffffn);\n }\n\n // /**\n // * Setup table change update callback\n // */\n // var onTableChangedFunctionPointer = Module.addFunction(onTableUpdate);\n // var passFnPointer = Module.cwrap('passFnPointer', 'undefined', ['number']);\n // passFnPointer(onTableChangedFunctionPointer);\n /**\n * Concatenate 32-bit numbers and return as number or BigInt, depending\n * on the value.\n * @param {number} lo32\n * @param {number} hi32\n * @returns {number|bigint}\n */\n const cvt32x2AsSafe = (function() {\n const hiMax = BigInt(Number.MAX_SAFE_INTEGER) >> 32n;\n const hiMin = BigInt(Number.MIN_SAFE_INTEGER) >> 32n;\n\n return function(lo32, hi32) {\n if (hi32 > hiMax || hi32 < hiMin) {\n // Can't be expressed as a Number so use BigInt.\n return cvt32x2ToBigInt(lo32, hi32);\n } else {\n // Combine the upper and lower 32-bit numbers. The complication is\n // that lo32 is a signed integer which makes manipulating its bits\n // a little tricky - the sign bit gets handled separately.\n return hi32 * 0x100000000 + (lo32 & 0x7fffffff) - (lo32 & 0x80000000);\n }\n };\n })();\n\n const databases = new Set();\n function verifyDatabase(db) {\n if (!databases.has(db)) {\n throw new SQLiteError('not a database', SQLite.SQLITE_MISUSE);\n }\n }\n\n const mapStmtToDB = new Map();\n function verifyStatement(stmt) {\n if (!mapStmtToDB.has(stmt)) {\n throw new SQLiteError('not a statement', SQLite.SQLITE_MISUSE);\n }\n }\n\n sqlite3.bind_collection = function(stmt, bindings) {\n verifyStatement(stmt);\n const isArray = Array.isArray(bindings);\n const nBindings = sqlite3.bind_parameter_count(stmt);\n for (let i = 1; i <= nBindings; ++i) {\n const key = isArray ? i - 1 : sqlite3.bind_parameter_name(stmt, i);\n const value = bindings[key];\n if (value !== undefined) {\n sqlite3.bind(stmt, i, value);\n }\n }\n return SQLite.SQLITE_OK;\n };\n\n sqlite3.bind = function(stmt, i, value) {\n verifyStatement(stmt);\n switch (typeof value) {\n case 'number':\n if (value === (value | 0)) {\n return sqlite3.bind_int(stmt, i, value);\n } else {\n return sqlite3.bind_double(stmt, i, value);\n }\n case 'string':\n return sqlite3.bind_text(stmt, i, value);\n case \"boolean\":\n return sqlite3.bind_int(stmt, i, value ? 1 : 0);\n default:\n if (value instanceof Uint8Array || Array.isArray(value)) {\n return sqlite3.bind_blob(stmt, i, value);\n } else if (value === null) {\n return sqlite3.bind_null(stmt, i);\n } else if (typeof value === 'bigint') {\n return sqlite3.bind_int64(stmt, i, value);\n } else if (value === undefined) {\n // Existing binding (or NULL) will be used.\n return SQLite.SQLITE_NOTICE;\n } else {\n console.warn('unknown binding converted to null', value);\n return sqlite3.bind_null(stmt, i);\n }\n }\n };\n\n sqlite3.bind_blob = (function() {\n const fname = 'sqlite3_bind_blob';\n const f = Module.cwrap(fname, ...decl('nnnnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n // @ts-ignore\n const byteLength = value.byteLength ?? value.length;\n const ptr = Module._sqlite3_malloc(byteLength);\n Module.HEAPU8.subarray(ptr).set(value);\n const result = f(stmt, i, ptr, byteLength, sqliteFreeAddress);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_parameter_count = (function() {\n const fname = 'sqlite3_bind_parameter_count';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return result;\n };\n })();\n\n sqlite3.bind_double = (function() {\n const fname = 'sqlite3_bind_double';\n const f = Module.cwrap(fname, ...decl('nnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n const result = f(stmt, i, value);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_int = (function() {\n const fname = 'sqlite3_bind_int';\n const f = Module.cwrap(fname, ...decl('nnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n if (value > 0x7fffffff || value < -0x80000000) return SQLite.SQLITE_RANGE;\n\n const result = f(stmt, i, value);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_int64 = (function() {\n const fname = 'sqlite3_bind_int64';\n const f = Module.cwrap(fname, ...decl('nnnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n if (value > MAX_INT64 || value < MIN_INT64) return SQLite.SQLITE_RANGE;\n\n const lo32 = value & 0xffffffffn;\n const hi32 = value >> 32n;\n const result = f(stmt, i, Number(lo32), Number(hi32));\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_null = (function() {\n const fname = 'sqlite3_bind_null';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, i) {\n verifyStatement(stmt);\n const result = f(stmt, i);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.bind_parameter_name = (function() {\n const fname = 'sqlite3_bind_parameter_name';\n const f = Module.cwrap(fname, ...decl('n:s'));\n return function(stmt, i) {\n verifyStatement(stmt);\n const result = f(stmt, i);\n return result;\n };\n })();\n\n sqlite3.bind_text = (function() {\n const fname = 'sqlite3_bind_text';\n const f = Module.cwrap(fname, ...decl('nnnnn:n'));\n return function(stmt, i, value) {\n verifyStatement(stmt);\n const ptr = createUTF8(value);\n const result = f(stmt, i, ptr, -1, sqliteFreeAddress);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.changes = (function() {\n const fname = 'sqlite3_changes';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(db) {\n verifyDatabase(db);\n const result = f(db);\n return result;\n };\n })();\n\n sqlite3.clear_bindings = (function() {\n const fname = 'sqlite3_clear_bindings';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.last_insert_id = (function() {\n const fname = 'sqlite3_last_insert_rowid';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(db) {\n verifyDatabase(db);\n const result = f(db);\n // trace(fname, result);\n return result;\n };\n })();\n \n sqlite3.close = (function() {\n const fname = 'sqlite3_close';\n const f = Module.cwrap(fname, ...decl('n:n'), { async });\n return async function(db) {\n verifyDatabase(db);\n const result = await f(db);\n databases.delete(db);\n return check(fname, result, db);\n };\n })();\n\n sqlite3.column = function(stmt, iCol) {\n verifyStatement(stmt);\n const type = sqlite3.column_type(stmt, iCol);\n switch (type) {\n case SQLite.SQLITE_BLOB:\n return sqlite3.column_blob(stmt, iCol);\n case SQLite.SQLITE_FLOAT:\n return sqlite3.column_double(stmt, iCol);\n case SQLite.SQLITE_INTEGER:\n const lo32 = sqlite3.column_int(stmt, iCol);\n const hi32 = Module.getTempRet0();\n return cvt32x2AsSafe(lo32, hi32);\n case SQLite.SQLITE_NULL:\n return null;\n case SQLite.SQLITE_TEXT:\n return sqlite3.column_text(stmt, iCol);\n default:\n throw new SQLiteError('unknown type', type);\n }\n };\n\n sqlite3.column_blob = (function() {\n const fname = 'sqlite3_column_blob';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const nBytes = sqlite3.column_bytes(stmt, iCol);\n const address = f(stmt, iCol);\n const result = Module.HEAPU8.subarray(address, address + nBytes);\n return result;\n };\n })();\n\n sqlite3.column_bytes = (function() {\n const fname = 'sqlite3_column_bytes';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_count = (function() {\n const fname = 'sqlite3_column_count';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return result;\n };\n })();\n\n sqlite3.column_double = (function() {\n const fname = 'sqlite3_column_double';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_int = (function() {\n // Retrieve int64 but use only the lower 32 bits. The upper 32-bits are\n // accessible with Module.getTempRet0().\n const fname = 'sqlite3_column_int64';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_int64 = (function() {\n const fname = 'sqlite3_column_int64';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const lo32 = f(stmt, iCol);\n const hi32 = Module.getTempRet0();\n const result = cvt32x2ToBigInt(lo32, hi32);\n return result;\n };\n })();\n\n sqlite3.column_name = (function() {\n const fname = 'sqlite3_column_name';\n const f = Module.cwrap(fname, ...decl('nn:s'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_names = function(stmt) {\n const columns = [];\n const nColumns = sqlite3.column_count(stmt);\n for (let i = 0; i < nColumns; ++i) {\n columns.push(sqlite3.column_name(stmt, i));\n }\n return columns;\n };\n\n sqlite3.column_text = (function() {\n const fname = 'sqlite3_column_text';\n const f = Module.cwrap(fname, ...decl('nn:s'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.column_type = (function() {\n const fname = 'sqlite3_column_type';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(stmt, iCol) {\n verifyStatement(stmt);\n const result = f(stmt, iCol);\n return result;\n };\n })();\n\n sqlite3.create_function = function(db, zFunctionName, nArg, eTextRep, pApp, xFunc, xStep, xFinal) {\n verifyDatabase(db);\n \n // Convert SQLite callback arguments to JavaScript-friendly arguments.\n function adapt(f) {\n return f instanceof AsyncFunction ?\n (async (ctx, n, values) => f(ctx, Module.HEAP32.subarray(values / 4, values / 4 + n))) :\n ((ctx, n, values) => f(ctx, Module.HEAP32.subarray(values / 4, values / 4 + n)));\n }\n\n const result = Module.create_function(\n db,\n zFunctionName,\n nArg,\n eTextRep,\n pApp,\n xFunc && adapt(xFunc),\n xStep && adapt(xStep),\n xFinal);\n return check('sqlite3_create_function', result, db);\n };\n\n sqlite3.data_count = (function() {\n const fname = 'sqlite3_data_count';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return result;\n };\n })();\n\n sqlite3.exec = async function(db, sql, callback) {\n for await (const stmt of sqlite3.statements(db, sql)) {\n let columns;\n while ((await sqlite3.step(stmt)) === SQLite.SQLITE_ROW) {\n if (callback) {\n columns = columns ?? sqlite3.column_names(stmt);\n const row = sqlite3.row(stmt);\n await callback(row, columns);\n }\n }\n }\n return SQLite.SQLITE_OK;\n };\n\n sqlite3.finalize = (function() {\n const fname = 'sqlite3_finalize';\n const f = Module.cwrap(fname, ...decl('n:n'), { async });\n return async function(stmt) {\n const result = await f(stmt);\n mapStmtToDB.delete(stmt)\n\n // Don't throw on error here. Typically the error has already been\n // thrown and finalize() is part of the cleanup.\n return result;\n };\n })();\n\n sqlite3.get_autocommit = (function() {\n const fname = 'sqlite3_get_autocommit';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(db) {\n const result = f(db);\n return result;\n };\n })();\n\n sqlite3.libversion = (function() {\n const fname = 'sqlite3_libversion';\n const f = Module.cwrap(fname, ...decl(':s'));\n return function() {\n const result = f();\n return result;\n };\n })();\n\n sqlite3.libversion_number = (function() {\n const fname = 'sqlite3_libversion_number';\n const f = Module.cwrap(fname, ...decl(':n'));\n return function() {\n const result = f();\n return result;\n };\n })();\n\n sqlite3.limit = (function() {\n const fname = 'sqlite3_limit';\n const f = Module.cwrap(fname, ...decl('nnn:n'));\n return function(db, id, newVal) {\n const result = f(db, id, newVal);\n return result;\n };\n })();\n\n sqlite3.open_v2 = (function() {\n const fname = 'sqlite3_open_v2';\n const f = Module.cwrap(fname, ...decl('snnn:n'), { async });\n return async function(zFilename, flags, zVfs) {\n flags = flags || SQLite.SQLITE_OPEN_CREATE | SQLite.SQLITE_OPEN_READWRITE;\n zVfs = createUTF8(zVfs);\n try {\n // Allow retry operations.\n const rc = await retry(() => f(zFilename, tmpPtr[0], flags, zVfs));\n\n const db = Module.getValue(tmpPtr[0], '*');\n databases.add(db);\n\n Module.ccall('RegisterExtensionFunctions', 'number', ['number'], [db]);\n check(fname, rc);\n return db;\n } finally {\n Module._sqlite3_free(zVfs);\n }\n };\n })();\n\n sqlite3.progress_handler = function(db, nProgressOps, handler, userData) {\n verifyDatabase(db);\n Module.progress_handler(db, nProgressOps, handler, userData);\n };;\n\n sqlite3.reset = (function() {\n const fname = 'sqlite3_reset';\n const f = Module.cwrap(fname, ...decl('n:n'), { async });\n return async function(stmt) {\n verifyStatement(stmt);\n const result = await f(stmt);\n return check(fname, result, mapStmtToDB.get(stmt));\n };\n })();\n\n sqlite3.result = function(context, value) {\n switch (typeof value) {\n case 'number':\n if (value === (value | 0)) {\n sqlite3.result_int(context, value);\n } else {\n sqlite3.result_double(context, value);\n }\n break;\n case 'string':\n sqlite3.result_text(context, value);\n break;\n default:\n if (value instanceof Uint8Array || Array.isArray(value)) {\n sqlite3.result_blob(context, value);\n } else if (value === null) {\n sqlite3.result_null(context);\n } else if (typeof value === 'bigint') {\n return sqlite3.result_int64(context, value);\n } else {\n console.warn('unknown result converted to null', value);\n sqlite3.result_null(context);\n }\n break;\n }\n };\n\n sqlite3.result_blob = (function() {\n const fname = 'sqlite3_result_blob';\n const f = Module.cwrap(fname, ...decl('nnnn:n'));\n return function(context, value) {\n // @ts-ignore\n const byteLength = value.byteLength ?? value.length;\n const ptr = Module._sqlite3_malloc(byteLength);\n Module.HEAPU8.subarray(ptr).set(value);\n f(context, ptr, byteLength, sqliteFreeAddress); // void return\n };\n })();\n\n sqlite3.result_double = (function() {\n const fname = 'sqlite3_result_double';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(context, value) {\n f(context, value); // void return\n };\n })();\n\n sqlite3.result_int = (function() {\n const fname = 'sqlite3_result_int';\n const f = Module.cwrap(fname, ...decl('nn:n'));\n return function(context, value) {\n f(context, value); // void return\n };\n })();\n\n sqlite3.result_int64 = (function() {\n const fname = 'sqlite3_result_int64';\n const f = Module.cwrap(fname, ...decl('nnn:n'));\n return function(context, value) {\n if (value > MAX_INT64 || value < MIN_INT64) return SQLite.SQLITE_RANGE;\n\n const lo32 = value & 0xffffffffn;\n const hi32 = value >> 32n;\n f(context, Number(lo32), Number(hi32)); // void return\n };\n })();\n\n sqlite3.result_null = (function() {\n const fname = 'sqlite3_result_null';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(context) {\n f(context); // void return\n };\n })();\n\n sqlite3.result_text = (function() {\n const fname = 'sqlite3_result_text';\n const f = Module.cwrap(fname, ...decl('nnnn:n'));\n return function(context, value) {\n const ptr = createUTF8(value);\n f(context, ptr, -1, sqliteFreeAddress); // void return\n };\n })();\n\n sqlite3.row = function(stmt) {\n const row = [];\n const nColumns = sqlite3.data_count(stmt);\n for (let i = 0; i < nColumns; ++i) {\n const value = sqlite3.column(stmt, i);\n\n // Copy blob if aliasing volatile WebAssembly memory. This avoids an\n // unnecessary copy if users monkey patch column_blob to copy.\n // @ts-ignore\n row.push(value?.buffer === Module.HEAPU8.buffer ? value.slice() : value);\n }\n return row;\n };\n\n sqlite3.set_authorizer = function(db, xAuth, pApp) {\n verifyDatabase(db);\n\n // Convert SQLite callback arguments to JavaScript-friendly arguments.\n function cvtArgs(_, iAction, p3, p4, p5, p6) {\n return [\n _,\n iAction,\n Module.UTF8ToString(p3),\n Module.UTF8ToString(p4),\n Module.UTF8ToString(p5),\n Module.UTF8ToString(p6)\n ];\n };\n function adapt(f) {\n return f instanceof AsyncFunction ?\n (async (_, iAction, p3, p4, p5, p6) => f(...cvtArgs(_, iAction, p3, p4, p5, p6))) :\n ((_, iAction, p3, p4, p5, p6) => f(...cvtArgs(_, iAction, p3, p4, p5, p6)));\n }\n\n const result = Module.set_authorizer(db, adapt(xAuth), pApp);\n return check('sqlite3_set_authorizer', result, db);\n };\n\n sqlite3.sql = (function() {\n const fname = 'sqlite3_sql';\n const f = Module.cwrap(fname, ...decl('n:s'));\n return function(stmt) {\n verifyStatement(stmt);\n const result = f(stmt);\n return result;\n };\n })();\n\n sqlite3.statements = function(db, sql, options = {}) {\n const prepare = Module.cwrap(\n 'sqlite3_prepare_v3',\n 'number',\n ['number', 'number', 'number', 'number', 'number', 'number'],\n { async: true });\n\n return (async function*() {\n const onFinally = [];\n try {\n // Encode SQL string to UTF-8.\n const utf8 = textEncoder.encode(sql);\n\n // Copy encoded string to WebAssembly memory. The SQLite docs say\n // zero-termination is a minor optimization so add room for that.\n // Also add space for the statement handle and SQL tail pointer.\n const allocSize = utf8.byteLength - (utf8.byteLength % 4) + 12;\n const pzHead = Module._sqlite3_malloc(allocSize);\n const pzEnd = pzHead + utf8.byteLength + 1;\n onFinally.push(() => Module._sqlite3_free(pzHead));\n Module.HEAPU8.set(utf8, pzHead);\n Module.HEAPU8[pzEnd - 1] = 0;\n \n // Use extra space for the statement handle and SQL tail pointer.\n const pStmt = pzHead + allocSize - 8;\n const pzTail = pzHead + allocSize - 4;\n\n // Ensure that statement handles are not leaked.\n let stmt;\n function maybeFinalize() {\n if (stmt && !options.unscoped) {\n sqlite3.finalize(stmt);\n }\n stmt = 0;\n }\n onFinally.push(maybeFinalize);\n \n // Loop over statements.\n Module.setValue(pzTail, pzHead, '*');\n do {\n // Reclaim resources for the previous iteration.\n maybeFinalize();\n\n // Call sqlite3_prepare_v3() for the next statement.\n // Allow retry operations.\n const zTail = Module.getValue(pzTail, '*');\n const rc = await retry(() => {\n return prepare(\n db,\n zTail,\n pzEnd - pzTail,\n options.flags || 0,\n pStmt,\n pzTail);\n });\n\n if (rc !== SQLite.SQLITE_OK) {\n check('sqlite3_prepare_v3', rc, db);\n }\n \n stmt = Module.getValue(pStmt, '*');\n if (stmt) {\n mapStmtToDB.set(stmt, db);\n yield stmt;\n }\n } while (stmt);\n } finally {\n while (onFinally.length) {\n onFinally.pop()();\n }\n }\n })();\n };\n\n sqlite3.step = (function() {\n const fname = 'sqlite3_step';\n const f = Module.cwrap(fname, ...decl('n:n'), { async });\n return async function(stmt) {\n verifyStatement(stmt);\n\n // Allow retry operations.\n const rc = await retry(() => f(stmt));\n\n return check(fname, rc, mapStmtToDB.get(stmt), [SQLite.SQLITE_ROW, SQLite.SQLITE_DONE]);\n };\n })();\n\n sqlite3.commit_hook = function(db, xCommitHook) {\n verifyDatabase(db);\n Module.commit_hook(db, xCommitHook);\n };\n\n sqlite3.update_hook = function(db, xUpdateHook) {\n verifyDatabase(db);\n\n // Convert SQLite callback arguments to JavaScript-friendly arguments.\n function cvtArgs(iUpdateType, dbName, tblName, lo32, hi32) {\n return [\n iUpdateType,\n Module.UTF8ToString(dbName),\n Module.UTF8ToString(tblName),\n\t\tcvt32x2ToBigInt(lo32, hi32)\n ];\n };\n function adapt(f) {\n return f instanceof AsyncFunction ?\n (async (iUpdateType, dbName, tblName, lo32, hi32) => f(...cvtArgs(iUpdateType, dbName, tblName, lo32, hi32))) :\n ((iUpdateType, dbName, tblName, lo32, hi32) => f(...cvtArgs(iUpdateType, dbName, tblName, lo32, hi32)));\n }\n\n Module.update_hook(db, adapt(xUpdateHook));\n };;\n\n sqlite3.value = function(pValue) {\n const type = sqlite3.value_type(pValue);\n switch (type) {\n case SQLite.SQLITE_BLOB:\n return sqlite3.value_blob(pValue);\n case SQLite.SQLITE_FLOAT:\n return sqlite3.value_double(pValue);\n case SQLite.SQLITE_INTEGER:\n const lo32 = sqlite3.value_int(pValue);\n const hi32 = Module.getTempRet0();\n return cvt32x2AsSafe(lo32, hi32);\n case SQLite.SQLITE_NULL:\n return null;\n case SQLite.SQLITE_TEXT:\n return sqlite3.value_text(pValue);\n default:\n throw new SQLiteError('unknown type', type);\n }\n };\n\n sqlite3.value_blob = (function() {\n const fname = 'sqlite3_value_blob';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const nBytes = sqlite3.value_bytes(pValue);\n const address = f(pValue);\n const result = Module.HEAPU8.subarray(address, address + nBytes);\n return result;\n };\n })();\n\n sqlite3.value_bytes = (function() {\n const fname = 'sqlite3_value_bytes';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.value_double = (function() {\n const fname = 'sqlite3_value_double';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.value_int = (function() {\n const fname = 'sqlite3_value_int64';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.value_int64 = (function() {\n const fname = 'sqlite3_value_int64';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const lo32 = f(pValue);\n const hi32 = Module.getTempRet0();\n const result = cvt32x2ToBigInt(lo32, hi32);\n return result;\n };\n })();\n\n sqlite3.value_text = (function() {\n const fname = 'sqlite3_value_text';\n const f = Module.cwrap(fname, ...decl('n:s'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.value_type = (function() {\n const fname = 'sqlite3_value_type';\n const f = Module.cwrap(fname, ...decl('n:n'));\n return function(pValue) {\n const result = f(pValue);\n return result;\n };\n })();\n\n sqlite3.vfs_register = function(vfs, makeDefault) {\n const result = Module.vfs_register(vfs, makeDefault);\n return check('sqlite3_vfs_register', result);\n };\n\n function check(fname, result, db = null, allowed = [SQLite.SQLITE_OK]) {\n if (allowed.includes(result)) return result;\n const message = db ? Module.ccall('sqlite3_errmsg', 'string', ['number'], [db]) : fname;\n throw new SQLiteError(message, result);\n }\n\n // This function is used to automatically retry failed calls that\n // have pending retry operations that should allow the retry to\n // succeed.\n async function retry(f) {\n let rc;\n do {\n // Wait for all pending retry operations to complete. This is\n // normally empty on the first loop iteration.\n if (Module.retryOps.length) {\n try {\n await Promise.all(Module.retryOps);\n } finally {\n Module.retryOps = [];\n }\n }\n \n rc = await f();\n\n // Retry on failure with new pending retry operations.\n } while (rc && Module.retryOps.length);\n return rc;\n }\n\n return sqlite3;\n}\n\n// Helper function to use a more compact signature specification.\nfunction decl(s) {\n const result = [];\n const m = s.match(/([ns@]*):([nsv@])/);\n switch (m[2]) {\n case 'n':\n result.push('number');\n break;\n case 's':\n result.push('string');\n break;\n case 'v':\n result.push(null);\n break;\n }\n\n const args = [];\n for (let c of m[1]) {\n switch (c) {\n case 'n':\n args.push('number');\n break;\n case 's':\n args.push('string');\n break;\n }\n }\n result.push(args);\n return result;\n}\n","// Primary result codes.\n// https://www.sqlite.org/rescode.html\nexport const SQLITE_OK = 0;\nexport const SQLITE_ERROR = 1;\nexport const SQLITE_INTERNAL = 2;\nexport const SQLITE_PERM = 3;\nexport const SQLITE_ABORT = 4;\nexport const SQLITE_BUSY = 5;\nexport const SQLITE_LOCKED = 6;\nexport const SQLITE_NOMEM = 7;\nexport const SQLITE_READONLY = 8;\nexport const SQLITE_INTERRUPT = 9;\nexport const SQLITE_IOERR = 10;\nexport const SQLITE_CORRUPT = 11;\nexport const SQLITE_NOTFOUND = 12;\nexport const SQLITE_FULL = 13;\nexport const SQLITE_CANTOPEN = 14;\nexport const SQLITE_PROTOCOL = 15;\nexport const SQLITE_EMPTY = 16;\nexport const SQLITE_SCHEMA = 17;\nexport const SQLITE_TOOBIG = 18;\nexport const SQLITE_CONSTRAINT = 19;\nexport const SQLITE_MISMATCH = 20;\nexport const SQLITE_MISUSE = 21;\nexport const SQLITE_NOLFS = 22;\nexport const SQLITE_AUTH = 23;\nexport const SQLITE_FORMAT = 24;\nexport const SQLITE_RANGE = 25;\nexport const SQLITE_NOTADB = 26;\nexport const SQLITE_NOTICE = 27;\nexport const SQLITE_WARNING = 28;\nexport const SQLITE_ROW = 100;\nexport const SQLITE_DONE = 101;\n\n// Extended error codes.\nexport const SQLITE_IOERR_ACCESS = 3338;\nexport const SQLITE_IOERR_CHECKRESERVEDLOCK = 3594;\nexport const SQLITE_IOERR_CLOSE = 4106;\nexport const SQLITE_IOERR_DATA = 8202;\nexport const SQLITE_IOERR_DELETE = 2570;\nexport const SQLITE_IOERR_DELETE_NOENT = 5898;\nexport const SQLITE_IOERR_DIR_FSYNC = 1290;\nexport const SQLITE_IOERR_FSTAT = 1802;\nexport const SQLITE_IOERR_FSYNC = 1034;\nexport const SQLITE_IOERR_GETTEMPPATH = 6410;\nexport const SQLITE_IOERR_LOCK = 3850;\nexport const SQLITE_IOERR_NOMEM = 3082;\nexport const SQLITE_IOERR_READ = 266;\nexport const SQLITE_IOERR_RDLOCK = 2314;\nexport const SQLITE_IOERR_SEEK = 5642;\nexport const SQLITE_IOERR_SHORT_READ = 522;\nexport const SQLITE_IOERR_TRUNCATE = 1546;\nexport const SQLITE_IOERR_UNLOCK = 2058;\nexport const SQLITE_IOERR_VNODE = 6922;\nexport const SQLITE_IOERR_WRITE = 778;\nexport const SQLITE_IOERR_BEGIN_ATOMIC = 7434;\nexport const SQLITE_IOERR_COMMIT_ATOMIC = 7690;\nexport const SQLITE_IOERR_ROLLBACK_ATOMIC = 7946;\n\n// Other extended result codes.\nexport const SQLITE_CONSTRAINT_CHECK = 275;\nexport const SQLITE_CONSTRAINT_COMMITHOOK = 531;\nexport const SQLITE_CONSTRAINT_FOREIGNKEY = 787;\nexport const SQLITE_CONSTRAINT_FUNCTION = 1043;\nexport const SQLITE_CONSTRAINT_NOTNULL = 1299;\nexport const SQLITE_CONSTRAINT_PINNED = 2835;\nexport const SQLITE_CONSTRAINT_PRIMARYKEY = 1555;\nexport const SQLITE_CONSTRAINT_ROWID = 2579;\nexport const SQLITE_CONSTRAINT_TRIGGER = 1811;\nexport const SQLITE_CONSTRAINT_UNIQUE = 2067;\nexport const SQLITE_CONSTRAINT_VTAB = 2323;\n\n// Open flags.\n// https://www.sqlite.org/c3ref/c_open_autoproxy.html\nexport const SQLITE_OPEN_READONLY = 0x00000001;\nexport const SQLITE_OPEN_READWRITE = 0x00000002;\nexport const SQLITE_OPEN_CREATE = 0x00000004;\nexport const SQLITE_OPEN_DELETEONCLOSE = 0x00000008;\nexport const SQLITE_OPEN_EXCLUSIVE = 0x00000010;\nexport const SQLITE_OPEN_AUTOPROXY = 0x00000020;\nexport const SQLITE_OPEN_URI = 0x00000040;\nexport const SQLITE_OPEN_MEMORY = 0x00000080;\nexport const SQLITE_OPEN_MAIN_DB = 0x00000100;\nexport const SQLITE_OPEN_TEMP_DB = 0x00000200;\nexport const SQLITE_OPEN_TRANSIENT_DB = 0x00000400;\nexport const SQLITE_OPEN_MAIN_JOURNAL = 0x00000800;\nexport const SQLITE_OPEN_TEMP_JOURNAL = 0x00001000;\nexport const SQLITE_OPEN_SUBJOURNAL = 0x00002000;\nexport const SQLITE_OPEN_SUPER_JOURNAL = 0x00004000;\nexport const SQLITE_OPEN_NOMUTEX = 0x00008000;\nexport const SQLITE_OPEN_FULLMUTEX = 0x00010000;\nexport const SQLITE_OPEN_SHAREDCACHE = 0x00020000;\nexport const SQLITE_OPEN_PRIVATECACHE = 0x00040000;\nexport const SQLITE_OPEN_WAL = 0x00080000;\nexport const SQLITE_OPEN_NOFOLLOW = 0x01000000;\n\n// Locking levels.\n// https://www.sqlite.org/c3ref/c_lock_exclusive.html\nexport const SQLITE_LOCK_NONE = 0;\nexport const SQLITE_LOCK_SHARED = 1;\nexport const SQLITE_LOCK_RESERVED = 2;\nexport const SQLITE_LOCK_PENDING = 3;\nexport const SQLITE_LOCK_EXCLUSIVE = 4;\n\n// Device characteristics.\n// https://www.sqlite.org/c3ref/c_iocap_atomic.html\nexport const SQLITE_IOCAP_ATOMIC = 0x00000001;\nexport const SQLITE_IOCAP_ATOMIC512 = 0x00000002;\nexport const SQLITE_IOCAP_ATOMIC1K = 0x00000004;\nexport const SQLITE_IOCAP_ATOMIC2K = 0x00000008;\nexport const SQLITE_IOCAP_ATOMIC4K = 0x00000010;\nexport const SQLITE_IOCAP_ATOMIC8K = 0x00000020;\nexport const SQLITE_IOCAP_ATOMIC16K = 0x00000040;\nexport const SQLITE_IOCAP_ATOMIC32K = 0x00000080;\nexport const SQLITE_IOCAP_ATOMIC64K = 0x00000100;\nexport const SQLITE_IOCAP_SAFE_APPEND = 0x00000200;\nexport const SQLITE_IOCAP_SEQUENTIAL = 0x00000400;\nexport const SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN = 0x00000800;\nexport const SQLITE_IOCAP_POWERSAFE_OVERWRITE = 0x00001000;\nexport const SQLITE_IOCAP_IMMUTABLE = 0x00002000;\nexport const SQLITE_IOCAP_BATCH_ATOMIC = 0x00004000;\n\n// xAccess flags.\n// https://www.sqlite.org/c3ref/c_access_exists.html\nexport const SQLITE_ACCESS_EXISTS = 0;\nexport const SQLITE_ACCESS_READWRITE = 1;\nexport const SQLITE_ACCESS_READ = 2;\n\n// File control opcodes\n// https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlbeginatomicwrite\nexport const SQLITE_FCNTL_LOCKSTATE = 1; \nexport const SQLITE_FCNTL_GET_LOCKPROXYFILE = 2; \nexport const SQLITE_FCNTL_SET_LOCKPROXYFILE = 3; \nexport const SQLITE_FCNTL_LAST_ERRNO = 4; \nexport const SQLITE_FCNTL_SIZE_HINT = 5; \nexport const SQLITE_FCNTL_CHUNK_SIZE = 6; \nexport const SQLITE_FCNTL_FILE_POINTER = 7; \nexport const SQLITE_FCNTL_SYNC_OMITTED = 8; \nexport const SQLITE_FCNTL_WIN32_AV_RETRY = 9; \nexport const SQLITE_FCNTL_PERSIST_WAL = 10; \nexport const SQLITE_FCNTL_OVERWRITE = 11; \nexport const SQLITE_FCNTL_VFSNAME = 12; \nexport const SQLITE_FCNTL_POWERSAFE_OVERWRITE = 13; \nexport const SQLITE_FCNTL_PRAGMA = 14; \nexport const SQLITE_FCNTL_BUSYHANDLER = 15; \nexport const SQLITE_FCNTL_TEMPFILENAME = 16; \nexport const SQLITE_FCNTL_MMAP_SIZE = 18; \nexport const SQLITE_FCNTL_TRACE = 19; \nexport const SQLITE_FCNTL_HAS_MOVED = 20; \nexport const SQLITE_FCNTL_SYNC = 21; \nexport const SQLITE_FCNTL_COMMIT_PHASETWO = 22; \nexport const SQLITE_FCNTL_WIN32_SET_HANDLE = 23; \nexport const SQLITE_FCNTL_WAL_BLOCK = 24; \nexport const SQLITE_FCNTL_ZIPVFS = 25; \nexport const SQLITE_FCNTL_RBU = 26; \nexport const SQLITE_FCNTL_VFS_POINTER = 27; \nexport const SQLITE_FCNTL_JOURNAL_POINTER = 28; \nexport const SQLITE_FCNTL_WIN32_GET_HANDLE = 29; \nexport const SQLITE_FCNTL_PDB = 30; \nexport const SQLITE_FCNTL_BEGIN_ATOMIC_WRITE = 31; \nexport const SQLITE_FCNTL_COMMIT_ATOMIC_WRITE = 32; \nexport const SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE = 33; \nexport const SQLITE_FCNTL_LOCK_TIMEOUT = 34; \nexport const SQLITE_FCNTL_DATA_VERSION = 35; \nexport const SQLITE_FCNTL_SIZE_LIMIT = 36; \nexport const SQLITE_FCNTL_CKPT_DONE = 37; \nexport const SQLITE_FCNTL_RESERVE_BYTES = 38; \nexport const SQLITE_FCNTL_CKPT_START = 39;\n\n// Fundamental datatypes.\n// https://www.sqlite.org/c3ref/c_blob.html\nexport const SQLITE_INTEGER = 1;\nexport const SQLITE_FLOAT = 2;\nexport const SQLITE_TEXT = 3;\nexport const SQLITE_BLOB = 4;\nexport const SQLITE_NULL = 5;\n\n// Special destructor behavior.\n// https://www.sqlite.org/c3ref/c_static.html\nexport const SQLITE_STATIC = 0;\nexport const SQLITE_TRANSIENT = -1;\n\n// Text encodings.\n// https://sqlite.org/c3ref/c_any.html\nexport const SQLITE_UTF8 = 1; /* IMP: R-37514-35566 */\nexport const SQLITE_UTF16LE = 2; /* IMP: R-03371-37637 */\nexport const SQLITE_UTF16BE = 3; /* IMP: R-51971-34154 */\nexport const SQLITE_UTF16 = 4; /* Use native byte order */\n\n// Module constraint ops.\nexport const SQLITE_INDEX_CONSTRAINT_EQ = 2;\nexport const SQLITE_INDEX_CONSTRAINT_GT = 4;\nexport const SQLITE_INDEX_CONSTRAINT_LE = 8;\nexport const SQLITE_INDEX_CONSTRAINT_LT = 16;\nexport const SQLITE_INDEX_CONSTRAINT_GE = 32;\nexport const SQLITE_INDEX_CONSTRAINT_MATCH = 64;\nexport const SQLITE_INDEX_CONSTRAINT_LIKE = 65;\nexport const SQLITE_INDEX_CONSTRAINT_GLOB = 66;\nexport const SQLITE_INDEX_CONSTRAINT_REGEXP = 67;\nexport const SQLITE_INDEX_CONSTRAINT_NE = 68;\nexport const SQLITE_INDEX_CONSTRAINT_ISNOT = 69;\nexport const SQLITE_INDEX_CONSTRAINT_ISNOTNULL = 70;\nexport const SQLITE_INDEX_CONSTRAINT_ISNULL = 71;\nexport const SQLITE_INDEX_CONSTRAINT_IS = 72;\nexport const SQLITE_INDEX_CONSTRAINT_FUNCTION = 150;\nexport const SQLITE_INDEX_SCAN_UNIQUE = 1; /* Scan visits at most = 1 row */\n\n// Function flags\nexport const SQLITE_DETERMINISTIC = 0x000000800;\nexport const SQLITE_DIRECTONLY = 0x000080000;\nexport const SQLITE_SUBTYPE = 0x000100000;\nexport const SQLITE_INNOCUOUS = 0x000200000;\n\n// Sync flags\nexport const SQLITE_SYNC_NORMAL = 0x00002;\nexport const SQLITE_SYNC_FULL = 0x00003;\nexport const SQLITE_SYNC_DATAONLY = 0x00010;\n\n// Authorizer action codes\nexport const SQLITE_CREATE_INDEX = 1;\nexport const SQLITE_CREATE_TABLE = 2;\nexport const SQLITE_CREATE_TEMP_INDEX = 3;\nexport const SQLITE_CREATE_TEMP_TABLE = 4;\nexport const SQLITE_CREATE_TEMP_TRIGGER = 5;\nexport const SQLITE_CREATE_TEMP_VIEW = 6;\nexport const SQLITE_CREATE_TRIGGER = 7;\nexport const SQLITE_CREATE_VIEW = 8;\nexport const SQLITE_DELETE = 9;\nexport const SQLITE_DROP_INDEX = 10;\nexport const SQLITE_DROP_TABLE = 11;\nexport const SQLITE_DROP_TEMP_INDEX = 12;\nexport const SQLITE_DROP_TEMP_TABLE = 13;\nexport const SQLITE_DROP_TEMP_TRIGGER = 14;\nexport const SQLITE_DROP_TEMP_VIEW = 15;\nexport const SQLITE_DROP_TRIGGER = 16;\nexport const SQLITE_DROP_VIEW = 17;\nexport const SQLITE_INSERT = 18;\nexport const SQLITE_PRAGMA = 19;\nexport const SQLITE_READ = 20;\nexport const SQLITE_SELECT = 21;\nexport const SQLITE_TRANSACTION = 22;\nexport const SQLITE_UPDATE = 23;\nexport const SQLITE_ATTACH = 24;\nexport const SQLITE_DETACH = 25;\nexport const SQLITE_ALTER_TABLE = 26;\nexport const SQLITE_REINDEX = 27;\nexport const SQLITE_ANALYZE = 28;\nexport const SQLITE_CREATE_VTABLE = 29;\nexport const SQLITE_DROP_VTABLE = 30;\nexport const SQLITE_FUNCTION = 31;\nexport const SQLITE_SAVEPOINT = 32;\nexport const SQLITE_COPY = 0;\nexport const SQLITE_RECURSIVE = 33;\n\n// Authorizer return codes\nexport const SQLITE_DENY = 1;\nexport const SQLITE_IGNORE = 2;\n\n// Limit categories\nexport const SQLITE_LIMIT_LENGTH = 0;\nexport const SQLITE_LIMIT_SQL_LENGTH = 1;\nexport const SQLITE_LIMIT_COLUMN = 2;\nexport const SQLITE_LIMIT_EXPR_DEPTH = 3;\nexport const SQLITE_LIMIT_COMPOUND_SELECT = 4;\nexport const SQLITE_LIMIT_VDBE_OP = 5;\nexport const SQLITE_LIMIT_FUNCTION_ARG = 6;\nexport const SQLITE_LIMIT_ATTACHED = 7;\nexport const SQLITE_LIMIT_LIKE_PATTERN_LENGTH = 8;\nexport const SQLITE_LIMIT_VARIABLE_NUMBER = 9;\nexport const SQLITE_LIMIT_TRIGGER_DEPTH = 10;\nexport const SQLITE_LIMIT_WORKER_THREADS = 11;\n\nexport const SQLITE_PREPARE_PERSISTENT = 0x01;\nexport const SQLITE_PREPARE_NORMALIZED = 0x02;\nexport const SQLITE_PREPARE_NO_VTAB = 0x04;","import * as SQLite from '@journeyapps/wa-sqlite';\nimport { BaseObserver } from '@powersync/common';\nimport { Mutex } from 'async-mutex';\n/**\n * List of currently tested virtual filesystems\n */\nexport var WASQLiteVFS;\n(function (WASQLiteVFS) {\n WASQLiteVFS[\"IDBBatchAtomicVFS\"] = \"IDBBatchAtomicVFS\";\n WASQLiteVFS[\"OPFSCoopSyncVFS\"] = \"OPFSCoopSyncVFS\";\n WASQLiteVFS[\"AccessHandlePoolVFS\"] = \"AccessHandlePoolVFS\";\n})(WASQLiteVFS || (WASQLiteVFS = {}));\n/**\n * @internal\n */\nexport const AsyncWASQLiteModuleFactory = async () => {\n const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');\n return factory();\n};\n/**\n * @internal\n */\nexport const MultiCipherAsyncWASQLiteModuleFactory = async () => {\n const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs');\n return factory();\n};\n/**\n * @internal\n */\nexport const SyncWASQLiteModuleFactory = async () => {\n const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite.mjs');\n return factory();\n};\n/**\n * @internal\n */\nexport const MultiCipherSyncWASQLiteModuleFactory = async () => {\n const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs');\n return factory();\n};\n/**\n * @internal\n */\nexport const DEFAULT_MODULE_FACTORIES = {\n [WASQLiteVFS.IDBBatchAtomicVFS]: async (options) => {\n let module;\n if (options.encryptionKey) {\n module = await MultiCipherAsyncWASQLiteModuleFactory();\n }\n else {\n module = await AsyncWASQLiteModuleFactory();\n }\n const { IDBBatchAtomicVFS } = await import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');\n return {\n module,\n // @ts-expect-error The types for this static method are missing upstream\n vfs: await IDBBatchAtomicVFS.create(options.dbFileName, module, { lockPolicy: 'exclusive' })\n };\n },\n [WASQLiteVFS.AccessHandlePoolVFS]: async (options) => {\n let module;\n if (options.encryptionKey) {\n module = await MultiCipherSyncWASQLiteModuleFactory();\n }\n else {\n module = await SyncWASQLiteModuleFactory();\n }\n // @ts-expect-error The types for this static method are missing upstream\n const { AccessHandlePoolVFS } = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');\n return {\n module,\n vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)\n };\n },\n [WASQLiteVFS.OPFSCoopSyncVFS]: async (options) => {\n let module;\n if (options.encryptionKey) {\n module = await MultiCipherSyncWASQLiteModuleFactory();\n }\n else {\n module = await SyncWASQLiteModuleFactory();\n }\n // @ts-expect-error The types for this static method are missing upstream\n const { OPFSCoopSyncVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');\n const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);\n return {\n module,\n vfs\n };\n }\n};\n/**\n * @internal\n * WA-SQLite connection which directly interfaces with WA-SQLite.\n * This is usually instantiated inside a worker.\n */\nexport class WASqliteConnection extends BaseObserver {\n options;\n _sqliteAPI = null;\n _dbP = null;\n _moduleFactory;\n updatedTables;\n updateTimer;\n statementMutex;\n broadcastChannel;\n /**\n * Unique id for this specific connection. This is used to prevent broadcast table change\n * notification loops.\n */\n connectionId;\n _holdCounter;\n _holdId;\n constructor(options) {\n super();\n this.options = options;\n this.updatedTables = new Set();\n this.updateTimer = null;\n this.broadcastChannel = null;\n this.connectionId = new Date().valueOf() + Math.random();\n this.statementMutex = new Mutex();\n this._moduleFactory = DEFAULT_MODULE_FACTORIES[this.options.vfs];\n this._holdCounter = 0;\n this._holdId = null;\n }\n /**\n * Gets the id for the current hold.\n * This can be used to check for invalid states.\n */\n get currentHoldId() {\n return this._holdId;\n }\n get sqliteAPI() {\n if (!this._sqliteAPI) {\n throw new Error(`Initialization has not completed`);\n }\n return this._sqliteAPI;\n }\n get dbP() {\n if (!this._dbP) {\n throw new Error(`Initialization has not completed`);\n }\n return this._dbP;\n }\n /**\n * Checks if the database connection is in autocommit mode.\n * @returns true if in autocommit mode, false if in a transaction\n */\n async isAutoCommit() {\n return this.sqliteAPI.get_autocommit(this.dbP) != 0;\n }\n async markHold() {\n const previousHoldId = this._holdId;\n this._holdId = `${++this._holdCounter}`;\n if (previousHoldId) {\n await this.iterateAsyncListeners(async (cb) => cb.holdOverwritten?.(previousHoldId));\n }\n return this._holdId;\n }\n async releaseHold(holdId) {\n if (holdId != this._holdId) {\n throw new Error(`Invalid hold state, expected ${this._holdId} but got ${holdId}`);\n }\n this._holdId = null;\n }\n async openDB() {\n this._dbP = await this.sqliteAPI.open_v2(this.options.dbFilename);\n return this._dbP;\n }\n async executeEncryptionPragma() {\n if (this.options.encryptionKey) {\n await this.executeSingleStatement(`PRAGMA key = \"${this.options.encryptionKey}\"`);\n }\n return;\n }\n async openSQLiteAPI() {\n const { module, vfs } = await this._moduleFactory({\n dbFileName: this.options.dbFilename,\n encryptionKey: this.options.encryptionKey\n });\n const sqlite3 = SQLite.Factory(module);\n sqlite3.vfs_register(vfs, true);\n /**\n * Register the PowerSync core SQLite extension\n */\n module.ccall('powersync_init_static', 'int', []);\n /**\n * Create the multiple cipher vfs if an encryption key is provided\n */\n if (this.options.encryptionKey) {\n const createResult = module.ccall('sqlite3mc_vfs_create', 'int', ['string', 'int'], [this.options.dbFilename, 1]);\n if (createResult !== 0) {\n throw new Error('Failed to create multiple cipher vfs, Database encryption will not work');\n }\n }\n return sqlite3;\n }\n registerBroadcastListeners() {\n this.broadcastChannel = new BroadcastChannel(`${this.options.dbFilename}-table-updates`);\n this.broadcastChannel.addEventListener('message', (event) => {\n const data = event.data;\n if (this.connectionId == data.connectionId) {\n // Ignore messages from the same connection\n return;\n }\n // Ensuring that we don't rebroadcast the same message\n this.queueTableUpdate(data.changedTables, false);\n });\n }\n queueTableUpdate(tableNames, shouldBroadcast = true) {\n tableNames.forEach((tableName) => this.updatedTables.add(tableName));\n if (this.updateTimer == null) {\n this.updateTimer = setTimeout(() => this.fireUpdates(shouldBroadcast), 0);\n }\n }\n async init() {\n this._sqliteAPI = await this.openSQLiteAPI();\n await this.openDB();\n this.registerBroadcastListeners();\n await this.executeSingleStatement(`PRAGMA temp_store = ${this.options.temporaryStorage};`);\n await this.executeEncryptionPragma();\n await this.executeSingleStatement(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);\n this.sqliteAPI.update_hook(this.dbP, (updateType, dbName, tableName) => {\n if (!tableName) {\n return;\n }\n const changedTables = new Set([tableName]);\n this.queueTableUpdate(changedTables);\n });\n }\n async getConfig() {\n return this.options;\n }\n fireUpdates(shouldBroadcast = true) {\n this.updateTimer = null;\n const event = { tables: [...this.updatedTables], groupedUpdates: {}, rawUpdates: [] };\n // Share to other connections\n if (shouldBroadcast) {\n this.broadcastChannel.postMessage({\n changedTables: this.updatedTables,\n connectionId: this.connectionId\n });\n }\n this.updatedTables.clear();\n this.iterateListeners((cb) => cb.tablesUpdated?.(event));\n }\n /**\n * This executes SQL statements in a batch.\n */\n async executeBatch(sql, bindings) {\n return this.acquireExecuteLock(async () => {\n let affectedRows = 0;\n try {\n await this.executeSingleStatement('BEGIN TRANSACTION');\n const wrappedBindings = bindings ? bindings : [];\n for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {\n if (stmt === null) {\n return {\n rowsAffected: 0,\n rows: { _array: [], length: 0 }\n };\n }\n //Prepare statement once\n for (const binding of wrappedBindings) {\n // TODO not sure why this is needed currently, but booleans break\n for (let i = 0; i < binding.length; i++) {\n const b = binding[i];\n if (typeof b == 'boolean') {\n binding[i] = b ? 1 : 0;\n }\n }\n if (bindings) {\n this.sqliteAPI.bind_collection(stmt, binding);\n }\n const result = await this.sqliteAPI.step(stmt);\n if (result === SQLite.SQLITE_DONE) {\n //The value returned by sqlite3_changes() immediately after an INSERT, UPDATE or DELETE statement run on a view is always zero.\n affectedRows += this.sqliteAPI.changes(this.dbP);\n }\n this.sqliteAPI.reset(stmt);\n }\n }\n await this.executeSingleStatement('COMMIT');\n }\n catch (err) {\n await this.executeSingleStatement('ROLLBACK');\n return {\n rowsAffected: 0,\n rows: { _array: [], length: 0 }\n };\n }\n const result = {\n rowsAffected: affectedRows,\n rows: { _array: [], length: 0 }\n };\n return result;\n });\n }\n /**\n * This executes single SQL statements inside a requested lock.\n */\n async execute(sql, bindings) {\n // Running multiple statements on the same connection concurrently should not be allowed\n return this.acquireExecuteLock(async () => {\n return this.executeSingleStatement(sql, bindings);\n });\n }\n async executeRaw(sql, bindings) {\n return this.acquireExecuteLock(async () => {\n return this.executeSingleStatementRaw(sql, bindings);\n });\n }\n async close() {\n this.broadcastChannel?.close();\n await this.acquireExecuteLock(async () => {\n /**\n * Running the close operation inside the same execute mutex prevents errors like:\n * ```\n * unable to close due to unfinalized statements or unfinished backups\n * ```\n */\n await this.sqliteAPI.close(this.dbP);\n });\n }\n async registerOnTableChange(callback) {\n return this.registerListener({\n tablesUpdated: (event) => callback(event)\n });\n }\n /**\n * This requests a lock for executing statements.\n * Should only be used internally.\n */\n acquireExecuteLock = (callback) => {\n return this.statementMutex.runExclusive(callback);\n };\n /**\n * This executes a single statement using SQLite3.\n */\n async executeSingleStatement(sql, bindings) {\n const results = await this._execute(sql, bindings);\n const rows = [];\n for (const resultSet of results) {\n for (const row of resultSet.rows) {\n const outRow = {};\n resultSet.columns.forEach((key, index) => {\n outRow[key] = row[index];\n });\n rows.push(outRow);\n }\n }\n const result = {\n insertId: this.sqliteAPI.last_insert_id(this.dbP),\n rowsAffected: this.sqliteAPI.changes(this.dbP),\n rows: {\n _array: rows,\n length: rows.length\n }\n };\n return result;\n }\n /**\n * This executes a single statement using SQLite3 and returns the results as an array of arrays.\n */\n async executeSingleStatementRaw(sql, bindings) {\n const results = await this._execute(sql, bindings);\n return results.flatMap((resultset) => resultset.rows.map((row) => resultset.columns.map((_, index) => row[index])));\n }\n async _execute(sql, bindings) {\n const results = [];\n for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {\n let columns;\n const wrappedBindings = bindings ? [bindings] : [[]];\n for (const binding of wrappedBindings) {\n // TODO not sure why this is needed currently, but booleans break\n binding.forEach((b, index, arr) => {\n if (typeof b == 'boolean') {\n arr[index] = b ? 1 : 0;\n }\n });\n this.sqliteAPI.reset(stmt);\n if (bindings) {\n this.sqliteAPI.bind_collection(stmt, binding);\n }\n const rows = [];\n while ((await this.sqliteAPI.step(stmt)) === SQLite.SQLITE_ROW) {\n const row = this.sqliteAPI.row(stmt);\n rows.push(row);\n }\n columns = columns ?? this.sqliteAPI.column_names(stmt);\n if (columns.length) {\n results.push({ columns, rows });\n }\n }\n // When binding parameters, only a single statement is executed.\n if (bindings) {\n break;\n }\n }\n return results;\n }\n}\n","export const getNavigatorLocks = () => {\n if ('locks' in navigator && navigator.locks) {\n return navigator.locks;\n }\n throw new Error('Navigator locks are not available in an insecure context. Use a secure context such as HTTPS or http://localhost.');\n};\n","export class SharedWASQLiteConnection {\n options;\n isClosing;\n // Keeps track if this current hold if the shared connection has a hold\n activeHoldId;\n constructor(options) {\n this.options = options;\n // Add this client ID to the set of known clients\n this.clientIds.add(options.clientId);\n this.isClosing = false;\n this.activeHoldId = null;\n }\n get logger() {\n return this.options.logger;\n }\n get dbEntry() {\n return this.options.dbMap.get(this.options.dbFilename);\n }\n get connection() {\n return this.dbEntry.db;\n }\n get clientIds() {\n return this.dbEntry.clientIds;\n }\n async init() {\n // No-op since the connection is already initialized when it was created\n }\n async markHold() {\n this.activeHoldId = await this.connection.markHold();\n return this.activeHoldId;\n }\n async releaseHold(id) {\n try {\n await this.connection.releaseHold(id);\n }\n finally {\n this.activeHoldId = null;\n }\n }\n async isAutoCommit() {\n return this.connection.isAutoCommit();\n }\n /**\n * Handles closing of a shared connection.\n * The connection is only closed if there are no active clients using it.\n */\n async close() {\n // This prevents further statements on this connection from being executed\n this.isClosing = true;\n const { clientIds, logger } = this;\n const { clientId, dbFilename, dbMap } = this.options;\n logger.debug(`Close requested from client ${clientId} of ${[...clientIds]}`);\n clientIds.delete(clientId);\n if (this.activeHoldId) {\n // We can't cleanup here since we're not in a lock context.\n // The cleanup will occur once a new hold is acquired.\n this.logger.info(`Hold ${this.activeHoldId} was still active when the connection was closed. Cleanup will occur once a new hold is acquired.`);\n }\n if (clientIds.size == 0) {\n logger.debug(`Closing connection to ${this.options}.`);\n const connection = this.connection;\n dbMap.delete(dbFilename);\n await connection.close();\n return;\n }\n logger.debug(`Connection to ${dbFilename} not closed yet due to active clients.`);\n return;\n }\n async withClosing(action) {\n if (this.isClosing) {\n throw new Error('Connection is closing');\n }\n return action();\n }\n async execute(sql, params) {\n return this.withClosing(() => this.connection.execute(sql, params));\n }\n async executeRaw(sql, params) {\n return this.withClosing(() => this.connection.executeRaw(sql, params));\n }\n executeBatch(sql, params) {\n return this.withClosing(() => this.connection.executeBatch(sql, params));\n }\n registerOnTableChange(callback) {\n return this.connection.registerOnTableChange(callback);\n }\n getConfig() {\n return this.connection.getConfig();\n }\n}\n","import * as Comlink from 'comlink';\nimport { WASqliteConnection } from '../../db/adapters/wa-sqlite/WASQLiteConnection.js';\n/**\n * A Small proxy wrapper around the WASqliteConnection.\n * This ensures that certain return types are properly proxied.\n */\nexport class WorkerWASQLiteConnection extends WASqliteConnection {\n async registerOnTableChange(callback) {\n // Proxy the callback remove function\n return Comlink.proxy(await super.registerOnTableChange(callback));\n }\n}\n","import { Mutex } from 'async-mutex';\n\n// https://www.sqlite.org/lang_expr.html#castexpr\nvar ColumnType;\n(function (ColumnType) {\n ColumnType[\"TEXT\"] = \"TEXT\";\n ColumnType[\"INTEGER\"] = \"INTEGER\";\n ColumnType[\"REAL\"] = \"REAL\";\n})(ColumnType || (ColumnType = {}));\nconst text = {\n type: ColumnType.TEXT\n};\nconst integer = {\n type: ColumnType.INTEGER\n};\nconst real = {\n type: ColumnType.REAL\n};\n// powersync-sqlite-core limits the number of column per table to 1999, due to internal SQLite limits.\n// In earlier versions this was limited to 63.\nconst MAX_AMOUNT_OF_COLUMNS = 1999;\nconst column = {\n text,\n integer,\n real\n};\nclass Column {\n options;\n constructor(options) {\n this.options = options;\n }\n get name() {\n return this.options.name;\n }\n get type() {\n return this.options.type;\n }\n toJSON() {\n return {\n name: this.name,\n type: this.type\n };\n }\n}\n\nconst DEFAULT_INDEX_COLUMN_OPTIONS = {\n ascending: true\n};\nclass IndexedColumn {\n options;\n static createAscending(column) {\n return new IndexedColumn({\n name: column,\n ascending: true\n });\n }\n constructor(options) {\n this.options = { ...DEFAULT_INDEX_COLUMN_OPTIONS, ...options };\n }\n get name() {\n return this.options.name;\n }\n get ascending() {\n return this.options.ascending;\n }\n toJSON(table) {\n return {\n name: this.name,\n ascending: this.ascending,\n type: table.columns.find((column) => column.name === this.name)?.type ?? ColumnType.TEXT\n };\n }\n}\n\nconst DEFAULT_INDEX_OPTIONS = {\n columns: []\n};\nclass Index {\n options;\n static createAscending(options, columnNames) {\n return new Index({\n ...options,\n columns: columnNames.map((name) => IndexedColumn.createAscending(name))\n });\n }\n constructor(options) {\n this.options = options;\n this.options = { ...DEFAULT_INDEX_OPTIONS, ...options };\n }\n get name() {\n return this.options.name;\n }\n get columns() {\n return this.options.columns ?? [];\n }\n toJSON(table) {\n return {\n name: this.name,\n columns: this.columns.map((c) => c.toJSON(table))\n };\n }\n}\n\n/**\n * @internal Not exported from `index.ts`.\n */\nfunction encodeTableOptions(options) {\n const trackPrevious = options.trackPrevious;\n return {\n local_only: options.localOnly,\n insert_only: options.insertOnly,\n include_old: trackPrevious && (trackPrevious.columns ?? true),\n include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,\n include_metadata: options.trackMetadata,\n ignore_empty_update: options.ignoreEmptyUpdates\n };\n}\n\nconst DEFAULT_TABLE_OPTIONS = {\n indexes: [],\n insertOnly: false,\n localOnly: false,\n trackPrevious: false,\n trackMetadata: false,\n ignoreEmptyUpdates: false\n};\nconst InvalidSQLCharacters = /[\"'%,.#\\s[\\]]/;\nclass Table {\n options;\n _mappedColumns;\n static createLocalOnly(options) {\n return new Table({ ...options, localOnly: true, insertOnly: false });\n }\n static createInsertOnly(options) {\n return new Table({ ...options, localOnly: false, insertOnly: true });\n }\n /**\n * Create a table.\n * @deprecated This was only only included for TableV2 and is no longer necessary.\n * Prefer to use new Table() directly.\n *\n * TODO remove in the next major release.\n */\n static createTable(name, table) {\n return new Table({\n name,\n columns: table.columns,\n indexes: table.indexes,\n localOnly: table.options.localOnly,\n insertOnly: table.options.insertOnly,\n viewName: table.options.viewName\n });\n }\n constructor(optionsOrColumns, v2Options) {\n if (this.isTableV1(optionsOrColumns)) {\n this.initTableV1(optionsOrColumns);\n }\n else {\n this.initTableV2(optionsOrColumns, v2Options);\n }\n }\n copyWithName(name) {\n return new Table({\n ...this.options,\n name\n });\n }\n isTableV1(arg) {\n return 'columns' in arg && Array.isArray(arg.columns);\n }\n initTableV1(options) {\n this.options = {\n ...options,\n indexes: options.indexes || []\n };\n this.applyDefaultOptions();\n }\n initTableV2(columns, options) {\n const convertedColumns = Object.entries(columns).map(([name, columnInfo]) => new Column({ name, type: columnInfo.type }));\n const convertedIndexes = Object.entries(options?.indexes ?? {}).map(([name, columnNames]) => new Index({\n name,\n columns: columnNames.map((name) => new IndexedColumn({\n name: name.replace(/^-/, ''),\n ascending: !name.startsWith('-')\n }))\n }));\n this.options = {\n name: '',\n columns: convertedColumns,\n indexes: convertedIndexes,\n viewName: options?.viewName,\n insertOnly: options?.insertOnly,\n localOnly: options?.localOnly,\n trackPrevious: options?.trackPrevious,\n trackMetadata: options?.trackMetadata,\n ignoreEmptyUpdates: options?.ignoreEmptyUpdates\n };\n this.applyDefaultOptions();\n this._mappedColumns = columns;\n }\n applyDefaultOptions() {\n this.options.insertOnly ??= DEFAULT_TABLE_OPTIONS.insertOnly;\n this.options.localOnly ??= DEFAULT_TABLE_OPTIONS.localOnly;\n this.options.trackPrevious ??= DEFAULT_TABLE_OPTIONS.trackPrevious;\n this.options.trackMetadata ??= DEFAULT_TABLE_OPTIONS.trackMetadata;\n this.options.ignoreEmptyUpdates ??= DEFAULT_TABLE_OPTIONS.ignoreEmptyUpdates;\n }\n get name() {\n return this.options.name;\n }\n get viewNameOverride() {\n return this.options.viewName;\n }\n get viewName() {\n return this.viewNameOverride ?? this.name;\n }\n get columns() {\n return this.options.columns;\n }\n get columnMap() {\n return (this._mappedColumns ??\n this.columns.reduce((hash, column) => {\n hash[column.name] = { type: column.type ?? ColumnType.TEXT };\n return hash;\n }, {}));\n }\n get indexes() {\n return this.options.indexes ?? [];\n }\n get localOnly() {\n return this.options.localOnly;\n }\n get insertOnly() {\n return this.options.insertOnly;\n }\n get trackPrevious() {\n return this.options.trackPrevious;\n }\n get trackMetadata() {\n return this.options.trackMetadata;\n }\n get ignoreEmptyUpdates() {\n return this.options.ignoreEmptyUpdates;\n }\n get internalName() {\n if (this.options.localOnly) {\n return `ps_data_local__${this.name}`;\n }\n return `ps_data__${this.name}`;\n }\n get validName() {\n if (InvalidSQLCharacters.test(this.name)) {\n return false;\n }\n if (this.viewNameOverride != null && InvalidSQLCharacters.test(this.viewNameOverride)) {\n return false;\n }\n return true;\n }\n validate() {\n if (InvalidSQLCharacters.test(this.name)) {\n throw new Error(`Invalid characters in table name: ${this.name}`);\n }\n if (this.viewNameOverride && InvalidSQLCharacters.test(this.viewNameOverride)) {\n throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);\n }\n if (this.columns.length > MAX_AMOUNT_OF_COLUMNS) {\n throw new Error(`Table has too many columns. The maximum number of columns is ${MAX_AMOUNT_OF_COLUMNS}.`);\n }\n if (this.trackMetadata && this.localOnly) {\n throw new Error(`Can't include metadata for local-only tables.`);\n }\n if (this.trackPrevious != false && this.localOnly) {\n throw new Error(`Can't include old values for local-only tables.`);\n }\n const columnNames = new Set();\n columnNames.add('id');\n for (const column of this.columns) {\n const { name: columnName } = column;\n if (column.name === 'id') {\n throw new Error(`An id column is automatically added, custom id columns are not supported`);\n }\n if (columnNames.has(columnName)) {\n throw new Error(`Duplicate column ${columnName}`);\n }\n if (InvalidSQLCharacters.test(columnName)) {\n throw new Error(`Invalid characters in column name: ${column.name}`);\n }\n columnNames.add(columnName);\n }\n const indexNames = new Set();\n for (const index of this.indexes) {\n if (indexNames.has(index.name)) {\n throw new Error(`Duplicate index ${index.name}`);\n }\n if (InvalidSQLCharacters.test(index.name)) {\n throw new Error(`Invalid characters in index name: ${index.name}`);\n }\n for (const column of index.columns) {\n if (!columnNames.has(column.name)) {\n throw new Error(`Column ${column.name} not found for index ${index.name}`);\n }\n }\n indexNames.add(index.name);\n }\n }\n toJSON() {\n return {\n name: this.name,\n view_name: this.viewName,\n columns: this.columns.map((c) => c.toJSON()),\n indexes: this.indexes.map((e) => e.toJSON(this)),\n ...encodeTableOptions(this)\n };\n }\n}\n\nconst ATTACHMENT_TABLE = 'attachments';\n/**\n * Maps a database row to an AttachmentRecord.\n *\n * @param row - The database row object\n * @returns The corresponding AttachmentRecord\n *\n * @experimental\n */\nfunction attachmentFromSql(row) {\n return {\n id: row.id,\n filename: row.filename,\n localUri: row.local_uri,\n size: row.size,\n mediaType: row.media_type,\n timestamp: row.timestamp,\n metaData: row.meta_data,\n hasSynced: row.has_synced === 1,\n state: row.state\n };\n}\n/**\n * AttachmentState represents the current synchronization state of an attachment.\n *\n * @experimental\n */\nvar AttachmentState;\n(function (AttachmentState) {\n AttachmentState[AttachmentState[\"QUEUED_UPLOAD\"] = 0] = \"QUEUED_UPLOAD\";\n AttachmentState[AttachmentState[\"QUEUED_DOWNLOAD\"] = 1] = \"QUEUED_DOWNLOAD\";\n AttachmentState[AttachmentState[\"QUEUED_DELETE\"] = 2] = \"QUEUED_DELETE\";\n AttachmentState[AttachmentState[\"SYNCED\"] = 3] = \"SYNCED\";\n AttachmentState[AttachmentState[\"ARCHIVED\"] = 4] = \"ARCHIVED\"; // Attachment has been orphaned, i.e. the associated record has been deleted\n})(AttachmentState || (AttachmentState = {}));\n/**\n * AttachmentTable defines the schema for the attachment queue table.\n *\n * @internal\n */\nclass AttachmentTable extends Table {\n constructor(options) {\n super({\n filename: column.text,\n local_uri: column.text,\n timestamp: column.integer,\n size: column.integer,\n media_type: column.text,\n state: column.integer, // Corresponds to AttachmentState\n has_synced: column.integer,\n meta_data: column.text\n }, {\n ...options,\n viewName: options?.viewName ?? ATTACHMENT_TABLE,\n localOnly: true,\n insertOnly: false\n });\n }\n}\n\n/**\n * AttachmentContext provides database operations for managing attachment records.\n *\n * Provides methods to query, insert, update, and delete attachment records with\n * proper transaction management through PowerSync.\n *\n * @internal\n */\nclass AttachmentContext {\n /** PowerSync database instance for executing queries */\n db;\n /** Name of the database table storing attachment records */\n tableName;\n /** Logger instance for diagnostic information */\n logger;\n /** Maximum number of archived attachments to keep before cleanup */\n archivedCacheLimit = 100;\n /**\n * Creates a new AttachmentContext instance.\n *\n * @param db - PowerSync database instance\n * @param tableName - Name of the table storing attachment records. Default: 'attachments'\n * @param logger - Logger instance for diagnostic output\n */\n constructor(db, tableName = 'attachments', logger, archivedCacheLimit) {\n this.db = db;\n this.tableName = tableName;\n this.logger = logger;\n this.archivedCacheLimit = archivedCacheLimit;\n }\n /**\n * Retrieves all active attachments that require synchronization.\n * Active attachments include those queued for upload, download, or delete.\n * Results are ordered by timestamp in ascending order.\n *\n * @returns Promise resolving to an array of active attachment records\n */\n async getActiveAttachments() {\n const attachments = await this.db.getAll(\n /* sql */\n `\n SELECT\n *\n FROM\n ${this.tableName}\n WHERE\n state = ?\n OR state = ?\n OR state = ?\n ORDER BY\n timestamp ASC\n `, [AttachmentState.QUEUED_UPLOAD, AttachmentState.QUEUED_DOWNLOAD, AttachmentState.QUEUED_DELETE]);\n return attachments.map(attachmentFromSql);\n }\n /**\n * Retrieves all archived attachments.\n *\n * Archived attachments are no longer referenced but haven't been permanently deleted.\n * These are candidates for cleanup operations to free up storage space.\n *\n * @returns Promise resolving to an array of archived attachment records\n */\n async getArchivedAttachments() {\n const attachments = await this.db.getAll(\n /* sql */\n `\n SELECT\n *\n FROM\n ${this.tableName}\n WHERE\n state = ?\n ORDER BY\n timestamp ASC\n `, [AttachmentState.ARCHIVED]);\n return attachments.map(attachmentFromSql);\n }\n /**\n * Retrieves all attachment records regardless of state.\n * Results are ordered by timestamp in ascending order.\n *\n * @returns Promise resolving to an array of all attachment records\n */\n async getAttachments() {\n const attachments = await this.db.getAll(\n /* sql */\n `\n SELECT\n *\n FROM\n ${this.tableName}\n ORDER BY\n timestamp ASC\n `, []);\n return attachments.map(attachmentFromSql);\n }\n /**\n * Inserts or updates an attachment record within an existing transaction.\n *\n * Performs an upsert operation (INSERT OR REPLACE). Must be called within\n * an active database transaction context.\n *\n * @param attachment - The attachment record to upsert\n * @param context - Active database transaction context\n */\n async upsertAttachment(attachment, context) {\n await context.execute(\n /* sql */\n `\n INSERT\n OR REPLACE INTO ${this.tableName} (\n id,\n filename,\n local_uri,\n size,\n media_type,\n timestamp,\n state,\n has_synced,\n meta_data\n )\n VALUES\n (?, ?, ?, ?, ?, ?, ?, ?, ?)\n `, [\n attachment.id,\n attachment.filename,\n attachment.localUri || null,\n attachment.size || null,\n attachment.mediaType || null,\n attachment.timestamp,\n attachment.state,\n attachment.hasSynced ? 1 : 0,\n attachment.metaData || null\n ]);\n }\n async getAttachment(id) {\n const attachment = await this.db.get(\n /* sql */\n `\n SELECT\n *\n FROM\n ${this.tableName}\n WHERE\n id = ?\n `, [id]);\n return attachment ? attachmentFromSql(attachment) : undefined;\n }\n /**\n * Permanently deletes an attachment record from the database.\n *\n * This operation removes the attachment record but does not delete\n * the associated local or remote files. File deletion should be handled\n * separately through the appropriate storage adapters.\n *\n * @param attachmentId - Unique identifier of the attachment to delete\n */\n async deleteAttachment(attachmentId) {\n await this.db.writeTransaction((tx) => tx.execute(\n /* sql */\n `\n DELETE FROM ${this.tableName}\n WHERE\n id = ?\n `, [attachmentId]));\n }\n async clearQueue() {\n await this.db.writeTransaction((tx) => tx.execute(/* sql */ ` DELETE FROM ${this.tableName} `));\n }\n async deleteArchivedAttachments(callback) {\n const limit = 1000;\n const results = await this.db.getAll(\n /* sql */\n `\n SELECT\n *\n FROM\n ${this.tableName}\n WHERE\n state = ?\n ORDER BY\n timestamp DESC\n LIMIT\n ?\n OFFSET\n ?\n `, [AttachmentState.ARCHIVED, limit, this.archivedCacheLimit]);\n const archivedAttachments = results.map(attachmentFromSql);\n if (archivedAttachments.length === 0)\n return false;\n await callback?.(archivedAttachments);\n this.logger.info(`Deleting ${archivedAttachments.length} archived attachments. Archived attachment exceeds cache archiveCacheLimit of ${this.archivedCacheLimit}.`);\n const ids = archivedAttachments.map((attachment) => attachment.id);\n await this.db.execute(\n /* sql */\n `\n DELETE FROM ${this.tableName}\n WHERE\n id IN (\n SELECT\n json_each.value\n FROM\n json_each (?)\n );\n `, [JSON.stringify(ids)]);\n this.logger.info(`Deleted ${archivedAttachments.length} archived attachments`);\n return archivedAttachments.length < limit;\n }\n /**\n * Saves multiple attachment records in a single transaction.\n *\n * All updates are saved in a single batch after processing.\n * If the attachments array is empty, no database operations are performed.\n *\n * @param attachments - Array of attachment records to save\n */\n async saveAttachments(attachments) {\n if (attachments.length === 0) {\n return;\n }\n await this.db.writeTransaction(async (tx) => {\n for (const attachment of attachments) {\n await this.upsertAttachment(attachment, tx);\n }\n });\n }\n}\n\nvar WatchedQueryListenerEvent;\n(function (WatchedQueryListenerEvent) {\n WatchedQueryListenerEvent[\"ON_DATA\"] = \"onData\";\n WatchedQueryListenerEvent[\"ON_ERROR\"] = \"onError\";\n WatchedQueryListenerEvent[\"ON_STATE_CHANGE\"] = \"onStateChange\";\n WatchedQueryListenerEvent[\"SETTINGS_WILL_UPDATE\"] = \"settingsWillUpdate\";\n WatchedQueryListenerEvent[\"CLOSED\"] = \"closed\";\n})(WatchedQueryListenerEvent || (WatchedQueryListenerEvent = {}));\nconst DEFAULT_WATCH_THROTTLE_MS = 30;\nconst DEFAULT_WATCH_QUERY_OPTIONS = {\n throttleMs: DEFAULT_WATCH_THROTTLE_MS,\n reportFetching: true\n};\n\n/**\n * Orchestrates attachment synchronization between local and remote storage.\n * Handles uploads, downloads, deletions, and state transitions.\n *\n * @internal\n */\nclass SyncingService {\n attachmentService;\n localStorage;\n remoteStorage;\n logger;\n errorHandler;\n constructor(attachmentService, localStorage, remoteStorage, logger, errorHandler) {\n this.attachmentService = attachmentService;\n this.localStorage = localStorage;\n this.remoteStorage = remoteStorage;\n this.logger = logger;\n this.errorHandler = errorHandler;\n }\n /**\n * Processes attachments based on their state (upload, download, or delete).\n * All updates are saved in a single batch after processing.\n *\n * @param attachments - Array of attachment records to process\n * @param context - Attachment context for database operations\n * @returns Promise that resolves when all attachments have been processed and saved\n */\n async processAttachments(attachments, context) {\n const updatedAttachments = [];\n for (const attachment of attachments) {\n switch (attachment.state) {\n case AttachmentState.QUEUED_UPLOAD:\n const uploaded = await this.uploadAttachment(attachment);\n updatedAttachments.push(uploaded);\n break;\n case AttachmentState.QUEUED_DOWNLOAD:\n const downloaded = await this.downloadAttachment(attachment);\n updatedAttachments.push(downloaded);\n break;\n case AttachmentState.QUEUED_DELETE:\n const deleted = await this.deleteAttachment(attachment);\n updatedAttachments.push(deleted);\n break;\n }\n }\n await context.saveAttachments(updatedAttachments);\n }\n /**\n * Uploads an attachment from local storage to remote storage.\n * On success, marks as SYNCED. On failure, defers to error handler or archives.\n *\n * @param attachment - The attachment record to upload\n * @returns Updated attachment record with new state\n * @throws Error if the attachment has no localUri\n */\n async uploadAttachment(attachment) {\n this.logger.info(`Uploading attachment ${attachment.filename}`);\n try {\n if (attachment.localUri == null) {\n throw new Error(`No localUri for attachment ${attachment.id}`);\n }\n const fileBlob = await this.localStorage.readFile(attachment.localUri);\n await this.remoteStorage.uploadFile(fileBlob, attachment);\n return {\n ...attachment,\n state: AttachmentState.SYNCED,\n hasSynced: true\n };\n }\n catch (error) {\n const shouldRetry = (await this.errorHandler?.onUploadError(attachment, error)) ?? true;\n if (!shouldRetry) {\n return {\n ...attachment,\n state: AttachmentState.ARCHIVED\n };\n }\n return attachment;\n }\n }\n /**\n * Downloads an attachment from remote storage to local storage.\n * Retrieves the file, converts to base64, and saves locally.\n * On success, marks as SYNCED. On failure, defers to error handler or archives.\n *\n * @param attachment - The attachment record to download\n * @returns Updated attachment record with local URI and new state\n */\n async downloadAttachment(attachment) {\n this.logger.info(`Downloading attachment ${attachment.filename}`);\n try {\n const fileData = await this.remoteStorage.downloadFile(attachment);\n const localUri = this.localStorage.getLocalUri(attachment.filename);\n await this.localStorage.saveFile(localUri, fileData);\n return {\n ...attachment,\n state: AttachmentState.SYNCED,\n localUri: localUri,\n hasSynced: true\n };\n }\n catch (error) {\n const shouldRetry = (await this.errorHandler?.onDownloadError(attachment, error)) ?? true;\n if (!shouldRetry) {\n return {\n ...attachment,\n state: AttachmentState.ARCHIVED\n };\n }\n return attachment;\n }\n }\n /**\n * Deletes an attachment from both remote and local storage.\n * Removes the remote file, local file (if exists), and the attachment record.\n * On failure, defers to error handler or archives.\n *\n * @param attachment - The attachment record to delete\n * @returns Updated attachment record\n */\n async deleteAttachment(attachment) {\n try {\n await this.remoteStorage.deleteFile(attachment);\n if (attachment.localUri) {\n await this.localStorage.deleteFile(attachment.localUri);\n }\n await this.attachmentService.withContext(async (ctx) => {\n await ctx.deleteAttachment(attachment.id);\n });\n return {\n ...attachment,\n state: AttachmentState.ARCHIVED\n };\n }\n catch (error) {\n const shouldRetry = (await this.errorHandler?.onDeleteError(attachment, error)) ?? true;\n if (!shouldRetry) {\n return {\n ...attachment,\n state: AttachmentState.ARCHIVED\n };\n }\n return attachment;\n }\n }\n /**\n * Performs cleanup of archived attachments by removing their local files and records.\n * Errors during local file deletion are logged but do not prevent record deletion.\n */\n async deleteArchivedAttachments(context) {\n return await context.deleteArchivedAttachments(async (archivedAttachments) => {\n for (const attachment of archivedAttachments) {\n if (attachment.localUri) {\n try {\n await this.localStorage.deleteFile(attachment.localUri);\n }\n catch (error) {\n this.logger.error('Error deleting local file for archived attachment', error);\n }\n }\n }\n });\n }\n}\n\n/**\n * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.\n */\nasync function mutexRunExclusive(mutex, callback, options) {\n return new Promise((resolve, reject) => {\n const timeout = options?.timeoutMs;\n let timedOut = false;\n const timeoutId = timeout\n ? setTimeout(() => {\n timedOut = true;\n reject(new Error('Timeout waiting for lock'));\n }, timeout)\n : undefined;\n mutex.runExclusive(async () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n if (timedOut)\n return;\n try {\n resolve(await callback());\n }\n catch (ex) {\n reject(ex);\n }\n });\n });\n}\n\n/**\n * Service for querying and watching attachment records in the database.\n *\n * @internal\n */\nclass AttachmentService {\n db;\n logger;\n tableName;\n mutex = new Mutex();\n context;\n constructor(db, logger, tableName = 'attachments', archivedCacheLimit = 100) {\n this.db = db;\n this.logger = logger;\n this.tableName = tableName;\n this.context = new AttachmentContext(db, tableName, logger, archivedCacheLimit);\n }\n /**\n * Creates a differential watch query for active attachments requiring synchronization.\n * @returns Watch query that emits changes for queued uploads, downloads, and deletes\n */\n watchActiveAttachments({ throttleMs } = {}) {\n this.logger.info('Watching active attachments...');\n const watch = this.db\n .query({\n sql: /* sql */ `\n SELECT\n *\n FROM\n ${this.tableName}\n WHERE\n state = ?\n OR state = ?\n OR state = ?\n ORDER BY\n timestamp ASC\n `,\n parameters: [AttachmentState.QUEUED_UPLOAD, AttachmentState.QUEUED_DOWNLOAD, AttachmentState.QUEUED_DELETE]\n })\n .differentialWatch({ throttleMs });\n return watch;\n }\n /**\n * Executes a callback with exclusive access to the attachment context.\n */\n async withContext(callback) {\n return mutexRunExclusive(this.mutex, async () => {\n return callback(this.context);\n });\n }\n}\n\n/**\n * AttachmentQueue manages the lifecycle and synchronization of attachments\n * between local and remote storage.\n * Provides automatic synchronization, upload/download queuing, attachment monitoring,\n * verification and repair of local files, and cleanup of archived attachments.\n *\n * @experimental\n * @alpha This is currently experimental and may change without a major version bump.\n */\nclass AttachmentQueue {\n /** Timer for periodic synchronization operations */\n periodicSyncTimer;\n /** Service for synchronizing attachments between local and remote storage */\n syncingService;\n /** Adapter for local file storage operations */\n localStorage;\n /** Adapter for remote file storage operations */\n remoteStorage;\n /**\n * Callback function to watch for changes in attachment references in your data model.\n *\n * This should be implemented by the user of AttachmentQueue to monitor changes in your application's\n * data that reference attachments. When attachments are added, removed, or modified,\n * this callback should trigger the onUpdate function with the current set of attachments.\n */\n watchAttachments;\n /** Name of the database table storing attachment records */\n tableName;\n /** Logger instance for diagnostic information */\n logger;\n /** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */\n syncIntervalMs = 30 * 1000;\n /** Duration in milliseconds to throttle sync operations */\n syncThrottleDuration;\n /** Whether to automatically download remote attachments. Default: true */\n downloadAttachments = true;\n /** Maximum number of archived attachments to keep before cleanup. Default: 100 */\n archivedCacheLimit;\n /** Service for managing attachment-related database operations */\n attachmentService;\n /** PowerSync database instance */\n db;\n /** Cleanup function for status change listener */\n statusListenerDispose;\n watchActiveAttachments;\n watchAttachmentsAbortController;\n /**\n * Creates a new AttachmentQueue instance.\n *\n * @param options - Configuration options\n * @param options.db - PowerSync database instance\n * @param options.remoteStorage - Remote storage adapter for upload/download operations\n * @param options.localStorage - Local storage adapter for file persistence\n * @param options.watchAttachments - Callback for monitoring attachment changes in your data model\n * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'\n * @param options.logger - Logger instance. Defaults to db.logger\n * @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000\n * @param options.syncThrottleDuration - Throttle duration for sync operations in milliseconds. Default: 1000\n * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true\n * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100\n */\n constructor({ db, localStorage, remoteStorage, watchAttachments, logger, tableName = ATTACHMENT_TABLE, syncIntervalMs = 30 * 1000, syncThrottleDuration = DEFAULT_WATCH_THROTTLE_MS, downloadAttachments = true, archivedCacheLimit = 100, errorHandler }) {\n this.db = db;\n this.remoteStorage = remoteStorage;\n this.localStorage = localStorage;\n this.watchAttachments = watchAttachments;\n this.tableName = tableName;\n this.syncIntervalMs = syncIntervalMs;\n this.syncThrottleDuration = syncThrottleDuration;\n this.archivedCacheLimit = archivedCacheLimit;\n this.downloadAttachments = downloadAttachments;\n this.logger = logger ?? db.logger;\n this.attachmentService = new AttachmentService(db, this.logger, tableName, archivedCacheLimit);\n this.syncingService = new SyncingService(this.attachmentService, localStorage, remoteStorage, this.logger, errorHandler);\n }\n /**\n * Generates a new attachment ID using a SQLite UUID function.\n *\n * @returns Promise resolving to the new attachment ID\n */\n async generateAttachmentId() {\n return this.db.get('SELECT uuid() as id').then((row) => row.id);\n }\n /**\n * Starts the attachment synchronization process.\n *\n * This method:\n * - Stops any existing sync operations\n * - Sets up periodic synchronization based on syncIntervalMs\n * - Registers listeners for active attachment changes\n * - Processes watched attachments to queue uploads/downloads\n * - Handles state transitions for archived and new attachments\n */\n async startSync() {\n await this.stopSync();\n this.watchActiveAttachments = this.attachmentService.watchActiveAttachments({\n throttleMs: this.syncThrottleDuration\n });\n // immediately invoke the sync storage to initialize local storage\n await this.localStorage.initialize();\n await this.verifyAttachments();\n // Sync storage periodically\n this.periodicSyncTimer = setInterval(async () => {\n await this.syncStorage();\n }, this.syncIntervalMs);\n // Sync storage when there is a change in active attachments\n this.watchActiveAttachments.registerListener({\n onDiff: async () => {\n await this.syncStorage();\n }\n });\n this.statusListenerDispose = this.db.registerListener({\n statusChanged: (status) => {\n if (status.connected) {\n // Device came online, process attachments immediately\n this.syncStorage().catch((error) => {\n this.logger.error('Error syncing storage on connection:', error);\n });\n }\n }\n });\n this.watchAttachmentsAbortController = new AbortController();\n const signal = this.watchAttachmentsAbortController.signal;\n // Process attachments when there is a change in watched attachments\n this.watchAttachments(async (watchedAttachments) => {\n // Skip processing if sync has been stopped\n if (signal.aborted) {\n return;\n }\n await this.attachmentService.withContext(async (ctx) => {\n // Need to get all the attachments which are tracked in the DB.\n // We might need to restore an archived attachment.\n const currentAttachments = await ctx.getAttachments();\n const attachmentUpdates = [];\n for (const watchedAttachment of watchedAttachments) {\n const existingQueueItem = currentAttachments.find((a) => a.id === watchedAttachment.id);\n if (!existingQueueItem) {\n // Item is watched but not in the queue yet. Need to add it.\n if (!this.downloadAttachments) {\n continue;\n }\n const filename = watchedAttachment.filename ?? `${watchedAttachment.id}.${watchedAttachment.fileExtension}`;\n attachmentUpdates.push({\n id: watchedAttachment.id,\n filename,\n state: AttachmentState.QUEUED_DOWNLOAD,\n hasSynced: false,\n metaData: watchedAttachment.metaData,\n timestamp: new Date().getTime()\n });\n continue;\n }\n if (existingQueueItem.state === AttachmentState.ARCHIVED) {\n // The attachment is present again. Need to queue it for sync.\n // We might be able to optimize this in future\n if (existingQueueItem.hasSynced === true) {\n // No remote action required, we can restore the record (avoids deletion)\n attachmentUpdates.push({\n ...existingQueueItem,\n state: AttachmentState.SYNCED\n });\n }\n else {\n // The localURI should be set if the record was meant to be uploaded\n // and hasSynced is false then\n // it must be an upload operation\n const newState = existingQueueItem.localUri == null ? AttachmentState.QUEUED_DOWNLOAD : AttachmentState.QUEUED_UPLOAD;\n attachmentUpdates.push({\n ...existingQueueItem,\n state: newState\n });\n }\n }\n }\n for (const attachment of currentAttachments) {\n const notInWatchedItems = watchedAttachments.find((i) => i.id === attachment.id) == null;\n if (notInWatchedItems) {\n switch (attachment.state) {\n case AttachmentState.QUEUED_DELETE:\n case AttachmentState.QUEUED_UPLOAD:\n // Only archive if it has synced\n if (attachment.hasSynced === true) {\n attachmentUpdates.push({\n ...attachment,\n state: AttachmentState.ARCHIVED\n });\n }\n break;\n default:\n // Archive other states such as QUEUED_DOWNLOAD\n attachmentUpdates.push({\n ...attachment,\n state: AttachmentState.ARCHIVED\n });\n }\n }\n }\n if (attachmentUpdates.length > 0) {\n await ctx.saveAttachments(attachmentUpdates);\n }\n });\n }, signal);\n }\n /**\n * Synchronizes all active attachments between local and remote storage.\n *\n * This is called automatically at regular intervals when sync is started,\n * but can also be called manually to trigger an immediate sync.\n */\n async syncStorage() {\n await this.attachmentService.withContext(async (ctx) => {\n const activeAttachments = await ctx.getActiveAttachments();\n await this.localStorage.initialize();\n await this.syncingService.processAttachments(activeAttachments, ctx);\n await this.syncingService.deleteArchivedAttachments(ctx);\n });\n }\n /**\n * Stops the attachment synchronization process.\n *\n * Clears the periodic sync timer and closes all active attachment watchers.\n */\n async stopSync() {\n clearInterval(this.periodicSyncTimer);\n this.periodicSyncTimer = undefined;\n if (this.watchActiveAttachments)\n await this.watchActiveAttachments.close();\n if (this.watchAttachmentsAbortController) {\n this.watchAttachmentsAbortController.abort();\n }\n if (this.statusListenerDispose) {\n this.statusListenerDispose();\n this.statusListenerDispose = undefined;\n }\n }\n /**\n * Saves a file to local storage and queues it for upload to remote storage.\n *\n * @param options - File save options\n * @param options.data - The file data as ArrayBuffer, Blob, or base64 string\n * @param options.fileExtension - File extension (e.g., 'jpg', 'pdf')\n * @param options.mediaType - MIME type of the file (e.g., 'image/jpeg')\n * @param options.metaData - Optional metadata to associate with the attachment\n * @param options.id - Optional custom ID. If not provided, a UUID will be generated\n * @param options.updateHook - Optional callback to execute additional database operations\n * within the same transaction as the attachment creation\n * @returns Promise resolving to the created attachment record\n */\n async saveFile({ data, fileExtension, mediaType, metaData, id, updateHook }) {\n const resolvedId = id ?? (await this.generateAttachmentId());\n const filename = `${resolvedId}.${fileExtension}`;\n const localUri = this.localStorage.getLocalUri(filename);\n const size = await this.localStorage.saveFile(localUri, data);\n const attachment = {\n id: resolvedId,\n filename,\n mediaType,\n localUri,\n state: AttachmentState.QUEUED_UPLOAD,\n hasSynced: false,\n size,\n timestamp: new Date().getTime(),\n metaData\n };\n await this.attachmentService.withContext(async (ctx) => {\n await ctx.db.writeTransaction(async (tx) => {\n await updateHook?.(tx, attachment);\n await ctx.upsertAttachment(attachment, tx);\n });\n });\n return attachment;\n }\n async deleteFile({ id, updateHook }) {\n await this.attachmentService.withContext(async (ctx) => {\n const attachment = await ctx.getAttachment(id);\n if (!attachment) {\n throw new Error(`Attachment with id ${id} not found`);\n }\n await ctx.db.writeTransaction(async (tx) => {\n await updateHook?.(tx, attachment);\n await ctx.upsertAttachment({\n ...attachment,\n state: AttachmentState.QUEUED_DELETE,\n hasSynced: false\n }, tx);\n });\n });\n }\n async expireCache() {\n let isDone = false;\n while (!isDone) {\n await this.attachmentService.withContext(async (ctx) => {\n isDone = await this.syncingService.deleteArchivedAttachments(ctx);\n });\n }\n }\n async clearQueue() {\n await this.attachmentService.withContext(async (ctx) => {\n await ctx.clearQueue();\n });\n await this.localStorage.clear();\n }\n /**\n * Verifies the integrity of all attachment records and repairs inconsistencies.\n *\n * This method checks each attachment record against the local filesystem and:\n * - Updates localUri if the file exists at a different path\n * - Archives attachments with missing local files that haven't been uploaded\n * - Requeues synced attachments for download if their local files are missing\n */\n async verifyAttachments() {\n await this.attachmentService.withContext(async (ctx) => {\n const attachments = await ctx.getAttachments();\n const updates = [];\n for (const attachment of attachments) {\n if (attachment.localUri == null) {\n continue;\n }\n const exists = await this.localStorage.fileExists(attachment.localUri);\n if (exists) {\n // The file exists, this is correct\n continue;\n }\n const newLocalUri = this.localStorage.getLocalUri(attachment.filename);\n const newExists = await this.localStorage.fileExists(newLocalUri);\n if (newExists) {\n // The file exists locally but the localUri is broken, we update it.\n updates.push({\n ...attachment,\n localUri: newLocalUri\n });\n }\n else {\n // the file doesn't exist locally.\n if (attachment.state === AttachmentState.SYNCED) {\n // the file has been successfully synced to remote storage but is missing\n // we download it again\n updates.push({\n ...attachment,\n state: AttachmentState.QUEUED_DOWNLOAD,\n localUri: undefined\n });\n }\n else {\n // the file wasn't successfully synced to remote storage, we archive it\n updates.push({\n ...attachment,\n state: AttachmentState.ARCHIVED,\n localUri: undefined // Clears the value\n });\n }\n }\n }\n await ctx.saveAttachments(updates);\n });\n }\n}\n\nvar EncodingType;\n(function (EncodingType) {\n EncodingType[\"UTF8\"] = \"utf8\";\n EncodingType[\"Base64\"] = \"base64\";\n})(EncodingType || (EncodingType = {}));\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar dom = {};\n\nvar eventIterator = {};\n\nvar hasRequiredEventIterator;\n\nfunction requireEventIterator () {\n\tif (hasRequiredEventIterator) return eventIterator;\n\thasRequiredEventIterator = 1;\n\tObject.defineProperty(eventIterator, \"__esModule\", { value: true });\n\tclass EventQueue {\n\t constructor() {\n\t this.pullQueue = [];\n\t this.pushQueue = [];\n\t this.eventHandlers = {};\n\t this.isPaused = false;\n\t this.isStopped = false;\n\t }\n\t push(value) {\n\t if (this.isStopped)\n\t return;\n\t const resolution = { value, done: false };\n\t if (this.pullQueue.length) {\n\t const placeholder = this.pullQueue.shift();\n\t if (placeholder)\n\t placeholder.resolve(resolution);\n\t }\n\t else {\n\t this.pushQueue.push(Promise.resolve(resolution));\n\t if (this.highWaterMark !== undefined &&\n\t this.pushQueue.length >= this.highWaterMark &&\n\t !this.isPaused) {\n\t this.isPaused = true;\n\t if (this.eventHandlers.highWater) {\n\t this.eventHandlers.highWater();\n\t }\n\t else if (console) {\n\t console.warn(`EventIterator queue reached ${this.pushQueue.length} items`);\n\t }\n\t }\n\t }\n\t }\n\t stop() {\n\t if (this.isStopped)\n\t return;\n\t this.isStopped = true;\n\t this.remove();\n\t for (const placeholder of this.pullQueue) {\n\t placeholder.resolve({ value: undefined, done: true });\n\t }\n\t this.pullQueue.length = 0;\n\t }\n\t fail(error) {\n\t if (this.isStopped)\n\t return;\n\t this.isStopped = true;\n\t this.remove();\n\t if (this.pullQueue.length) {\n\t for (const placeholder of this.pullQueue) {\n\t placeholder.reject(error);\n\t }\n\t this.pullQueue.length = 0;\n\t }\n\t else {\n\t const rejection = Promise.reject(error);\n\t /* Attach error handler to avoid leaking an unhandled promise rejection. */\n\t rejection.catch(() => { });\n\t this.pushQueue.push(rejection);\n\t }\n\t }\n\t remove() {\n\t Promise.resolve().then(() => {\n\t if (this.removeCallback)\n\t this.removeCallback();\n\t });\n\t }\n\t [Symbol.asyncIterator]() {\n\t return {\n\t next: (value) => {\n\t const result = this.pushQueue.shift();\n\t if (result) {\n\t if (this.lowWaterMark !== undefined &&\n\t this.pushQueue.length <= this.lowWaterMark &&\n\t this.isPaused) {\n\t this.isPaused = false;\n\t if (this.eventHandlers.lowWater) {\n\t this.eventHandlers.lowWater();\n\t }\n\t }\n\t return result;\n\t }\n\t else if (this.isStopped) {\n\t return Promise.resolve({ value: undefined, done: true });\n\t }\n\t else {\n\t return new Promise((resolve, reject) => {\n\t this.pullQueue.push({ resolve, reject });\n\t });\n\t }\n\t },\n\t return: () => {\n\t this.isStopped = true;\n\t this.pushQueue.length = 0;\n\t this.remove();\n\t return Promise.resolve({ value: undefined, done: true });\n\t },\n\t };\n\t }\n\t}\n\tclass EventIterator {\n\t constructor(listen, { highWaterMark = 100, lowWaterMark = 1 } = {}) {\n\t const queue = new EventQueue();\n\t queue.highWaterMark = highWaterMark;\n\t queue.lowWaterMark = lowWaterMark;\n\t queue.removeCallback =\n\t listen({\n\t push: value => queue.push(value),\n\t stop: () => queue.stop(),\n\t fail: error => queue.fail(error),\n\t on: (event, fn) => {\n\t queue.eventHandlers[event] = fn;\n\t },\n\t }) || (() => { });\n\t this[Symbol.asyncIterator] = () => queue[Symbol.asyncIterator]();\n\t Object.freeze(this);\n\t }\n\t}\n\teventIterator.EventIterator = EventIterator;\n\teventIterator.default = EventIterator;\n\treturn eventIterator;\n}\n\nvar hasRequiredDom;\n\nfunction requireDom () {\n\tif (hasRequiredDom) return dom;\n\thasRequiredDom = 1;\n\tObject.defineProperty(dom, \"__esModule\", { value: true });\n\tconst event_iterator_1 = requireEventIterator();\n\tdom.EventIterator = event_iterator_1.EventIterator;\n\tfunction subscribe(event, options, evOptions) {\n\t return new event_iterator_1.EventIterator(({ push }) => {\n\t this.addEventListener(event, push, options);\n\t return () => this.removeEventListener(event, push, options);\n\t }, evOptions);\n\t}\n\tdom.subscribe = subscribe;\n\tdom.default = event_iterator_1.EventIterator;\n\treturn dom;\n}\n\nvar domExports = requireDom();\n\nvar logger$1 = {exports: {}};\n\n/*!\r\n * js-logger - http://github.com/jonnyreeves/js-logger\r\n * Jonny Reeves, http://jonnyreeves.co.uk/\r\n * js-logger may be freely distributed under the MIT license.\r\n */\nvar logger = logger$1.exports;\n\nvar hasRequiredLogger;\n\nfunction requireLogger () {\n\tif (hasRequiredLogger) return logger$1.exports;\n\thasRequiredLogger = 1;\n\t(function (module) {\n\t\t(function (global) {\r\n\r\n\t\t\t// Top level module for the global, static logger instance.\r\n\t\t\tvar Logger = { };\r\n\r\n\t\t\t// For those that are at home that are keeping score.\r\n\t\t\tLogger.VERSION = \"1.6.1\";\r\n\r\n\t\t\t// Function which handles all incoming log messages.\r\n\t\t\tvar logHandler;\r\n\r\n\t\t\t// Map of ContextualLogger instances by name; used by Logger.get() to return the same named instance.\r\n\t\t\tvar contextualLoggersByNameMap = {};\r\n\r\n\t\t\t// Polyfill for ES5's Function.bind.\r\n\t\t\tvar bind = function(scope, func) {\r\n\t\t\t\treturn function() {\r\n\t\t\t\t\treturn func.apply(scope, arguments);\r\n\t\t\t\t};\r\n\t\t\t};\r\n\r\n\t\t\t// Super exciting object merger-matron 9000 adding another 100 bytes to your download.\r\n\t\t\tvar merge = function () {\r\n\t\t\t\tvar args = arguments, target = args[0], key, i;\r\n\t\t\t\tfor (i = 1; i < args.length; i++) {\r\n\t\t\t\t\tfor (key in args[i]) {\r\n\t\t\t\t\t\tif (!(key in target) && args[i].hasOwnProperty(key)) {\r\n\t\t\t\t\t\t\ttarget[key] = args[i][key];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn target;\r\n\t\t\t};\r\n\r\n\t\t\t// Helper to define a logging level object; helps with optimisation.\r\n\t\t\tvar defineLogLevel = function(value, name) {\r\n\t\t\t\treturn { value: value, name: name };\r\n\t\t\t};\r\n\r\n\t\t\t// Predefined logging levels.\r\n\t\t\tLogger.TRACE = defineLogLevel(1, 'TRACE');\r\n\t\t\tLogger.DEBUG = defineLogLevel(2, 'DEBUG');\r\n\t\t\tLogger.INFO = defineLogLevel(3, 'INFO');\r\n\t\t\tLogger.TIME = defineLogLevel(4, 'TIME');\r\n\t\t\tLogger.WARN = defineLogLevel(5, 'WARN');\r\n\t\t\tLogger.ERROR = defineLogLevel(8, 'ERROR');\r\n\t\t\tLogger.OFF = defineLogLevel(99, 'OFF');\r\n\r\n\t\t\t// Inner class which performs the bulk of the work; ContextualLogger instances can be configured independently\r\n\t\t\t// of each other.\r\n\t\t\tvar ContextualLogger = function(defaultContext) {\r\n\t\t\t\tthis.context = defaultContext;\r\n\t\t\t\tthis.setLevel(defaultContext.filterLevel);\r\n\t\t\t\tthis.log = this.info; // Convenience alias.\r\n\t\t\t};\r\n\r\n\t\t\tContextualLogger.prototype = {\r\n\t\t\t\t// Changes the current logging level for the logging instance.\r\n\t\t\t\tsetLevel: function (newLevel) {\r\n\t\t\t\t\t// Ensure the supplied Level object looks valid.\r\n\t\t\t\t\tif (newLevel && \"value\" in newLevel) {\r\n\t\t\t\t\t\tthis.context.filterLevel = newLevel;\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\t\t\t\t\r\n\t\t\t\t// Gets the current logging level for the logging instance\r\n\t\t\t\tgetLevel: function () {\r\n\t\t\t\t\treturn this.context.filterLevel;\r\n\t\t\t\t},\r\n\r\n\t\t\t\t// Is the logger configured to output messages at the supplied level?\r\n\t\t\t\tenabledFor: function (lvl) {\r\n\t\t\t\t\tvar filterLevel = this.context.filterLevel;\r\n\t\t\t\t\treturn lvl.value >= filterLevel.value;\r\n\t\t\t\t},\r\n\r\n\t\t\t\ttrace: function () {\r\n\t\t\t\t\tthis.invoke(Logger.TRACE, arguments);\r\n\t\t\t\t},\r\n\r\n\t\t\t\tdebug: function () {\r\n\t\t\t\t\tthis.invoke(Logger.DEBUG, arguments);\r\n\t\t\t\t},\r\n\r\n\t\t\t\tinfo: function () {\r\n\t\t\t\t\tthis.invoke(Logger.INFO, arguments);\r\n\t\t\t\t},\r\n\r\n\t\t\t\twarn: function () {\r\n\t\t\t\t\tthis.invoke(Logger.WARN, arguments);\r\n\t\t\t\t},\r\n\r\n\t\t\t\terror: function () {\r\n\t\t\t\t\tthis.invoke(Logger.ERROR, arguments);\r\n\t\t\t\t},\r\n\r\n\t\t\t\ttime: function (label) {\r\n\t\t\t\t\tif (typeof label === 'string' && label.length > 0) {\r\n\t\t\t\t\t\tthis.invoke(Logger.TIME, [ label, 'start' ]);\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\r\n\t\t\t\ttimeEnd: function (label) {\r\n\t\t\t\t\tif (typeof label === 'string' && label.length > 0) {\r\n\t\t\t\t\t\tthis.invoke(Logger.TIME, [ label, 'end' ]);\r\n\t\t\t\t\t}\r\n\t\t\t\t},\r\n\r\n\t\t\t\t// Invokes the logger callback if it's not being filtered.\r\n\t\t\t\tinvoke: function (level, msgArgs) {\r\n\t\t\t\t\tif (logHandler && this.enabledFor(level)) {\r\n\t\t\t\t\t\tlogHandler(msgArgs, merge({ level: level }, this.context));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\r\n\t\t\t// Protected instance which all calls to the to level `Logger` module will be routed through.\r\n\t\t\tvar globalLogger = new ContextualLogger({ filterLevel: Logger.OFF });\r\n\r\n\t\t\t// Configure the global Logger instance.\r\n\t\t\t(function() {\r\n\t\t\t\t// Shortcut for optimisers.\r\n\t\t\t\tvar L = Logger;\r\n\r\n\t\t\t\tL.enabledFor = bind(globalLogger, globalLogger.enabledFor);\r\n\t\t\t\tL.trace = bind(globalLogger, globalLogger.trace);\r\n\t\t\t\tL.debug = bind(globalLogger, globalLogger.debug);\r\n\t\t\t\tL.time = bind(globalLogger, globalLogger.time);\r\n\t\t\t\tL.timeEnd = bind(globalLogger, globalLogger.timeEnd);\r\n\t\t\t\tL.info = bind(globalLogger, globalLogger.info);\r\n\t\t\t\tL.warn = bind(globalLogger, globalLogger.warn);\r\n\t\t\t\tL.error = bind(globalLogger, globalLogger.error);\r\n\r\n\t\t\t\t// Don't forget the convenience alias!\r\n\t\t\t\tL.log = L.info;\r\n\t\t\t}());\r\n\r\n\t\t\t// Set the global logging handler. The supplied function should expect two arguments, the first being an arguments\r\n\t\t\t// object with the supplied log messages and the second being a context object which contains a hash of stateful\r\n\t\t\t// parameters which the logging function can consume.\r\n\t\t\tLogger.setHandler = function (func) {\r\n\t\t\t\tlogHandler = func;\r\n\t\t\t};\r\n\r\n\t\t\t// Sets the global logging filter level which applies to *all* previously registered, and future Logger instances.\r\n\t\t\t// (note that named loggers (retrieved via `Logger.get`) can be configured independently if required).\r\n\t\t\tLogger.setLevel = function(level) {\r\n\t\t\t\t// Set the globalLogger's level.\r\n\t\t\t\tglobalLogger.setLevel(level);\r\n\r\n\t\t\t\t// Apply this level to all registered contextual loggers.\r\n\t\t\t\tfor (var key in contextualLoggersByNameMap) {\r\n\t\t\t\t\tif (contextualLoggersByNameMap.hasOwnProperty(key)) {\r\n\t\t\t\t\t\tcontextualLoggersByNameMap[key].setLevel(level);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\r\n\t\t\t// Gets the global logging filter level\r\n\t\t\tLogger.getLevel = function() {\r\n\t\t\t\treturn globalLogger.getLevel();\r\n\t\t\t};\r\n\r\n\t\t\t// Retrieve a ContextualLogger instance. Note that named loggers automatically inherit the global logger's level,\r\n\t\t\t// default context and log handler.\r\n\t\t\tLogger.get = function (name) {\r\n\t\t\t\t// All logger instances are cached so they can be configured ahead of use.\r\n\t\t\t\treturn contextualLoggersByNameMap[name] ||\r\n\t\t\t\t\t(contextualLoggersByNameMap[name] = new ContextualLogger(merge({ name: name }, globalLogger.context)));\r\n\t\t\t};\r\n\r\n\t\t\t// CreateDefaultHandler returns a handler function which can be passed to `Logger.setHandler()` which will\r\n\t\t\t// write to the window's console object (if present); the optional options object can be used to customise the\r\n\t\t\t// formatter used to format each log message.\r\n\t\t\tLogger.createDefaultHandler = function (options) {\r\n\t\t\t\toptions = options || {};\r\n\r\n\t\t\t\toptions.formatter = options.formatter || function defaultMessageFormatter(messages, context) {\r\n\t\t\t\t\t// Prepend the logger's name to the log message for easy identification.\r\n\t\t\t\t\tif (context.name) {\r\n\t\t\t\t\t\tmessages.unshift(\"[\" + context.name + \"]\");\r\n\t\t\t\t\t}\r\n\t\t\t\t};\r\n\r\n\t\t\t\t// Map of timestamps by timer labels used to track `#time` and `#timeEnd()` invocations in environments\r\n\t\t\t\t// that don't offer a native console method.\r\n\t\t\t\tvar timerStartTimeByLabelMap = {};\r\n\r\n\t\t\t\t// Support for IE8+ (and other, slightly more sane environments)\r\n\t\t\t\tvar invokeConsoleMethod = function (hdlr, messages) {\r\n\t\t\t\t\tFunction.prototype.apply.call(hdlr, console, messages);\r\n\t\t\t\t};\r\n\r\n\t\t\t\t// Check for the presence of a logger.\r\n\t\t\t\tif (typeof console === \"undefined\") {\r\n\t\t\t\t\treturn function () { /* no console */ };\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn function(messages, context) {\r\n\t\t\t\t\t// Convert arguments object to Array.\r\n\t\t\t\t\tmessages = Array.prototype.slice.call(messages);\r\n\r\n\t\t\t\t\tvar hdlr = console.log;\r\n\t\t\t\t\tvar timerLabel;\r\n\r\n\t\t\t\t\tif (context.level === Logger.TIME) {\r\n\t\t\t\t\t\ttimerLabel = (context.name ? '[' + context.name + '] ' : '') + messages[0];\r\n\r\n\t\t\t\t\t\tif (messages[1] === 'start') {\r\n\t\t\t\t\t\t\tif (console.time) {\r\n\t\t\t\t\t\t\t\tconsole.time(timerLabel);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\ttimerStartTimeByLabelMap[timerLabel] = new Date().getTime();\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tif (console.timeEnd) {\r\n\t\t\t\t\t\t\t\tconsole.timeEnd(timerLabel);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\tinvokeConsoleMethod(hdlr, [ timerLabel + ': ' +\r\n\t\t\t\t\t\t\t\t\t(new Date().getTime() - timerStartTimeByLabelMap[timerLabel]) + 'ms' ]);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\t// Delegate through to custom warn/error loggers if present on the console.\r\n\t\t\t\t\t\tif (context.level === Logger.WARN && console.warn) {\r\n\t\t\t\t\t\t\thdlr = console.warn;\r\n\t\t\t\t\t\t} else if (context.level === Logger.ERROR && console.error) {\r\n\t\t\t\t\t\t\thdlr = console.error;\r\n\t\t\t\t\t\t} else if (context.level === Logger.INFO && console.info) {\r\n\t\t\t\t\t\t\thdlr = console.info;\r\n\t\t\t\t\t\t} else if (context.level === Logger.DEBUG && console.debug) {\r\n\t\t\t\t\t\t\thdlr = console.debug;\r\n\t\t\t\t\t\t} else if (context.level === Logger.TRACE && console.trace) {\r\n\t\t\t\t\t\t\thdlr = console.trace;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\toptions.formatter(messages, context);\r\n\t\t\t\t\t\tinvokeConsoleMethod(hdlr, messages);\r\n\t\t\t\t\t}\r\n\t\t\t\t};\r\n\t\t\t};\r\n\r\n\t\t\t// Configure and example a Default implementation which writes to the `window.console` (if present). The\r\n\t\t\t// `options` hash can be used to configure the default logLevel and provide a custom message formatter.\r\n\t\t\tLogger.useDefaults = function(options) {\r\n\t\t\t\tLogger.setLevel(options && options.defaultLevel || Logger.DEBUG);\r\n\t\t\t\tLogger.setHandler(Logger.createDefaultHandler(options));\r\n\t\t\t};\r\n\r\n\t\t\t// Createa an alias to useDefaults to avoid reaking a react-hooks rule.\r\n\t\t\tLogger.setDefaults = Logger.useDefaults;\r\n\r\n\t\t\t// Export to popular environments boilerplate.\r\n\t\t\tif (module.exports) {\r\n\t\t\t\tmodule.exports = Logger;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tLogger._prevLogger = global.Logger;\r\n\r\n\t\t\t\tLogger.noConflict = function () {\r\n\t\t\t\t\tglobal.Logger = Logger._prevLogger;\r\n\t\t\t\t\treturn Logger;\r\n\t\t\t\t};\r\n\r\n\t\t\t\tglobal.Logger = Logger;\r\n\t\t\t}\r\n\t\t}(logger)); \n\t} (logger$1));\n\treturn logger$1.exports;\n}\n\nvar loggerExports = requireLogger();\nvar Logger = /*@__PURE__*/getDefaultExportFromCjs(loggerExports);\n\n/**\n * Set of generic interfaces to allow PowerSync compatibility with\n * different SQLite DB implementations.\n */\n/**\n * Update table operation numbers from SQLite\n */\nvar RowUpdateType;\n(function (RowUpdateType) {\n RowUpdateType[RowUpdateType[\"SQLITE_INSERT\"] = 18] = \"SQLITE_INSERT\";\n RowUpdateType[RowUpdateType[\"SQLITE_DELETE\"] = 9] = \"SQLITE_DELETE\";\n RowUpdateType[RowUpdateType[\"SQLITE_UPDATE\"] = 23] = \"SQLITE_UPDATE\";\n})(RowUpdateType || (RowUpdateType = {}));\nfunction isBatchedUpdateNotification(update) {\n return 'tables' in update;\n}\nfunction extractTableUpdates(update) {\n return isBatchedUpdateNotification(update) ? update.tables : [update.table];\n}\n\n/**\n * @internal The priority used by the core extension to indicate that a full sync was completed.\n */\nconst FULL_SYNC_PRIORITY = 2147483647;\n/**\n * Provides realtime progress on how PowerSync is downloading rows.\n *\n * The progress until the next complete sync is available through the fields on {@link ProgressWithOperations},\n * which this class implements.\n * Additionally, the {@link SyncProgress.untilPriority} method can be used to otbain progress towards\n * a specific priority (instead of the progress for the entire download).\n *\n * The reported progress always reflects the status towards the end of a sync iteration (after\n * which a consistent snapshot of all buckets is available locally).\n *\n * In rare cases (in particular, when a [compacting](https://docs.powersync.com/usage/lifecycle-maintenance/compacting-buckets)\n * operation takes place between syncs), it's possible for the returned numbers to be slightly\n * inaccurate. For this reason, {@link SyncProgress} should be seen as an approximation of progress.\n * The information returned is good enough to build progress bars, but not exact enough to track\n * individual download counts.\n *\n * Also note that data is downloaded in bulk, which means that individual counters are unlikely\n * to be updated one-by-one.\n */\nclass SyncProgress {\n internal;\n totalOperations;\n downloadedOperations;\n downloadedFraction;\n constructor(internal) {\n this.internal = internal;\n const untilCompletion = this.untilPriority(FULL_SYNC_PRIORITY);\n this.totalOperations = untilCompletion.totalOperations;\n this.downloadedOperations = untilCompletion.downloadedOperations;\n this.downloadedFraction = untilCompletion.downloadedFraction;\n }\n /**\n * Returns download progress towards all data up until the specified priority being received.\n *\n * The returned {@link ProgressWithOperations} tracks the target amount of operations that need\n * to be downloaded in total and how many of them have already been received.\n */\n untilPriority(priority) {\n let total = 0;\n let downloaded = 0;\n for (const progress of Object.values(this.internal)) {\n // Include higher-priority buckets, which are represented by lower numbers.\n if (progress.priority <= priority) {\n downloaded += progress.since_last;\n total += progress.target_count - progress.at_last;\n }\n }\n let progress = total == 0 ? 0.0 : downloaded / total;\n return {\n totalOperations: total,\n downloadedOperations: downloaded,\n downloadedFraction: progress\n };\n }\n}\n\nclass SyncStatus {\n options;\n constructor(options) {\n this.options = options;\n }\n /**\n * Returns the used sync client implementation (either the one implemented in JavaScript or the newer Rust-based\n * implementation).\n *\n * This information is only available after a connection has been requested.\n */\n get clientImplementation() {\n return this.options.clientImplementation;\n }\n /**\n * Indicates if the client is currently connected to the PowerSync service.\n *\n * @returns {boolean} True if connected, false otherwise. Defaults to false if not specified.\n */\n get connected() {\n return this.options.connected ?? false;\n }\n /**\n * Indicates if the client is in the process of establishing a connection to the PowerSync service.\n *\n * @returns {boolean} True if connecting, false otherwise. Defaults to false if not specified.\n */\n get connecting() {\n return this.options.connecting ?? false;\n }\n /**\n * Time that a last sync has fully completed, if any.\n * This timestamp is reset to null after a restart of the PowerSync service.\n *\n * @returns {Date | undefined} The timestamp of the last successful sync, or undefined if no sync has completed.\n */\n get lastSyncedAt() {\n return this.options.lastSyncedAt;\n }\n /**\n * Indicates whether there has been at least one full sync completed since initialization.\n *\n * @returns {boolean | undefined} True if at least one sync has completed, false if no sync has completed,\n * or undefined when the state is still being loaded from the database.\n */\n get hasSynced() {\n return this.options.hasSynced;\n }\n /**\n * Provides the current data flow status regarding uploads and downloads.\n *\n * @returns {SyncDataFlowStatus} An object containing:\n * - downloading: True if actively downloading changes (only when connected is also true)\n * - uploading: True if actively uploading changes\n * Defaults to {downloading: false, uploading: false} if not specified.\n */\n get dataFlowStatus() {\n return (this.options.dataFlow ?? {\n /**\n * true if actively downloading changes.\n * This is only true when {@link connected} is also true.\n */\n downloading: false,\n /**\n * true if uploading changes.\n */\n uploading: false\n });\n }\n /**\n * All sync streams currently being tracked in teh database.\n *\n * This returns null when the database is currently being opened and we don't have reliable information about all\n * included streams yet.\n *\n * @experimental Sync streams are currently in alpha.\n */\n get syncStreams() {\n return this.options.dataFlow?.internalStreamSubscriptions?.map((core) => new SyncStreamStatusView(this, core));\n }\n /**\n * If the `stream` appears in {@link syncStreams}, returns the current status for that stream.\n *\n * @experimental Sync streams are currently in alpha.\n */\n forStream(stream) {\n const asJson = JSON.stringify(stream.parameters);\n const raw = this.options.dataFlow?.internalStreamSubscriptions?.find((r) => r.name == stream.name && asJson == JSON.stringify(r.parameters));\n return raw && new SyncStreamStatusView(this, raw);\n }\n /**\n * Provides sync status information for all bucket priorities, sorted by priority (highest first).\n *\n * @returns {SyncPriorityStatus[]} An array of status entries for different sync priority levels,\n * sorted with highest priorities (lower numbers) first.\n */\n get priorityStatusEntries() {\n return (this.options.priorityStatusEntries ?? []).slice().sort(SyncStatus.comparePriorities);\n }\n /**\n * A realtime progress report on how many operations have been downloaded and\n * how many are necessary in total to complete the next sync iteration.\n *\n * This field is only set when {@link SyncDataFlowStatus#downloading} is also true.\n */\n get downloadProgress() {\n const internalProgress = this.options.dataFlow?.downloadProgress;\n if (internalProgress == null) {\n return null;\n }\n return new SyncProgress(internalProgress);\n }\n /**\n * Reports the sync status (a pair of {@link SyncStatus#hasSynced} and {@link SyncStatus#lastSyncedAt} fields)\n * for a specific bucket priority level.\n *\n * When buckets with different priorities are declared, PowerSync may choose to synchronize higher-priority\n * buckets first. When a consistent view over all buckets for all priorities up until the given priority is\n * reached, PowerSync makes data from those buckets available before lower-priority buckets have finished\n * syncing.\n *\n * This method returns the status for the requested priority or the next higher priority level that has\n * status information available. This is because when PowerSync makes data for a given priority available,\n * all buckets in higher-priorities are guaranteed to be consistent with that checkpoint.\n *\n * For example, if PowerSync just finished synchronizing buckets in priority level 3, calling this method\n * with a priority of 1 may return information for priority level 3.\n *\n * @param {number} priority The bucket priority for which the status should be reported\n * @returns {SyncPriorityStatus} Status information for the requested priority level or the next higher level with available status\n */\n statusForPriority(priority) {\n // priorityStatusEntries are sorted by ascending priorities (so higher numbers to lower numbers).\n for (const known of this.priorityStatusEntries) {\n // We look for the first entry that doesn't have a higher priority.\n if (known.priority >= priority) {\n return known;\n }\n }\n // If we have a complete sync, that necessarily includes all priorities.\n return {\n priority,\n lastSyncedAt: this.lastSyncedAt,\n hasSynced: this.hasSynced\n };\n }\n /**\n * Compares this SyncStatus instance with another to determine if they are equal.\n * Equality is determined by comparing the serialized JSON representation of both instances.\n *\n * @param {SyncStatus} status The SyncStatus instance to compare against\n * @returns {boolean} True if the instances are considered equal, false otherwise\n */\n isEqual(status) {\n /**\n * By default Error object are serialized to an empty object.\n * This replaces Errors with more useful information before serialization.\n */\n const replacer = (_, value) => {\n if (value instanceof Error) {\n return {\n name: value.name,\n message: value.message,\n stack: value.stack\n };\n }\n return value;\n };\n return JSON.stringify(this.options, replacer) == JSON.stringify(status.options, replacer);\n }\n /**\n * Creates a human-readable string representation of the current sync status.\n * Includes information about connection state, sync completion, and data flow.\n *\n * @returns {string} A string representation of the sync status\n */\n getMessage() {\n const dataFlow = this.dataFlowStatus;\n return `SyncStatus<connected: ${this.connected} connecting: ${this.connecting} lastSyncedAt: ${this.lastSyncedAt} hasSynced: ${this.hasSynced}. Downloading: ${dataFlow.downloading}. Uploading: ${dataFlow.uploading}. UploadError: ${dataFlow.uploadError}, DownloadError?: ${dataFlow.downloadError}>`;\n }\n /**\n * Serializes the SyncStatus instance to a plain object.\n *\n * @returns {SyncStatusOptions} A plain object representation of the sync status\n */\n toJSON() {\n return {\n connected: this.connected,\n connecting: this.connecting,\n dataFlow: {\n ...this.dataFlowStatus,\n uploadError: this.serializeError(this.dataFlowStatus.uploadError),\n downloadError: this.serializeError(this.dataFlowStatus.downloadError)\n },\n lastSyncedAt: this.lastSyncedAt,\n hasSynced: this.hasSynced,\n priorityStatusEntries: this.priorityStatusEntries\n };\n }\n /**\n * Not all errors are serializable over a MessagePort. E.g. some `DomExceptions` fail to be passed across workers.\n * This explicitly serializes errors in the SyncStatus.\n */\n serializeError(error) {\n if (typeof error == 'undefined') {\n return undefined;\n }\n return {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n }\n static comparePriorities(a, b) {\n return b.priority - a.priority; // Reverse because higher priorities have lower numbers\n }\n}\nclass SyncStreamStatusView {\n status;\n core;\n subscription;\n constructor(status, core) {\n this.status = status;\n this.core = core;\n this.subscription = {\n name: core.name,\n parameters: core.parameters,\n active: core.active,\n isDefault: core.is_default,\n hasExplicitSubscription: core.has_explicit_subscription,\n expiresAt: core.expires_at != null ? new Date(core.expires_at * 1000) : null,\n hasSynced: core.last_synced_at != null,\n lastSyncedAt: core.last_synced_at != null ? new Date(core.last_synced_at * 1000) : null\n };\n }\n get progress() {\n if (this.status.dataFlowStatus.downloadProgress == null) {\n // Don't make download progress public if we're not currently downloading.\n return null;\n }\n const { total, downloaded } = this.core.progress;\n const progress = total == 0 ? 0.0 : downloaded / total;\n return { totalOperations: total, downloadedOperations: downloaded, downloadedFraction: progress };\n }\n get priority() {\n return this.core.priority;\n }\n}\n\nclass UploadQueueStats {\n count;\n size;\n constructor(\n /**\n * Number of records in the upload queue.\n */\n count, \n /**\n * Size of the upload queue in bytes.\n */\n size = null) {\n this.count = count;\n this.size = size;\n }\n toString() {\n if (this.size == null) {\n return `UploadQueueStats<count:${this.count}>`;\n }\n else {\n return `UploadQueueStats<count: $count size: ${this.size / 1024}kB>`;\n }\n }\n}\n\nclass BaseObserver {\n listeners = new Set();\n constructor() { }\n dispose() {\n this.listeners.clear();\n }\n /**\n * Register a listener for updates to the PowerSync client.\n */\n registerListener(listener) {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n iterateListeners(cb) {\n for (const listener of this.listeners) {\n cb(listener);\n }\n }\n async iterateAsyncListeners(cb) {\n for (let i of Array.from(this.listeners.values())) {\n await cb(i);\n }\n }\n}\n\nclass ControlledExecutor {\n task;\n /**\n * Represents the currently running task, which could be a Promise or undefined if no task is running.\n */\n runningTask;\n pendingTaskParam;\n /**\n * Flag to determine if throttling is enabled, which controls whether tasks are queued or run immediately.\n */\n isThrottling;\n closed;\n constructor(task, options) {\n this.task = task;\n const { throttleEnabled = true } = options ?? {};\n this.isThrottling = throttleEnabled;\n this.closed = false;\n }\n schedule(param) {\n if (this.closed) {\n return;\n }\n if (!this.isThrottling) {\n this.task(param);\n return;\n }\n if (this.runningTask) {\n // set or replace the pending task param with latest one\n this.pendingTaskParam = param;\n return;\n }\n this.execute(param);\n }\n dispose() {\n this.closed = true;\n if (this.runningTask) {\n this.runningTask = undefined;\n }\n }\n async execute(param) {\n this.runningTask = this.task(param);\n await this.runningTask;\n this.runningTask = undefined;\n if (this.pendingTaskParam) {\n const pendingParam = this.pendingTaskParam;\n this.pendingTaskParam = undefined;\n this.execute(pendingParam);\n }\n }\n}\n\n/**\n * A ponyfill for `Symbol.asyncIterator` that is compatible with the\n * [recommended polyfill](https://github.com/Azure/azure-sdk-for-js/blob/%40azure/core-asynciterator-polyfill_1.0.2/sdk/core/core-asynciterator-polyfill/src/index.ts#L4-L6)\n * we recommend for React Native.\n *\n * As long as we use this symbol (instead of `for await` and `async *`) in this package, we can be compatible with async\n * iterators without requiring them.\n */\nconst symbolAsyncIterator = Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');\n/**\n * Throttle a function to be called at most once every \"wait\" milliseconds,\n * on the trailing edge.\n *\n * Roughly equivalent to lodash/throttle with {leading: false, trailing: true}\n */\nfunction throttleTrailing(func, wait) {\n let timeoutId = null;\n const later = () => {\n func();\n timeoutId = null;\n };\n return function () {\n if (timeoutId == null) {\n timeoutId = setTimeout(later, wait);\n }\n };\n}\n/**\n * Throttle a function to be called at most once every \"wait\" milliseconds,\n * on the leading and trailing edge.\n *\n * Roughly equivalent to lodash/throttle with {leading: true, trailing: true}\n */\nfunction throttleLeadingTrailing(func, wait) {\n let timeoutId = null;\n let lastCallTime = 0;\n const invokeFunction = () => {\n func();\n lastCallTime = Date.now();\n timeoutId = null;\n };\n return function () {\n const now = Date.now();\n const timeToWait = wait - (now - lastCallTime);\n if (timeToWait <= 0) {\n // Leading edge: Call the function immediately if enough time has passed\n invokeFunction();\n }\n else if (!timeoutId) {\n // Set a timeout for the trailing edge if not already set\n timeoutId = setTimeout(invokeFunction, timeToWait);\n }\n };\n}\n\n/**\n * @internal\n */\nclass ConnectionManager extends BaseObserver {\n options;\n /**\n * Tracks active connection attempts\n */\n connectingPromise;\n /**\n * Tracks actively instantiating a streaming sync implementation.\n */\n syncStreamInitPromise;\n /**\n * Active disconnect operation. Calling disconnect multiple times\n * will resolve to the same operation.\n */\n disconnectingPromise;\n /**\n * Tracks the last parameters supplied to `connect` calls.\n * Calling `connect` multiple times in succession will result in:\n * - 1 pending connection operation which will be aborted.\n * - updating the last set of parameters while waiting for the pending\n * attempt to be aborted\n * - internally connecting with the last set of parameters\n */\n pendingConnectionOptions;\n syncStreamImplementation;\n /**\n * Additional cleanup function which is called after the sync stream implementation\n * is disposed.\n */\n syncDisposer;\n /**\n * Subscriptions managed in this connection manager.\n *\n * On the web, these local subscriptions are merged across tabs by a shared worker.\n */\n locallyActiveSubscriptions = new Map();\n constructor(options) {\n super();\n this.options = options;\n this.connectingPromise = null;\n this.syncStreamInitPromise = null;\n this.disconnectingPromise = null;\n this.pendingConnectionOptions = null;\n this.syncStreamImplementation = null;\n this.syncDisposer = null;\n }\n get connector() {\n return this.pendingConnectionOptions?.connector ?? null;\n }\n get connectionOptions() {\n return this.pendingConnectionOptions?.options ?? null;\n }\n get logger() {\n return this.options.logger;\n }\n async close() {\n await this.syncStreamImplementation?.dispose();\n await this.syncDisposer?.();\n }\n async connect(connector, options) {\n // Keep track if there were pending operations before this call\n const hadPendingOptions = !!this.pendingConnectionOptions;\n // Update pending options to the latest values\n this.pendingConnectionOptions = {\n connector,\n options\n };\n // Disconnecting here provides aborting in progress connection attempts.\n // The connectInternal method will clear pending options once it starts connecting (with the options).\n // We only need to trigger a disconnect here if we have already reached the point of connecting.\n // If we do already have pending options, a disconnect has already been performed.\n // The connectInternal method also does a sanity disconnect to prevent straggler connections.\n // We should also disconnect if we have already completed a connection attempt.\n if (!hadPendingOptions || this.syncStreamImplementation) {\n await this.disconnectInternal();\n }\n // Triggers a connect which checks if pending options are available after the connect completes.\n // The completion can be for a successful, unsuccessful or aborted connection attempt.\n // If pending options are available another connection will be triggered.\n const checkConnection = async () => {\n if (this.pendingConnectionOptions) {\n // Pending options have been placed while connecting.\n // Need to reconnect.\n this.connectingPromise = this.connectInternal()\n .catch(() => { })\n .finally(checkConnection);\n return this.connectingPromise;\n }\n else {\n // Clear the connecting promise, done.\n this.connectingPromise = null;\n return;\n }\n };\n this.connectingPromise ??= this.connectInternal()\n .catch(() => { })\n .finally(checkConnection);\n return this.connectingPromise;\n }\n async connectInternal() {\n let appliedOptions = null;\n // This method ensures a disconnect before any connection attempt\n await this.disconnectInternal();\n /**\n * This portion creates a sync implementation which can be racy when disconnecting or\n * if multiple tabs on web are in use.\n * This is protected in an exclusive lock.\n * The promise tracks the creation which is used to synchronize disconnect attempts.\n */\n this.syncStreamInitPromise = new Promise(async (resolve, reject) => {\n try {\n if (!this.pendingConnectionOptions) {\n this.logger.debug('No pending connection options found, not creating sync stream implementation');\n // A disconnect could have cleared this.\n resolve();\n return;\n }\n if (this.disconnectingPromise) {\n resolve();\n return;\n }\n const { connector, options } = this.pendingConnectionOptions;\n appliedOptions = options;\n this.pendingConnectionOptions = null;\n const { sync, onDispose } = await this.options.createSyncImplementation(connector, {\n subscriptions: this.activeStreams,\n ...options\n });\n this.iterateListeners((l) => l.syncStreamCreated?.(sync));\n this.syncStreamImplementation = sync;\n this.syncDisposer = onDispose;\n await this.syncStreamImplementation.waitForReady();\n resolve();\n }\n catch (error) {\n reject(error);\n }\n });\n await this.syncStreamInitPromise;\n this.syncStreamInitPromise = null;\n if (!appliedOptions) {\n // A disconnect could have cleared the options which did not create a syncStreamImplementation\n return;\n }\n // It might be possible that a disconnect triggered between the last check\n // and this point. Awaiting here allows the sync stream to be cleared if disconnected.\n await this.disconnectingPromise;\n this.logger.debug('Attempting to connect to PowerSync instance');\n await this.syncStreamImplementation?.connect(appliedOptions);\n }\n /**\n * Close the sync connection.\n *\n * Use {@link connect} to connect again.\n */\n async disconnect() {\n // This will help abort pending connects\n this.pendingConnectionOptions = null;\n await this.disconnectInternal();\n }\n async disconnectInternal() {\n if (this.disconnectingPromise) {\n // A disconnect is already in progress\n return this.disconnectingPromise;\n }\n this.disconnectingPromise = this.performDisconnect();\n await this.disconnectingPromise;\n this.disconnectingPromise = null;\n }\n async performDisconnect() {\n // Wait if a sync stream implementation is being created before closing it\n // (syncStreamImplementation must be assigned before we can properly dispose it)\n await this.syncStreamInitPromise;\n // Keep reference to the sync stream implementation and disposer\n // The class members will be cleared before we trigger the disconnect\n // to prevent any further calls to the sync stream implementation.\n const sync = this.syncStreamImplementation;\n this.syncStreamImplementation = null;\n const disposer = this.syncDisposer;\n this.syncDisposer = null;\n await sync?.disconnect();\n await sync?.dispose();\n await disposer?.();\n }\n stream(adapter, name, parameters) {\n const desc = { name, parameters };\n const waitForFirstSync = (abort) => {\n return adapter.firstStatusMatching((s) => s.forStream(desc)?.subscription.hasSynced, abort);\n };\n return {\n ...desc,\n subscribe: async (options) => {\n // NOTE: We also run this command if a subscription already exists, because this increases the expiry date\n // (relevant if the app is closed before connecting again, where the last subscribe call determines the ttl).\n await adapter.rustSubscriptionsCommand({\n subscribe: {\n stream: {\n name,\n params: parameters\n },\n ttl: options?.ttl,\n priority: options?.priority\n }\n });\n if (!this.syncStreamImplementation) {\n // We're not connected. So, update the offline sync status to reflect the new subscription.\n // (With an active iteration, the sync client would include it in its state).\n await adapter.resolveOfflineSyncStatus();\n }\n const key = `${name}|${JSON.stringify(parameters)}`;\n let subscription = this.locallyActiveSubscriptions.get(key);\n if (subscription == null) {\n const clearSubscription = () => {\n this.locallyActiveSubscriptions.delete(key);\n this.subscriptionsMayHaveChanged();\n };\n subscription = new ActiveSubscription(name, parameters, this.logger, waitForFirstSync, clearSubscription);\n this.locallyActiveSubscriptions.set(key, subscription);\n this.subscriptionsMayHaveChanged();\n }\n return new SyncStreamSubscriptionHandle(subscription);\n },\n unsubscribeAll: async () => {\n await adapter.rustSubscriptionsCommand({ unsubscribe: { name, params: parameters } });\n this.subscriptionsMayHaveChanged();\n }\n };\n }\n /**\n * @internal exposed for testing\n */\n get activeStreams() {\n return [...this.locallyActiveSubscriptions.values()].map((a) => ({ name: a.name, params: a.parameters }));\n }\n subscriptionsMayHaveChanged() {\n this.syncStreamImplementation?.updateSubscriptions(this.activeStreams);\n }\n}\nclass ActiveSubscription {\n name;\n parameters;\n logger;\n waitForFirstSync;\n clearSubscription;\n refcount = 0;\n constructor(name, parameters, logger, waitForFirstSync, clearSubscription) {\n this.name = name;\n this.parameters = parameters;\n this.logger = logger;\n this.waitForFirstSync = waitForFirstSync;\n this.clearSubscription = clearSubscription;\n }\n decrementRefCount() {\n this.refcount--;\n if (this.refcount == 0) {\n this.clearSubscription();\n }\n }\n}\nclass SyncStreamSubscriptionHandle {\n subscription;\n active = true;\n constructor(subscription) {\n this.subscription = subscription;\n subscription.refcount++;\n _finalizer?.register(this, subscription);\n }\n get name() {\n return this.subscription.name;\n }\n get parameters() {\n return this.subscription.parameters;\n }\n waitForFirstSync(abort) {\n return this.subscription.waitForFirstSync(abort);\n }\n unsubscribe() {\n if (this.active) {\n this.active = false;\n _finalizer?.unregister(this);\n this.subscription.decrementRefCount();\n }\n }\n}\nconst _finalizer = 'FinalizationRegistry' in globalThis\n ? new FinalizationRegistry((sub) => {\n sub.logger.warn(`A subscription to ${sub.name} with params ${JSON.stringify(sub.parameters)} leaked! Please ensure calling unsubscribe() when you don't need a subscription anymore. For global subscriptions, consider storing them in global fields to avoid this warning.`);\n })\n : null;\n\n/**\n * An efficient comparator for {@link WatchedQuery} created with {@link Query#watch}. This has the ability to determine if a query\n * result has changes without necessarily processing all items in the result.\n */\nclass ArrayComparator {\n options;\n constructor(options) {\n this.options = options;\n }\n checkEquality(current, previous) {\n if (current.length === 0 && previous.length === 0) {\n return true;\n }\n if (current.length !== previous.length) {\n return false;\n }\n const { compareBy } = this.options;\n // At this point the lengths are equal\n for (let i = 0; i < current.length; i++) {\n const currentItem = compareBy(current[i]);\n const previousItem = compareBy(previous[i]);\n if (currentItem !== previousItem) {\n return false;\n }\n }\n return true;\n }\n}\n/**\n * Watched query comparator that always reports changed result sets.\n */\nconst FalsyComparator = {\n checkEquality: () => false // Default comparator that always returns false\n};\n\n/**\n * A BaseObserver that tracks the counts of listeners for each event type.\n */\nclass MetaBaseObserver extends BaseObserver {\n get listenerCounts() {\n const counts = {};\n let total = 0;\n for (const listener of this.listeners) {\n for (const key in listener) {\n if (listener[key]) {\n counts[key] = (counts[key] ?? 0) + 1;\n total++;\n }\n }\n }\n return {\n ...counts,\n total\n };\n }\n get listenerMeta() {\n return {\n counts: this.listenerCounts,\n // Allows registering a meta listener that will be notified of changes in listener counts\n registerListener: (listener) => {\n return this.metaListener.registerListener(listener);\n }\n };\n }\n metaListener;\n constructor() {\n super();\n this.metaListener = new BaseObserver();\n }\n registerListener(listener) {\n const dispose = super.registerListener(listener);\n const updatedCount = this.listenerCounts;\n this.metaListener.iterateListeners((l) => {\n l.listenersChanged?.(updatedCount);\n });\n return () => {\n dispose();\n const updatedCount = this.listenerCounts;\n this.metaListener.iterateListeners((l) => {\n l.listenersChanged?.(updatedCount);\n });\n };\n }\n}\n\n/**\n * Performs underlying watching and yields a stream of results.\n * @internal\n */\nclass AbstractQueryProcessor extends MetaBaseObserver {\n options;\n state;\n abortController;\n initialized;\n _closed;\n disposeListeners;\n get closed() {\n return this._closed;\n }\n constructor(options) {\n super();\n this.options = options;\n this.abortController = new AbortController();\n this._closed = false;\n this.state = this.constructInitialState();\n this.disposeListeners = null;\n this.initialized = this.init(this.abortController.signal);\n }\n constructInitialState() {\n return {\n isLoading: true,\n isFetching: this.reportFetching, // Only set to true if we will report updates in future\n error: null,\n lastUpdated: null,\n data: this.options.placeholderData\n };\n }\n get reportFetching() {\n return this.options.watchOptions.reportFetching ?? true;\n }\n async updateSettingsInternal(settings, signal) {\n // This may have been aborted while awaiting or if multiple calls to `updateSettings` were made\n if (this._closed || signal.aborted) {\n return;\n }\n this.options.watchOptions = settings;\n this.iterateListeners((l) => l[WatchedQueryListenerEvent.SETTINGS_WILL_UPDATE]?.());\n if (!this.state.isFetching && this.reportFetching) {\n await this.updateState({\n isFetching: true\n });\n }\n await this.runWithReporting(() => this.linkQuery({\n abortSignal: signal,\n settings\n }));\n }\n /**\n * Updates the underlying query.\n */\n async updateSettings(settings) {\n // Abort the previous request\n this.abortController.abort();\n // Keep track of this controller's abort status\n const abortController = new AbortController();\n // Allow this to be aborted externally\n this.abortController = abortController;\n await this.initialized;\n return this.updateSettingsInternal(settings, abortController.signal);\n }\n async updateState(update) {\n if (this._closed) {\n return;\n }\n if (typeof update.error !== 'undefined') {\n await this.iterateAsyncListenersWithError(async (l) => l.onError?.(update.error));\n // An error always stops for the current fetching state\n update.isFetching = false;\n update.isLoading = false;\n }\n Object.assign(this.state, { lastUpdated: new Date() }, update);\n if (typeof update.data !== 'undefined') {\n await this.iterateAsyncListenersWithError(async (l) => l.onData?.(this.state.data));\n }\n await this.iterateAsyncListenersWithError(async (l) => l.onStateChange?.(this.state));\n }\n /**\n * Configures base DB listeners and links the query to listeners.\n */\n async init(signal) {\n const { db } = this.options;\n const disposeCloseListener = db.registerListener({\n closing: async () => {\n await this.close();\n }\n });\n // Wait for the schema to be set before listening to changes\n await db.waitForReady();\n const disposeSchemaListener = db.registerListener({\n schemaChanged: async () => {\n await this.runWithReporting(async () => {\n await this.updateSettings(this.options.watchOptions);\n });\n }\n });\n this.disposeListeners = () => {\n disposeCloseListener();\n disposeSchemaListener();\n };\n // Initial setup\n await this.runWithReporting(async () => {\n await this.updateSettingsInternal(this.options.watchOptions, signal);\n });\n }\n async close() {\n this._closed = true;\n this.abortController.abort();\n this.disposeListeners?.();\n this.disposeListeners = null;\n this.iterateListeners((l) => l.closed?.());\n this.listeners.clear();\n }\n /**\n * Runs a callback and reports errors to the error listeners.\n */\n async runWithReporting(callback) {\n try {\n await callback();\n }\n catch (error) {\n // This will update the error on the state and iterate error listeners\n await this.updateState({ error });\n }\n }\n /**\n * Iterate listeners and reports errors to onError handlers.\n */\n async iterateAsyncListenersWithError(callback) {\n try {\n await this.iterateAsyncListeners(async (l) => callback(l));\n }\n catch (error) {\n try {\n await this.iterateAsyncListeners(async (l) => l.onError?.(error));\n }\n catch (error) {\n // Errors here are ignored\n // since we are already in an error state\n this.options.db.logger.error('Watched query error handler threw an Error', error);\n }\n }\n }\n}\n\n/**\n * An empty differential result set.\n * This is used as the initial state for differential incrementally watched queries.\n */\nconst EMPTY_DIFFERENTIAL = {\n added: [],\n all: [],\n removed: [],\n updated: [],\n unchanged: []\n};\n/**\n * Default implementation of the {@link DifferentialWatchedQueryComparator} for watched queries.\n * It keys items by their `id` property if available, alternatively it uses JSON stringification\n * of the entire item for the key and comparison.\n */\nconst DEFAULT_ROW_COMPARATOR = {\n keyBy: (item) => {\n if (item && typeof item == 'object' && typeof item['id'] == 'string') {\n return item['id'];\n }\n return JSON.stringify(item);\n },\n compareBy: (item) => JSON.stringify(item)\n};\n/**\n * Uses the PowerSync onChange event to trigger watched queries.\n * Results are emitted on every change of the relevant tables.\n * @internal\n */\nclass DifferentialQueryProcessor extends AbstractQueryProcessor {\n options;\n comparator;\n constructor(options) {\n super(options);\n this.options = options;\n this.comparator = options.rowComparator ?? DEFAULT_ROW_COMPARATOR;\n }\n /*\n * @returns If the sets are equal\n */\n differentiate(current, previousMap) {\n const { keyBy, compareBy } = this.comparator;\n let hasChanged = false;\n const currentMap = new Map();\n const removedTracker = new Set(previousMap.keys());\n // Allow mutating to populate the data temporarily.\n const diff = {\n all: [],\n added: [],\n removed: [],\n updated: [],\n unchanged: []\n };\n /**\n * Looping over the current result set array is important to preserve\n * the ordering of the result set.\n * We can replace items in the current array with previous object references if they are equal.\n */\n for (const item of current) {\n const key = keyBy(item);\n const hash = compareBy(item);\n currentMap.set(key, { hash, item });\n const previousItem = previousMap.get(key);\n if (!previousItem) {\n // New item\n hasChanged = true;\n diff.added.push(item);\n diff.all.push(item);\n }\n else {\n // Existing item\n if (hash == previousItem.hash) {\n diff.unchanged.push(previousItem.item);\n // Use the previous object reference\n diff.all.push(previousItem.item);\n // update the map to preserve the reference\n currentMap.set(key, previousItem);\n }\n else {\n hasChanged = true;\n diff.updated.push({ current: item, previous: previousItem.item });\n // Use the new reference\n diff.all.push(item);\n }\n }\n // The item is present, we don't consider it removed\n removedTracker.delete(key);\n }\n diff.removed = Array.from(removedTracker).map((key) => previousMap.get(key).item);\n hasChanged = hasChanged || diff.removed.length > 0;\n return {\n diff,\n hasChanged,\n map: currentMap\n };\n }\n async linkQuery(options) {\n const { db, watchOptions } = this.options;\n const { abortSignal } = options;\n const compiledQuery = watchOptions.query.compile();\n const tables = await db.resolveTables(compiledQuery.sql, compiledQuery.parameters, {\n tables: options.settings.triggerOnTables\n });\n let currentMap = new Map();\n // populate the currentMap from the placeholder data\n this.state.data.forEach((item) => {\n currentMap.set(this.comparator.keyBy(item), {\n hash: this.comparator.compareBy(item),\n item\n });\n });\n db.onChangeWithCallback({\n onChange: async () => {\n if (this.closed || abortSignal.aborted) {\n return;\n }\n // This fires for each change of the relevant tables\n try {\n if (this.reportFetching && !this.state.isFetching) {\n await this.updateState({ isFetching: true });\n }\n const partialStateUpdate = {};\n // Always run the query if an underlying table has changed\n const result = await watchOptions.query.execute({\n sql: compiledQuery.sql,\n // Allows casting from ReadOnlyArray[unknown] to Array<unknown>\n // This allows simpler compatibility with PowerSync queries\n parameters: [...compiledQuery.parameters],\n db: this.options.db\n });\n if (abortSignal.aborted) {\n return;\n }\n if (this.reportFetching) {\n partialStateUpdate.isFetching = false;\n }\n if (this.state.isLoading) {\n partialStateUpdate.isLoading = false;\n }\n const { diff, hasChanged, map } = this.differentiate(result, currentMap);\n // Update for future comparisons\n currentMap = map;\n if (hasChanged) {\n await this.iterateAsyncListenersWithError((l) => l.onDiff?.(diff));\n Object.assign(partialStateUpdate, {\n data: diff.all\n });\n }\n if (this.state.error) {\n partialStateUpdate.error = null;\n }\n if (Object.keys(partialStateUpdate).length > 0) {\n await this.updateState(partialStateUpdate);\n }\n }\n catch (error) {\n await this.updateState({ error });\n }\n },\n onError: async (error) => {\n await this.updateState({ error });\n }\n }, {\n signal: abortSignal,\n tables,\n throttleMs: watchOptions.throttleMs,\n triggerImmediate: true // used to emit the initial state\n });\n }\n}\n\n/**\n * Uses the PowerSync onChange event to trigger watched queries.\n * Results are emitted on every change of the relevant tables.\n * @internal\n */\nclass OnChangeQueryProcessor extends AbstractQueryProcessor {\n options;\n constructor(options) {\n super(options);\n this.options = options;\n }\n /**\n * @returns If the sets are equal\n */\n checkEquality(current, previous) {\n // Use the provided comparator if available. Assume values are unique if not available.\n return this.options.comparator?.checkEquality?.(current, previous) ?? false;\n }\n async linkQuery(options) {\n const { db, watchOptions } = this.options;\n const { abortSignal } = options;\n const compiledQuery = watchOptions.query.compile();\n const tables = await db.resolveTables(compiledQuery.sql, compiledQuery.parameters, {\n tables: options.settings.triggerOnTables\n });\n db.onChangeWithCallback({\n onChange: async () => {\n if (this.closed || abortSignal.aborted) {\n return;\n }\n // This fires for each change of the relevant tables\n try {\n if (this.reportFetching && !this.state.isFetching) {\n await this.updateState({ isFetching: true });\n }\n const partialStateUpdate = {};\n // Always run the query if an underlying table has changed\n const result = await watchOptions.query.execute({\n sql: compiledQuery.sql,\n // Allows casting from ReadOnlyArray[unknown] to Array<unknown>\n // This allows simpler compatibility with PowerSync queries\n parameters: [...compiledQuery.parameters],\n db: this.options.db\n });\n if (abortSignal.aborted) {\n return;\n }\n if (this.reportFetching) {\n partialStateUpdate.isFetching = false;\n }\n if (this.state.isLoading) {\n partialStateUpdate.isLoading = false;\n }\n // Check if the result has changed\n if (!this.checkEquality(result, this.state.data)) {\n Object.assign(partialStateUpdate, {\n data: result\n });\n }\n if (this.state.error) {\n partialStateUpdate.error = null;\n }\n if (Object.keys(partialStateUpdate).length > 0) {\n await this.updateState(partialStateUpdate);\n }\n }\n catch (error) {\n await this.updateState({ error });\n }\n },\n onError: async (error) => {\n await this.updateState({ error });\n }\n }, {\n signal: abortSignal,\n tables,\n throttleMs: watchOptions.throttleMs,\n triggerImmediate: true // used to emit the initial state\n });\n }\n}\n\n/**\n * @internal\n */\nclass CustomQuery {\n options;\n constructor(options) {\n this.options = options;\n }\n resolveOptions(options) {\n return {\n reportFetching: options?.reportFetching ?? DEFAULT_WATCH_QUERY_OPTIONS.reportFetching,\n throttleMs: options?.throttleMs ?? DEFAULT_WATCH_QUERY_OPTIONS.throttleMs,\n triggerOnTables: options?.triggerOnTables\n };\n }\n watch(watchOptions) {\n return new OnChangeQueryProcessor({\n db: this.options.db,\n comparator: watchOptions?.comparator ?? FalsyComparator,\n placeholderData: watchOptions?.placeholderData ?? [],\n watchOptions: {\n ...this.resolveOptions(watchOptions),\n query: this.options.query\n }\n });\n }\n differentialWatch(differentialWatchOptions) {\n return new DifferentialQueryProcessor({\n db: this.options.db,\n rowComparator: differentialWatchOptions?.rowComparator,\n placeholderData: differentialWatchOptions?.placeholderData ?? [],\n watchOptions: {\n ...this.resolveOptions(differentialWatchOptions),\n query: this.options.query\n }\n });\n }\n}\n\n/**\n * Tests if the input is a {@link SQLOpenOptions}\n */\nconst isSQLOpenOptions = (test) => {\n // typeof null is `object`, but you cannot use the `in` operator on `null.\n return test && typeof test == 'object' && 'dbFilename' in test;\n};\n/**\n * Tests if input is a {@link SQLOpenFactory}\n */\nconst isSQLOpenFactory = (test) => {\n return typeof test?.openDB == 'function';\n};\n/**\n * Tests if input is a {@link DBAdapter}\n */\nconst isDBAdapter = (test) => {\n return typeof test?.writeTransaction == 'function';\n};\n\nvar PSInternalTable;\n(function (PSInternalTable) {\n PSInternalTable[\"DATA\"] = \"ps_data\";\n PSInternalTable[\"CRUD\"] = \"ps_crud\";\n PSInternalTable[\"BUCKETS\"] = \"ps_buckets\";\n PSInternalTable[\"OPLOG\"] = \"ps_oplog\";\n PSInternalTable[\"UNTYPED\"] = \"ps_untyped\";\n})(PSInternalTable || (PSInternalTable = {}));\nvar PowerSyncControlCommand;\n(function (PowerSyncControlCommand) {\n PowerSyncControlCommand[\"PROCESS_TEXT_LINE\"] = \"line_text\";\n PowerSyncControlCommand[\"PROCESS_BSON_LINE\"] = \"line_binary\";\n PowerSyncControlCommand[\"STOP\"] = \"stop\";\n PowerSyncControlCommand[\"START\"] = \"start\";\n PowerSyncControlCommand[\"NOTIFY_TOKEN_REFRESHED\"] = \"refreshed_token\";\n PowerSyncControlCommand[\"NOTIFY_CRUD_UPLOAD_COMPLETED\"] = \"completed_upload\";\n PowerSyncControlCommand[\"UPDATE_SUBSCRIPTIONS\"] = \"update_subscriptions\";\n})(PowerSyncControlCommand || (PowerSyncControlCommand = {}));\n\n/**\n * A batch of client-side changes.\n */\nclass CrudBatch {\n crud;\n haveMore;\n complete;\n constructor(\n /**\n * List of client-side changes.\n */\n crud, \n /**\n * true if there are more changes in the local queue.\n */\n haveMore, \n /**\n * Call to remove the changes from the local queue, once successfully uploaded.\n */\n complete) {\n this.crud = crud;\n this.haveMore = haveMore;\n this.complete = complete;\n }\n}\n\n/**\n * Type of local change.\n */\nvar UpdateType;\n(function (UpdateType) {\n /** Insert or replace existing row. All non-null columns are included in the data. Generated by INSERT statements. */\n UpdateType[\"PUT\"] = \"PUT\";\n /** Update existing row. Contains the id, and value of each changed column. Generated by UPDATE statements. */\n UpdateType[\"PATCH\"] = \"PATCH\";\n /** Delete existing row. Contains the id. Generated by DELETE statements. */\n UpdateType[\"DELETE\"] = \"DELETE\";\n})(UpdateType || (UpdateType = {}));\n/**\n * A single client-side change.\n */\nclass CrudEntry {\n /**\n * Auto-incrementing client-side id.\n */\n clientId;\n /**\n * ID of the changed row.\n */\n id;\n /**\n * Type of change.\n */\n op;\n /**\n * Data associated with the change.\n */\n opData;\n /**\n * For tables where the `trackPreviousValues` option has been enabled, this tracks previous values for\n * `UPDATE` and `DELETE` statements.\n */\n previousValues;\n /**\n * Table that contained the change.\n */\n table;\n /**\n * Auto-incrementing transaction id. This is the same for all operations within the same transaction.\n */\n transactionId;\n /**\n * Client-side metadata attached with this write.\n *\n * This field is only available when the `trackMetadata` option was set to `true` when creating a table\n * and the insert or update statement set the `_metadata` column.\n */\n metadata;\n static fromRow(dbRow) {\n const data = JSON.parse(dbRow.data);\n return new CrudEntry(parseInt(dbRow.id), data.op, data.type, data.id, dbRow.tx_id, data.data, data.old, data.metadata);\n }\n constructor(clientId, op, table, id, transactionId, opData, previousValues, metadata) {\n this.clientId = clientId;\n this.id = id;\n this.op = op;\n this.opData = opData;\n this.table = table;\n this.transactionId = transactionId;\n this.previousValues = previousValues;\n this.metadata = metadata;\n }\n /**\n * Converts the change to JSON format.\n */\n toJSON() {\n return {\n op_id: this.clientId,\n op: this.op,\n type: this.table,\n id: this.id,\n tx_id: this.transactionId,\n data: this.opData,\n old: this.previousValues,\n metadata: this.metadata\n };\n }\n equals(entry) {\n return JSON.stringify(this.toComparisonArray()) == JSON.stringify(entry.toComparisonArray());\n }\n /**\n * The hash code for this object.\n * @deprecated This should not be necessary in the JS SDK.\n * Use the @see CrudEntry#equals method instead.\n * TODO remove in the next major release.\n */\n hashCode() {\n return JSON.stringify(this.toComparisonArray());\n }\n /**\n * Generates an array for use in deep comparison operations\n */\n toComparisonArray() {\n return [\n this.transactionId,\n this.clientId,\n this.op,\n this.table,\n this.id,\n this.opData,\n this.previousValues,\n this.metadata\n ];\n }\n}\n\nclass CrudTransaction extends CrudBatch {\n crud;\n complete;\n transactionId;\n constructor(\n /**\n * List of client-side changes.\n */\n crud, \n /**\n * Call to remove the changes from the local queue, once successfully uploaded.\n */\n complete, \n /**\n * If null, this contains a list of changes recorded without an explicit transaction associated.\n */\n transactionId) {\n super(crud, false, complete);\n this.crud = crud;\n this.complete = complete;\n this.transactionId = transactionId;\n }\n}\n\n/**\n * Calls to Abortcontroller.abort(reason: any) will result in the\n * `reason` being thrown. This is not necessarily an error,\n * but extends error for better logging purposes.\n */\nclass AbortOperation extends Error {\n reason;\n constructor(reason) {\n super(reason);\n this.reason = reason;\n // Set the prototype explicitly\n Object.setPrototypeOf(this, AbortOperation.prototype);\n // Capture stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, AbortOperation);\n }\n }\n}\n\nvar OpTypeEnum;\n(function (OpTypeEnum) {\n OpTypeEnum[OpTypeEnum[\"CLEAR\"] = 1] = \"CLEAR\";\n OpTypeEnum[OpTypeEnum[\"MOVE\"] = 2] = \"MOVE\";\n OpTypeEnum[OpTypeEnum[\"PUT\"] = 3] = \"PUT\";\n OpTypeEnum[OpTypeEnum[\"REMOVE\"] = 4] = \"REMOVE\";\n})(OpTypeEnum || (OpTypeEnum = {}));\n/**\n * Used internally for sync buckets.\n */\nclass OpType {\n value;\n static fromJSON(jsonValue) {\n return new OpType(OpTypeEnum[jsonValue]);\n }\n constructor(value) {\n this.value = value;\n }\n toJSON() {\n return Object.entries(OpTypeEnum).find(([, value]) => value === this.value)[0];\n }\n}\n\nclass OplogEntry {\n op_id;\n op;\n checksum;\n subkey;\n object_type;\n object_id;\n data;\n static fromRow(row) {\n return new OplogEntry(row.op_id, OpType.fromJSON(row.op), row.checksum, row.subkey, row.object_type, row.object_id, row.data);\n }\n constructor(op_id, op, checksum, subkey, object_type, object_id, data) {\n this.op_id = op_id;\n this.op = op;\n this.checksum = checksum;\n this.subkey = subkey;\n this.object_type = object_type;\n this.object_id = object_id;\n this.data = data;\n }\n toJSON(fixedKeyEncoding = false) {\n return {\n op_id: this.op_id,\n op: this.op.toJSON(),\n object_type: this.object_type,\n object_id: this.object_id,\n checksum: this.checksum,\n data: this.data,\n // Older versions of the JS SDK used to always JSON.stringify here. That has always been wrong,\n // but we need to migrate gradually to not break existing databases.\n subkey: fixedKeyEncoding ? this.subkey : JSON.stringify(this.subkey)\n };\n }\n}\n\nclass SyncDataBucket {\n bucket;\n data;\n has_more;\n after;\n next_after;\n static fromRow(row) {\n return new SyncDataBucket(row.bucket, row.data.map((entry) => OplogEntry.fromRow(entry)), row.has_more ?? false, row.after, row.next_after);\n }\n constructor(bucket, data, \n /**\n * True if the response does not contain all the data for this bucket, and another request must be made.\n */\n has_more, \n /**\n * The `after` specified in the request.\n */\n after, \n /**\n * Use this for the next request.\n */\n next_after) {\n this.bucket = bucket;\n this.data = data;\n this.has_more = has_more;\n this.after = after;\n this.next_after = next_after;\n }\n toJSON(fixedKeyEncoding = false) {\n return {\n bucket: this.bucket,\n has_more: this.has_more,\n after: this.after,\n next_after: this.next_after,\n data: this.data.map((entry) => entry.toJSON(fixedKeyEncoding))\n };\n }\n}\n\nvar buffer = {};\n\nvar base64Js = {};\n\nvar hasRequiredBase64Js;\n\nfunction requireBase64Js () {\n\tif (hasRequiredBase64Js) return base64Js;\n\thasRequiredBase64Js = 1;\n\n\tbase64Js.byteLength = byteLength;\n\tbase64Js.toByteArray = toByteArray;\n\tbase64Js.fromByteArray = fromByteArray;\n\n\tvar lookup = [];\n\tvar revLookup = [];\n\tvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;\n\n\tvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\tfor (var i = 0, len = code.length; i < len; ++i) {\n\t lookup[i] = code[i];\n\t revLookup[code.charCodeAt(i)] = i;\n\t}\n\n\t// Support decoding URL-safe base64 strings, as Node.js does.\n\t// See: https://en.wikipedia.org/wiki/Base64#URL_applications\n\trevLookup['-'.charCodeAt(0)] = 62;\n\trevLookup['_'.charCodeAt(0)] = 63;\n\n\tfunction getLens (b64) {\n\t var len = b64.length;\n\n\t if (len % 4 > 0) {\n\t throw new Error('Invalid string. Length must be a multiple of 4')\n\t }\n\n\t // Trim off extra bytes after placeholder bytes are found\n\t // See: https://github.com/beatgammit/base64-js/issues/42\n\t var validLen = b64.indexOf('=');\n\t if (validLen === -1) validLen = len;\n\n\t var placeHoldersLen = validLen === len\n\t ? 0\n\t : 4 - (validLen % 4);\n\n\t return [validLen, placeHoldersLen]\n\t}\n\n\t// base64 is 4/3 + up to two characters of the original data\n\tfunction byteLength (b64) {\n\t var lens = getLens(b64);\n\t var validLen = lens[0];\n\t var placeHoldersLen = lens[1];\n\t return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n\t}\n\n\tfunction _byteLength (b64, validLen, placeHoldersLen) {\n\t return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n\t}\n\n\tfunction toByteArray (b64) {\n\t var tmp;\n\t var lens = getLens(b64);\n\t var validLen = lens[0];\n\t var placeHoldersLen = lens[1];\n\n\t var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));\n\n\t var curByte = 0;\n\n\t // if there are placeholders, only get up to the last complete 4 chars\n\t var len = placeHoldersLen > 0\n\t ? validLen - 4\n\t : validLen;\n\n\t var i;\n\t for (i = 0; i < len; i += 4) {\n\t tmp =\n\t (revLookup[b64.charCodeAt(i)] << 18) |\n\t (revLookup[b64.charCodeAt(i + 1)] << 12) |\n\t (revLookup[b64.charCodeAt(i + 2)] << 6) |\n\t revLookup[b64.charCodeAt(i + 3)];\n\t arr[curByte++] = (tmp >> 16) & 0xFF;\n\t arr[curByte++] = (tmp >> 8) & 0xFF;\n\t arr[curByte++] = tmp & 0xFF;\n\t }\n\n\t if (placeHoldersLen === 2) {\n\t tmp =\n\t (revLookup[b64.charCodeAt(i)] << 2) |\n\t (revLookup[b64.charCodeAt(i + 1)] >> 4);\n\t arr[curByte++] = tmp & 0xFF;\n\t }\n\n\t if (placeHoldersLen === 1) {\n\t tmp =\n\t (revLookup[b64.charCodeAt(i)] << 10) |\n\t (revLookup[b64.charCodeAt(i + 1)] << 4) |\n\t (revLookup[b64.charCodeAt(i + 2)] >> 2);\n\t arr[curByte++] = (tmp >> 8) & 0xFF;\n\t arr[curByte++] = tmp & 0xFF;\n\t }\n\n\t return arr\n\t}\n\n\tfunction tripletToBase64 (num) {\n\t return lookup[num >> 18 & 0x3F] +\n\t lookup[num >> 12 & 0x3F] +\n\t lookup[num >> 6 & 0x3F] +\n\t lookup[num & 0x3F]\n\t}\n\n\tfunction encodeChunk (uint8, start, end) {\n\t var tmp;\n\t var output = [];\n\t for (var i = start; i < end; i += 3) {\n\t tmp =\n\t ((uint8[i] << 16) & 0xFF0000) +\n\t ((uint8[i + 1] << 8) & 0xFF00) +\n\t (uint8[i + 2] & 0xFF);\n\t output.push(tripletToBase64(tmp));\n\t }\n\t return output.join('')\n\t}\n\n\tfunction fromByteArray (uint8) {\n\t var tmp;\n\t var len = uint8.length;\n\t var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes\n\t var parts = [];\n\t var maxChunkLength = 16383; // must be multiple of 3\n\n\t // go through the array every three bytes, we'll deal with trailing stuff later\n\t for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n\t parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));\n\t }\n\n\t // pad the end with zeros, but make sure to not forget the extra bytes\n\t if (extraBytes === 1) {\n\t tmp = uint8[len - 1];\n\t parts.push(\n\t lookup[tmp >> 2] +\n\t lookup[(tmp << 4) & 0x3F] +\n\t '=='\n\t );\n\t } else if (extraBytes === 2) {\n\t tmp = (uint8[len - 2] << 8) + uint8[len - 1];\n\t parts.push(\n\t lookup[tmp >> 10] +\n\t lookup[(tmp >> 4) & 0x3F] +\n\t lookup[(tmp << 2) & 0x3F] +\n\t '='\n\t );\n\t }\n\n\t return parts.join('')\n\t}\n\treturn base64Js;\n}\n\nvar ieee754 = {};\n\n/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */\n\nvar hasRequiredIeee754;\n\nfunction requireIeee754 () {\n\tif (hasRequiredIeee754) return ieee754;\n\thasRequiredIeee754 = 1;\n\tieee754.read = function (buffer, offset, isLE, mLen, nBytes) {\n\t var e, m;\n\t var eLen = (nBytes * 8) - mLen - 1;\n\t var eMax = (1 << eLen) - 1;\n\t var eBias = eMax >> 1;\n\t var nBits = -7;\n\t var i = isLE ? (nBytes - 1) : 0;\n\t var d = isLE ? -1 : 1;\n\t var s = buffer[offset + i];\n\n\t i += d;\n\n\t e = s & ((1 << (-nBits)) - 1);\n\t s >>= (-nBits);\n\t nBits += eLen;\n\t for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n\t m = e & ((1 << (-nBits)) - 1);\n\t e >>= (-nBits);\n\t nBits += mLen;\n\t for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n\t if (e === 0) {\n\t e = 1 - eBias;\n\t } else if (e === eMax) {\n\t return m ? NaN : ((s ? -1 : 1) * Infinity)\n\t } else {\n\t m = m + Math.pow(2, mLen);\n\t e = e - eBias;\n\t }\n\t return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n\t};\n\n\tieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n\t var e, m, c;\n\t var eLen = (nBytes * 8) - mLen - 1;\n\t var eMax = (1 << eLen) - 1;\n\t var eBias = eMax >> 1;\n\t var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);\n\t var i = isLE ? 0 : (nBytes - 1);\n\t var d = isLE ? 1 : -1;\n\t var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;\n\n\t value = Math.abs(value);\n\n\t if (isNaN(value) || value === Infinity) {\n\t m = isNaN(value) ? 1 : 0;\n\t e = eMax;\n\t } else {\n\t e = Math.floor(Math.log(value) / Math.LN2);\n\t if (value * (c = Math.pow(2, -e)) < 1) {\n\t e--;\n\t c *= 2;\n\t }\n\t if (e + eBias >= 1) {\n\t value += rt / c;\n\t } else {\n\t value += rt * Math.pow(2, 1 - eBias);\n\t }\n\t if (value * c >= 2) {\n\t e++;\n\t c /= 2;\n\t }\n\n\t if (e + eBias >= eMax) {\n\t m = 0;\n\t e = eMax;\n\t } else if (e + eBias >= 1) {\n\t m = ((value * c) - 1) * Math.pow(2, mLen);\n\t e = e + eBias;\n\t } else {\n\t m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);\n\t e = 0;\n\t }\n\t }\n\n\t for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n\t e = (e << mLen) | m;\n\t eLen += mLen;\n\t for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n\t buffer[offset + i - d] |= s * 128;\n\t};\n\treturn ieee754;\n}\n\n/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh <https://feross.org>\n * @license MIT\n */\n\nvar hasRequiredBuffer;\n\nfunction requireBuffer () {\n\tif (hasRequiredBuffer) return buffer;\n\thasRequiredBuffer = 1;\n\t(function (exports$1) {\n\n\t\tconst base64 = requireBase64Js();\n\t\tconst ieee754 = requireIeee754();\n\t\tconst customInspectSymbol =\n\t\t (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n\t\t ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n\t\t : null;\n\n\t\texports$1.Buffer = Buffer;\n\t\texports$1.SlowBuffer = SlowBuffer;\n\t\texports$1.INSPECT_MAX_BYTES = 50;\n\n\t\tconst K_MAX_LENGTH = 0x7fffffff;\n\t\texports$1.kMaxLength = K_MAX_LENGTH;\n\n\t\t/**\n\t\t * If `Buffer.TYPED_ARRAY_SUPPORT`:\n\t\t * === true Use Uint8Array implementation (fastest)\n\t\t * === false Print warning and recommend using `buffer` v4.x which has an Object\n\t\t * implementation (most compatible, even IE6)\n\t\t *\n\t\t * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n\t\t * Opera 11.6+, iOS 4.2+.\n\t\t *\n\t\t * We report that the browser does not support typed arrays if the are not subclassable\n\t\t * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n\t\t * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n\t\t * for __proto__ and has a buggy typed array implementation.\n\t\t */\n\t\tBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport();\n\n\t\tif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n\t\t typeof console.error === 'function') {\n\t\t console.error(\n\t\t 'This browser lacks typed array (Uint8Array) support which is required by ' +\n\t\t '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n\t\t );\n\t\t}\n\n\t\tfunction typedArraySupport () {\n\t\t // Can typed array instances can be augmented?\n\t\t try {\n\t\t const arr = new Uint8Array(1);\n\t\t const proto = { foo: function () { return 42 } };\n\t\t Object.setPrototypeOf(proto, Uint8Array.prototype);\n\t\t Object.setPrototypeOf(arr, proto);\n\t\t return arr.foo() === 42\n\t\t } catch (e) {\n\t\t return false\n\t\t }\n\t\t}\n\n\t\tObject.defineProperty(Buffer.prototype, 'parent', {\n\t\t enumerable: true,\n\t\t get: function () {\n\t\t if (!Buffer.isBuffer(this)) return undefined\n\t\t return this.buffer\n\t\t }\n\t\t});\n\n\t\tObject.defineProperty(Buffer.prototype, 'offset', {\n\t\t enumerable: true,\n\t\t get: function () {\n\t\t if (!Buffer.isBuffer(this)) return undefined\n\t\t return this.byteOffset\n\t\t }\n\t\t});\n\n\t\tfunction createBuffer (length) {\n\t\t if (length > K_MAX_LENGTH) {\n\t\t throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n\t\t }\n\t\t // Return an augmented `Uint8Array` instance\n\t\t const buf = new Uint8Array(length);\n\t\t Object.setPrototypeOf(buf, Buffer.prototype);\n\t\t return buf\n\t\t}\n\n\t\t/**\n\t\t * The Buffer constructor returns instances of `Uint8Array` that have their\n\t\t * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n\t\t * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n\t\t * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n\t\t * returns a single octet.\n\t\t *\n\t\t * The `Uint8Array` prototype remains unmodified.\n\t\t */\n\n\t\tfunction Buffer (arg, encodingOrOffset, length) {\n\t\t // Common case.\n\t\t if (typeof arg === 'number') {\n\t\t if (typeof encodingOrOffset === 'string') {\n\t\t throw new TypeError(\n\t\t 'The \"string\" argument must be of type string. Received type number'\n\t\t )\n\t\t }\n\t\t return allocUnsafe(arg)\n\t\t }\n\t\t return from(arg, encodingOrOffset, length)\n\t\t}\n\n\t\tBuffer.poolSize = 8192; // not used by this implementation\n\n\t\tfunction from (value, encodingOrOffset, length) {\n\t\t if (typeof value === 'string') {\n\t\t return fromString(value, encodingOrOffset)\n\t\t }\n\n\t\t if (ArrayBuffer.isView(value)) {\n\t\t return fromArrayView(value)\n\t\t }\n\n\t\t if (value == null) {\n\t\t throw new TypeError(\n\t\t 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n\t\t 'or Array-like Object. Received type ' + (typeof value)\n\t\t )\n\t\t }\n\n\t\t if (isInstance(value, ArrayBuffer) ||\n\t\t (value && isInstance(value.buffer, ArrayBuffer))) {\n\t\t return fromArrayBuffer(value, encodingOrOffset, length)\n\t\t }\n\n\t\t if (typeof SharedArrayBuffer !== 'undefined' &&\n\t\t (isInstance(value, SharedArrayBuffer) ||\n\t\t (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n\t\t return fromArrayBuffer(value, encodingOrOffset, length)\n\t\t }\n\n\t\t if (typeof value === 'number') {\n\t\t throw new TypeError(\n\t\t 'The \"value\" argument must not be of type number. Received type number'\n\t\t )\n\t\t }\n\n\t\t const valueOf = value.valueOf && value.valueOf();\n\t\t if (valueOf != null && valueOf !== value) {\n\t\t return Buffer.from(valueOf, encodingOrOffset, length)\n\t\t }\n\n\t\t const b = fromObject(value);\n\t\t if (b) return b\n\n\t\t if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n\t\t typeof value[Symbol.toPrimitive] === 'function') {\n\t\t return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n\t\t }\n\n\t\t throw new TypeError(\n\t\t 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n\t\t 'or Array-like Object. Received type ' + (typeof value)\n\t\t )\n\t\t}\n\n\t\t/**\n\t\t * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n\t\t * if value is a number.\n\t\t * Buffer.from(str[, encoding])\n\t\t * Buffer.from(array)\n\t\t * Buffer.from(buffer)\n\t\t * Buffer.from(arrayBuffer[, byteOffset[, length]])\n\t\t **/\n\t\tBuffer.from = function (value, encodingOrOffset, length) {\n\t\t return from(value, encodingOrOffset, length)\n\t\t};\n\n\t\t// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n\t\t// https://github.com/feross/buffer/pull/148\n\t\tObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);\n\t\tObject.setPrototypeOf(Buffer, Uint8Array);\n\n\t\tfunction assertSize (size) {\n\t\t if (typeof size !== 'number') {\n\t\t throw new TypeError('\"size\" argument must be of type number')\n\t\t } else if (size < 0) {\n\t\t throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n\t\t }\n\t\t}\n\n\t\tfunction alloc (size, fill, encoding) {\n\t\t assertSize(size);\n\t\t if (size <= 0) {\n\t\t return createBuffer(size)\n\t\t }\n\t\t if (fill !== undefined) {\n\t\t // Only pay attention to encoding if it's a string. This\n\t\t // prevents accidentally sending in a number that would\n\t\t // be interpreted as a start offset.\n\t\t return typeof encoding === 'string'\n\t\t ? createBuffer(size).fill(fill, encoding)\n\t\t : createBuffer(size).fill(fill)\n\t\t }\n\t\t return createBuffer(size)\n\t\t}\n\n\t\t/**\n\t\t * Creates a new filled Buffer instance.\n\t\t * alloc(size[, fill[, encoding]])\n\t\t **/\n\t\tBuffer.alloc = function (size, fill, encoding) {\n\t\t return alloc(size, fill, encoding)\n\t\t};\n\n\t\tfunction allocUnsafe (size) {\n\t\t assertSize(size);\n\t\t return createBuffer(size < 0 ? 0 : checked(size) | 0)\n\t\t}\n\n\t\t/**\n\t\t * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n\t\t * */\n\t\tBuffer.allocUnsafe = function (size) {\n\t\t return allocUnsafe(size)\n\t\t};\n\t\t/**\n\t\t * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n\t\t */\n\t\tBuffer.allocUnsafeSlow = function (size) {\n\t\t return allocUnsafe(size)\n\t\t};\n\n\t\tfunction fromString (string, encoding) {\n\t\t if (typeof encoding !== 'string' || encoding === '') {\n\t\t encoding = 'utf8';\n\t\t }\n\n\t\t if (!Buffer.isEncoding(encoding)) {\n\t\t throw new TypeError('Unknown encoding: ' + encoding)\n\t\t }\n\n\t\t const length = byteLength(string, encoding) | 0;\n\t\t let buf = createBuffer(length);\n\n\t\t const actual = buf.write(string, encoding);\n\n\t\t if (actual !== length) {\n\t\t // Writing a hex string, for example, that contains invalid characters will\n\t\t // cause everything after the first invalid character to be ignored. (e.g.\n\t\t // 'abxxcd' will be treated as 'ab')\n\t\t buf = buf.slice(0, actual);\n\t\t }\n\n\t\t return buf\n\t\t}\n\n\t\tfunction fromArrayLike (array) {\n\t\t const length = array.length < 0 ? 0 : checked(array.length) | 0;\n\t\t const buf = createBuffer(length);\n\t\t for (let i = 0; i < length; i += 1) {\n\t\t buf[i] = array[i] & 255;\n\t\t }\n\t\t return buf\n\t\t}\n\n\t\tfunction fromArrayView (arrayView) {\n\t\t if (isInstance(arrayView, Uint8Array)) {\n\t\t const copy = new Uint8Array(arrayView);\n\t\t return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n\t\t }\n\t\t return fromArrayLike(arrayView)\n\t\t}\n\n\t\tfunction fromArrayBuffer (array, byteOffset, length) {\n\t\t if (byteOffset < 0 || array.byteLength < byteOffset) {\n\t\t throw new RangeError('\"offset\" is outside of buffer bounds')\n\t\t }\n\n\t\t if (array.byteLength < byteOffset + (length || 0)) {\n\t\t throw new RangeError('\"length\" is outside of buffer bounds')\n\t\t }\n\n\t\t let buf;\n\t\t if (byteOffset === undefined && length === undefined) {\n\t\t buf = new Uint8Array(array);\n\t\t } else if (length === undefined) {\n\t\t buf = new Uint8Array(array, byteOffset);\n\t\t } else {\n\t\t buf = new Uint8Array(array, byteOffset, length);\n\t\t }\n\n\t\t // Return an augmented `Uint8Array` instance\n\t\t Object.setPrototypeOf(buf, Buffer.prototype);\n\n\t\t return buf\n\t\t}\n\n\t\tfunction fromObject (obj) {\n\t\t if (Buffer.isBuffer(obj)) {\n\t\t const len = checked(obj.length) | 0;\n\t\t const buf = createBuffer(len);\n\n\t\t if (buf.length === 0) {\n\t\t return buf\n\t\t }\n\n\t\t obj.copy(buf, 0, 0, len);\n\t\t return buf\n\t\t }\n\n\t\t if (obj.length !== undefined) {\n\t\t if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n\t\t return createBuffer(0)\n\t\t }\n\t\t return fromArrayLike(obj)\n\t\t }\n\n\t\t if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n\t\t return fromArrayLike(obj.data)\n\t\t }\n\t\t}\n\n\t\tfunction checked (length) {\n\t\t // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n\t\t // length is NaN (which is otherwise coerced to zero.)\n\t\t if (length >= K_MAX_LENGTH) {\n\t\t throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n\t\t 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n\t\t }\n\t\t return length | 0\n\t\t}\n\n\t\tfunction SlowBuffer (length) {\n\t\t if (+length != length) { // eslint-disable-line eqeqeq\n\t\t length = 0;\n\t\t }\n\t\t return Buffer.alloc(+length)\n\t\t}\n\n\t\tBuffer.isBuffer = function isBuffer (b) {\n\t\t return b != null && b._isBuffer === true &&\n\t\t b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n\t\t};\n\n\t\tBuffer.compare = function compare (a, b) {\n\t\t if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);\n\t\t if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);\n\t\t if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n\t\t throw new TypeError(\n\t\t 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n\t\t )\n\t\t }\n\n\t\t if (a === b) return 0\n\n\t\t let x = a.length;\n\t\t let y = b.length;\n\n\t\t for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n\t\t if (a[i] !== b[i]) {\n\t\t x = a[i];\n\t\t y = b[i];\n\t\t break\n\t\t }\n\t\t }\n\n\t\t if (x < y) return -1\n\t\t if (y < x) return 1\n\t\t return 0\n\t\t};\n\n\t\tBuffer.isEncoding = function isEncoding (encoding) {\n\t\t switch (String(encoding).toLowerCase()) {\n\t\t case 'hex':\n\t\t case 'utf8':\n\t\t case 'utf-8':\n\t\t case 'ascii':\n\t\t case 'latin1':\n\t\t case 'binary':\n\t\t case 'base64':\n\t\t case 'ucs2':\n\t\t case 'ucs-2':\n\t\t case 'utf16le':\n\t\t case 'utf-16le':\n\t\t return true\n\t\t default:\n\t\t return false\n\t\t }\n\t\t};\n\n\t\tBuffer.concat = function concat (list, length) {\n\t\t if (!Array.isArray(list)) {\n\t\t throw new TypeError('\"list\" argument must be an Array of Buffers')\n\t\t }\n\n\t\t if (list.length === 0) {\n\t\t return Buffer.alloc(0)\n\t\t }\n\n\t\t let i;\n\t\t if (length === undefined) {\n\t\t length = 0;\n\t\t for (i = 0; i < list.length; ++i) {\n\t\t length += list[i].length;\n\t\t }\n\t\t }\n\n\t\t const buffer = Buffer.allocUnsafe(length);\n\t\t let pos = 0;\n\t\t for (i = 0; i < list.length; ++i) {\n\t\t let buf = list[i];\n\t\t if (isInstance(buf, Uint8Array)) {\n\t\t if (pos + buf.length > buffer.length) {\n\t\t if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf);\n\t\t buf.copy(buffer, pos);\n\t\t } else {\n\t\t Uint8Array.prototype.set.call(\n\t\t buffer,\n\t\t buf,\n\t\t pos\n\t\t );\n\t\t }\n\t\t } else if (!Buffer.isBuffer(buf)) {\n\t\t throw new TypeError('\"list\" argument must be an Array of Buffers')\n\t\t } else {\n\t\t buf.copy(buffer, pos);\n\t\t }\n\t\t pos += buf.length;\n\t\t }\n\t\t return buffer\n\t\t};\n\n\t\tfunction byteLength (string, encoding) {\n\t\t if (Buffer.isBuffer(string)) {\n\t\t return string.length\n\t\t }\n\t\t if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n\t\t return string.byteLength\n\t\t }\n\t\t if (typeof string !== 'string') {\n\t\t throw new TypeError(\n\t\t 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n\t\t 'Received type ' + typeof string\n\t\t )\n\t\t }\n\n\t\t const len = string.length;\n\t\t const mustMatch = (arguments.length > 2 && arguments[2] === true);\n\t\t if (!mustMatch && len === 0) return 0\n\n\t\t // Use a for loop to avoid recursion\n\t\t let loweredCase = false;\n\t\t for (;;) {\n\t\t switch (encoding) {\n\t\t case 'ascii':\n\t\t case 'latin1':\n\t\t case 'binary':\n\t\t return len\n\t\t case 'utf8':\n\t\t case 'utf-8':\n\t\t return utf8ToBytes(string).length\n\t\t case 'ucs2':\n\t\t case 'ucs-2':\n\t\t case 'utf16le':\n\t\t case 'utf-16le':\n\t\t return len * 2\n\t\t case 'hex':\n\t\t return len >>> 1\n\t\t case 'base64':\n\t\t return base64ToBytes(string).length\n\t\t default:\n\t\t if (loweredCase) {\n\t\t return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n\t\t }\n\t\t encoding = ('' + encoding).toLowerCase();\n\t\t loweredCase = true;\n\t\t }\n\t\t }\n\t\t}\n\t\tBuffer.byteLength = byteLength;\n\n\t\tfunction slowToString (encoding, start, end) {\n\t\t let loweredCase = false;\n\n\t\t // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n\t\t // property of a typed array.\n\n\t\t // This behaves neither like String nor Uint8Array in that we set start/end\n\t\t // to their upper/lower bounds if the value passed is out of range.\n\t\t // undefined is handled specially as per ECMA-262 6th Edition,\n\t\t // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n\t\t if (start === undefined || start < 0) {\n\t\t start = 0;\n\t\t }\n\t\t // Return early if start > this.length. Done here to prevent potential uint32\n\t\t // coercion fail below.\n\t\t if (start > this.length) {\n\t\t return ''\n\t\t }\n\n\t\t if (end === undefined || end > this.length) {\n\t\t end = this.length;\n\t\t }\n\n\t\t if (end <= 0) {\n\t\t return ''\n\t\t }\n\n\t\t // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n\t\t end >>>= 0;\n\t\t start >>>= 0;\n\n\t\t if (end <= start) {\n\t\t return ''\n\t\t }\n\n\t\t if (!encoding) encoding = 'utf8';\n\n\t\t while (true) {\n\t\t switch (encoding) {\n\t\t case 'hex':\n\t\t return hexSlice(this, start, end)\n\n\t\t case 'utf8':\n\t\t case 'utf-8':\n\t\t return utf8Slice(this, start, end)\n\n\t\t case 'ascii':\n\t\t return asciiSlice(this, start, end)\n\n\t\t case 'latin1':\n\t\t case 'binary':\n\t\t return latin1Slice(this, start, end)\n\n\t\t case 'base64':\n\t\t return base64Slice(this, start, end)\n\n\t\t case 'ucs2':\n\t\t case 'ucs-2':\n\t\t case 'utf16le':\n\t\t case 'utf-16le':\n\t\t return utf16leSlice(this, start, end)\n\n\t\t default:\n\t\t if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n\t\t encoding = (encoding + '').toLowerCase();\n\t\t loweredCase = true;\n\t\t }\n\t\t }\n\t\t}\n\n\t\t// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n\t\t// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n\t\t// reliably in a browserify context because there could be multiple different\n\t\t// copies of the 'buffer' package in use. This method works even for Buffer\n\t\t// instances that were created from another copy of the `buffer` package.\n\t\t// See: https://github.com/feross/buffer/issues/154\n\t\tBuffer.prototype._isBuffer = true;\n\n\t\tfunction swap (b, n, m) {\n\t\t const i = b[n];\n\t\t b[n] = b[m];\n\t\t b[m] = i;\n\t\t}\n\n\t\tBuffer.prototype.swap16 = function swap16 () {\n\t\t const len = this.length;\n\t\t if (len % 2 !== 0) {\n\t\t throw new RangeError('Buffer size must be a multiple of 16-bits')\n\t\t }\n\t\t for (let i = 0; i < len; i += 2) {\n\t\t swap(this, i, i + 1);\n\t\t }\n\t\t return this\n\t\t};\n\n\t\tBuffer.prototype.swap32 = function swap32 () {\n\t\t const len = this.length;\n\t\t if (len % 4 !== 0) {\n\t\t throw new RangeError('Buffer size must be a multiple of 32-bits')\n\t\t }\n\t\t for (let i = 0; i < len; i += 4) {\n\t\t swap(this, i, i + 3);\n\t\t swap(this, i + 1, i + 2);\n\t\t }\n\t\t return this\n\t\t};\n\n\t\tBuffer.prototype.swap64 = function swap64 () {\n\t\t const len = this.length;\n\t\t if (len % 8 !== 0) {\n\t\t throw new RangeError('Buffer size must be a multiple of 64-bits')\n\t\t }\n\t\t for (let i = 0; i < len; i += 8) {\n\t\t swap(this, i, i + 7);\n\t\t swap(this, i + 1, i + 6);\n\t\t swap(this, i + 2, i + 5);\n\t\t swap(this, i + 3, i + 4);\n\t\t }\n\t\t return this\n\t\t};\n\n\t\tBuffer.prototype.toString = function toString () {\n\t\t const length = this.length;\n\t\t if (length === 0) return ''\n\t\t if (arguments.length === 0) return utf8Slice(this, 0, length)\n\t\t return slowToString.apply(this, arguments)\n\t\t};\n\n\t\tBuffer.prototype.toLocaleString = Buffer.prototype.toString;\n\n\t\tBuffer.prototype.equals = function equals (b) {\n\t\t if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n\t\t if (this === b) return true\n\t\t return Buffer.compare(this, b) === 0\n\t\t};\n\n\t\tBuffer.prototype.inspect = function inspect () {\n\t\t let str = '';\n\t\t const max = exports$1.INSPECT_MAX_BYTES;\n\t\t str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();\n\t\t if (this.length > max) str += ' ... ';\n\t\t return '<Buffer ' + str + '>'\n\t\t};\n\t\tif (customInspectSymbol) {\n\t\t Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;\n\t\t}\n\n\t\tBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n\t\t if (isInstance(target, Uint8Array)) {\n\t\t target = Buffer.from(target, target.offset, target.byteLength);\n\t\t }\n\t\t if (!Buffer.isBuffer(target)) {\n\t\t throw new TypeError(\n\t\t 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n\t\t 'Received type ' + (typeof target)\n\t\t )\n\t\t }\n\n\t\t if (start === undefined) {\n\t\t start = 0;\n\t\t }\n\t\t if (end === undefined) {\n\t\t end = target ? target.length : 0;\n\t\t }\n\t\t if (thisStart === undefined) {\n\t\t thisStart = 0;\n\t\t }\n\t\t if (thisEnd === undefined) {\n\t\t thisEnd = this.length;\n\t\t }\n\n\t\t if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n\t\t throw new RangeError('out of range index')\n\t\t }\n\n\t\t if (thisStart >= thisEnd && start >= end) {\n\t\t return 0\n\t\t }\n\t\t if (thisStart >= thisEnd) {\n\t\t return -1\n\t\t }\n\t\t if (start >= end) {\n\t\t return 1\n\t\t }\n\n\t\t start >>>= 0;\n\t\t end >>>= 0;\n\t\t thisStart >>>= 0;\n\t\t thisEnd >>>= 0;\n\n\t\t if (this === target) return 0\n\n\t\t let x = thisEnd - thisStart;\n\t\t let y = end - start;\n\t\t const len = Math.min(x, y);\n\n\t\t const thisCopy = this.slice(thisStart, thisEnd);\n\t\t const targetCopy = target.slice(start, end);\n\n\t\t for (let i = 0; i < len; ++i) {\n\t\t if (thisCopy[i] !== targetCopy[i]) {\n\t\t x = thisCopy[i];\n\t\t y = targetCopy[i];\n\t\t break\n\t\t }\n\t\t }\n\n\t\t if (x < y) return -1\n\t\t if (y < x) return 1\n\t\t return 0\n\t\t};\n\n\t\t// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n\t\t// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n\t\t//\n\t\t// Arguments:\n\t\t// - buffer - a Buffer to search\n\t\t// - val - a string, Buffer, or number\n\t\t// - byteOffset - an index into `buffer`; will be clamped to an int32\n\t\t// - encoding - an optional encoding, relevant is val is a string\n\t\t// - dir - true for indexOf, false for lastIndexOf\n\t\tfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n\t\t // Empty buffer means no match\n\t\t if (buffer.length === 0) return -1\n\n\t\t // Normalize byteOffset\n\t\t if (typeof byteOffset === 'string') {\n\t\t encoding = byteOffset;\n\t\t byteOffset = 0;\n\t\t } else if (byteOffset > 0x7fffffff) {\n\t\t byteOffset = 0x7fffffff;\n\t\t } else if (byteOffset < -2147483648) {\n\t\t byteOffset = -2147483648;\n\t\t }\n\t\t byteOffset = +byteOffset; // Coerce to Number.\n\t\t if (numberIsNaN(byteOffset)) {\n\t\t // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n\t\t byteOffset = dir ? 0 : (buffer.length - 1);\n\t\t }\n\n\t\t // Normalize byteOffset: negative offsets start from the end of the buffer\n\t\t if (byteOffset < 0) byteOffset = buffer.length + byteOffset;\n\t\t if (byteOffset >= buffer.length) {\n\t\t if (dir) return -1\n\t\t else byteOffset = buffer.length - 1;\n\t\t } else if (byteOffset < 0) {\n\t\t if (dir) byteOffset = 0;\n\t\t else return -1\n\t\t }\n\n\t\t // Normalize val\n\t\t if (typeof val === 'string') {\n\t\t val = Buffer.from(val, encoding);\n\t\t }\n\n\t\t // Finally, search either indexOf (if dir is true) or lastIndexOf\n\t\t if (Buffer.isBuffer(val)) {\n\t\t // Special case: looking for empty string/buffer always fails\n\t\t if (val.length === 0) {\n\t\t return -1\n\t\t }\n\t\t return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n\t\t } else if (typeof val === 'number') {\n\t\t val = val & 0xFF; // Search for a byte value [0-255]\n\t\t if (typeof Uint8Array.prototype.indexOf === 'function') {\n\t\t if (dir) {\n\t\t return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n\t\t } else {\n\t\t return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n\t\t }\n\t\t }\n\t\t return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n\t\t }\n\n\t\t throw new TypeError('val must be string, number or Buffer')\n\t\t}\n\n\t\tfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n\t\t let indexSize = 1;\n\t\t let arrLength = arr.length;\n\t\t let valLength = val.length;\n\n\t\t if (encoding !== undefined) {\n\t\t encoding = String(encoding).toLowerCase();\n\t\t if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n\t\t encoding === 'utf16le' || encoding === 'utf-16le') {\n\t\t if (arr.length < 2 || val.length < 2) {\n\t\t return -1\n\t\t }\n\t\t indexSize = 2;\n\t\t arrLength /= 2;\n\t\t valLength /= 2;\n\t\t byteOffset /= 2;\n\t\t }\n\t\t }\n\n\t\t function read (buf, i) {\n\t\t if (indexSize === 1) {\n\t\t return buf[i]\n\t\t } else {\n\t\t return buf.readUInt16BE(i * indexSize)\n\t\t }\n\t\t }\n\n\t\t let i;\n\t\t if (dir) {\n\t\t let foundIndex = -1;\n\t\t for (i = byteOffset; i < arrLength; i++) {\n\t\t if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n\t\t if (foundIndex === -1) foundIndex = i;\n\t\t if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n\t\t } else {\n\t\t if (foundIndex !== -1) i -= i - foundIndex;\n\t\t foundIndex = -1;\n\t\t }\n\t\t }\n\t\t } else {\n\t\t if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;\n\t\t for (i = byteOffset; i >= 0; i--) {\n\t\t let found = true;\n\t\t for (let j = 0; j < valLength; j++) {\n\t\t if (read(arr, i + j) !== read(val, j)) {\n\t\t found = false;\n\t\t break\n\t\t }\n\t\t }\n\t\t if (found) return i\n\t\t }\n\t\t }\n\n\t\t return -1\n\t\t}\n\n\t\tBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n\t\t return this.indexOf(val, byteOffset, encoding) !== -1\n\t\t};\n\n\t\tBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n\t\t return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n\t\t};\n\n\t\tBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n\t\t return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n\t\t};\n\n\t\tfunction hexWrite (buf, string, offset, length) {\n\t\t offset = Number(offset) || 0;\n\t\t const remaining = buf.length - offset;\n\t\t if (!length) {\n\t\t length = remaining;\n\t\t } else {\n\t\t length = Number(length);\n\t\t if (length > remaining) {\n\t\t length = remaining;\n\t\t }\n\t\t }\n\n\t\t const strLen = string.length;\n\n\t\t if (length > strLen / 2) {\n\t\t length = strLen / 2;\n\t\t }\n\t\t let i;\n\t\t for (i = 0; i < length; ++i) {\n\t\t const parsed = parseInt(string.substr(i * 2, 2), 16);\n\t\t if (numberIsNaN(parsed)) return i\n\t\t buf[offset + i] = parsed;\n\t\t }\n\t\t return i\n\t\t}\n\n\t\tfunction utf8Write (buf, string, offset, length) {\n\t\t return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n\t\t}\n\n\t\tfunction asciiWrite (buf, string, offset, length) {\n\t\t return blitBuffer(asciiToBytes(string), buf, offset, length)\n\t\t}\n\n\t\tfunction base64Write (buf, string, offset, length) {\n\t\t return blitBuffer(base64ToBytes(string), buf, offset, length)\n\t\t}\n\n\t\tfunction ucs2Write (buf, string, offset, length) {\n\t\t return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n\t\t}\n\n\t\tBuffer.prototype.write = function write (string, offset, length, encoding) {\n\t\t // Buffer#write(string)\n\t\t if (offset === undefined) {\n\t\t encoding = 'utf8';\n\t\t length = this.length;\n\t\t offset = 0;\n\t\t // Buffer#write(string, encoding)\n\t\t } else if (length === undefined && typeof offset === 'string') {\n\t\t encoding = offset;\n\t\t length = this.length;\n\t\t offset = 0;\n\t\t // Buffer#write(string, offset[, length][, encoding])\n\t\t } else if (isFinite(offset)) {\n\t\t offset = offset >>> 0;\n\t\t if (isFinite(length)) {\n\t\t length = length >>> 0;\n\t\t if (encoding === undefined) encoding = 'utf8';\n\t\t } else {\n\t\t encoding = length;\n\t\t length = undefined;\n\t\t }\n\t\t } else {\n\t\t throw new Error(\n\t\t 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n\t\t )\n\t\t }\n\n\t\t const remaining = this.length - offset;\n\t\t if (length === undefined || length > remaining) length = remaining;\n\n\t\t if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n\t\t throw new RangeError('Attempt to write outside buffer bounds')\n\t\t }\n\n\t\t if (!encoding) encoding = 'utf8';\n\n\t\t let loweredCase = false;\n\t\t for (;;) {\n\t\t switch (encoding) {\n\t\t case 'hex':\n\t\t return hexWrite(this, string, offset, length)\n\n\t\t case 'utf8':\n\t\t case 'utf-8':\n\t\t return utf8Write(this, string, offset, length)\n\n\t\t case 'ascii':\n\t\t case 'latin1':\n\t\t case 'binary':\n\t\t return asciiWrite(this, string, offset, length)\n\n\t\t case 'base64':\n\t\t // Warning: maxLength not taken into account in base64Write\n\t\t return base64Write(this, string, offset, length)\n\n\t\t case 'ucs2':\n\t\t case 'ucs-2':\n\t\t case 'utf16le':\n\t\t case 'utf-16le':\n\t\t return ucs2Write(this, string, offset, length)\n\n\t\t default:\n\t\t if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n\t\t encoding = ('' + encoding).toLowerCase();\n\t\t loweredCase = true;\n\t\t }\n\t\t }\n\t\t};\n\n\t\tBuffer.prototype.toJSON = function toJSON () {\n\t\t return {\n\t\t type: 'Buffer',\n\t\t data: Array.prototype.slice.call(this._arr || this, 0)\n\t\t }\n\t\t};\n\n\t\tfunction base64Slice (buf, start, end) {\n\t\t if (start === 0 && end === buf.length) {\n\t\t return base64.fromByteArray(buf)\n\t\t } else {\n\t\t return base64.fromByteArray(buf.slice(start, end))\n\t\t }\n\t\t}\n\n\t\tfunction utf8Slice (buf, start, end) {\n\t\t end = Math.min(buf.length, end);\n\t\t const res = [];\n\n\t\t let i = start;\n\t\t while (i < end) {\n\t\t const firstByte = buf[i];\n\t\t let codePoint = null;\n\t\t let bytesPerSequence = (firstByte > 0xEF)\n\t\t ? 4\n\t\t : (firstByte > 0xDF)\n\t\t ? 3\n\t\t : (firstByte > 0xBF)\n\t\t ? 2\n\t\t : 1;\n\n\t\t if (i + bytesPerSequence <= end) {\n\t\t let secondByte, thirdByte, fourthByte, tempCodePoint;\n\n\t\t switch (bytesPerSequence) {\n\t\t case 1:\n\t\t if (firstByte < 0x80) {\n\t\t codePoint = firstByte;\n\t\t }\n\t\t break\n\t\t case 2:\n\t\t secondByte = buf[i + 1];\n\t\t if ((secondByte & 0xC0) === 0x80) {\n\t\t tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);\n\t\t if (tempCodePoint > 0x7F) {\n\t\t codePoint = tempCodePoint;\n\t\t }\n\t\t }\n\t\t break\n\t\t case 3:\n\t\t secondByte = buf[i + 1];\n\t\t thirdByte = buf[i + 2];\n\t\t if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n\t\t tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);\n\t\t if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n\t\t codePoint = tempCodePoint;\n\t\t }\n\t\t }\n\t\t break\n\t\t case 4:\n\t\t secondByte = buf[i + 1];\n\t\t thirdByte = buf[i + 2];\n\t\t fourthByte = buf[i + 3];\n\t\t if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n\t\t tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);\n\t\t if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n\t\t codePoint = tempCodePoint;\n\t\t }\n\t\t }\n\t\t }\n\t\t }\n\n\t\t if (codePoint === null) {\n\t\t // we did not generate a valid codePoint so insert a\n\t\t // replacement char (U+FFFD) and advance only 1 byte\n\t\t codePoint = 0xFFFD;\n\t\t bytesPerSequence = 1;\n\t\t } else if (codePoint > 0xFFFF) {\n\t\t // encode to utf16 (surrogate pair dance)\n\t\t codePoint -= 0x10000;\n\t\t res.push(codePoint >>> 10 & 0x3FF | 0xD800);\n\t\t codePoint = 0xDC00 | codePoint & 0x3FF;\n\t\t }\n\n\t\t res.push(codePoint);\n\t\t i += bytesPerSequence;\n\t\t }\n\n\t\t return decodeCodePointsArray(res)\n\t\t}\n\n\t\t// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n\t\t// the lowest limit is Chrome, with 0x10000 args.\n\t\t// We go 1 magnitude less, for safety\n\t\tconst MAX_ARGUMENTS_LENGTH = 0x1000;\n\n\t\tfunction decodeCodePointsArray (codePoints) {\n\t\t const len = codePoints.length;\n\t\t if (len <= MAX_ARGUMENTS_LENGTH) {\n\t\t return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n\t\t }\n\n\t\t // Decode in chunks to avoid \"call stack size exceeded\".\n\t\t let res = '';\n\t\t let i = 0;\n\t\t while (i < len) {\n\t\t res += String.fromCharCode.apply(\n\t\t String,\n\t\t codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n\t\t );\n\t\t }\n\t\t return res\n\t\t}\n\n\t\tfunction asciiSlice (buf, start, end) {\n\t\t let ret = '';\n\t\t end = Math.min(buf.length, end);\n\n\t\t for (let i = start; i < end; ++i) {\n\t\t ret += String.fromCharCode(buf[i] & 0x7F);\n\t\t }\n\t\t return ret\n\t\t}\n\n\t\tfunction latin1Slice (buf, start, end) {\n\t\t let ret = '';\n\t\t end = Math.min(buf.length, end);\n\n\t\t for (let i = start; i < end; ++i) {\n\t\t ret += String.fromCharCode(buf[i]);\n\t\t }\n\t\t return ret\n\t\t}\n\n\t\tfunction hexSlice (buf, start, end) {\n\t\t const len = buf.length;\n\n\t\t if (!start || start < 0) start = 0;\n\t\t if (!end || end < 0 || end > len) end = len;\n\n\t\t let out = '';\n\t\t for (let i = start; i < end; ++i) {\n\t\t out += hexSliceLookupTable[buf[i]];\n\t\t }\n\t\t return out\n\t\t}\n\n\t\tfunction utf16leSlice (buf, start, end) {\n\t\t const bytes = buf.slice(start, end);\n\t\t let res = '';\n\t\t // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n\t\t for (let i = 0; i < bytes.length - 1; i += 2) {\n\t\t res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256));\n\t\t }\n\t\t return res\n\t\t}\n\n\t\tBuffer.prototype.slice = function slice (start, end) {\n\t\t const len = this.length;\n\t\t start = ~~start;\n\t\t end = end === undefined ? len : ~~end;\n\n\t\t if (start < 0) {\n\t\t start += len;\n\t\t if (start < 0) start = 0;\n\t\t } else if (start > len) {\n\t\t start = len;\n\t\t }\n\n\t\t if (end < 0) {\n\t\t end += len;\n\t\t if (end < 0) end = 0;\n\t\t } else if (end > len) {\n\t\t end = len;\n\t\t }\n\n\t\t if (end < start) end = start;\n\n\t\t const newBuf = this.subarray(start, end);\n\t\t // Return an augmented `Uint8Array` instance\n\t\t Object.setPrototypeOf(newBuf, Buffer.prototype);\n\n\t\t return newBuf\n\t\t};\n\n\t\t/*\n\t\t * Need to make sure that buffer isn't trying to write out of bounds.\n\t\t */\n\t\tfunction checkOffset (offset, ext, length) {\n\t\t if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n\t\t if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n\t\t}\n\n\t\tBuffer.prototype.readUintLE =\n\t\tBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t byteLength = byteLength >>> 0;\n\t\t if (!noAssert) checkOffset(offset, byteLength, this.length);\n\n\t\t let val = this[offset];\n\t\t let mul = 1;\n\t\t let i = 0;\n\t\t while (++i < byteLength && (mul *= 0x100)) {\n\t\t val += this[offset + i] * mul;\n\t\t }\n\n\t\t return val\n\t\t};\n\n\t\tBuffer.prototype.readUintBE =\n\t\tBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t byteLength = byteLength >>> 0;\n\t\t if (!noAssert) {\n\t\t checkOffset(offset, byteLength, this.length);\n\t\t }\n\n\t\t let val = this[offset + --byteLength];\n\t\t let mul = 1;\n\t\t while (byteLength > 0 && (mul *= 0x100)) {\n\t\t val += this[offset + --byteLength] * mul;\n\t\t }\n\n\t\t return val\n\t\t};\n\n\t\tBuffer.prototype.readUint8 =\n\t\tBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 1, this.length);\n\t\t return this[offset]\n\t\t};\n\n\t\tBuffer.prototype.readUint16LE =\n\t\tBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 2, this.length);\n\t\t return this[offset] | (this[offset + 1] << 8)\n\t\t};\n\n\t\tBuffer.prototype.readUint16BE =\n\t\tBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 2, this.length);\n\t\t return (this[offset] << 8) | this[offset + 1]\n\t\t};\n\n\t\tBuffer.prototype.readUint32LE =\n\t\tBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 4, this.length);\n\n\t\t return ((this[offset]) |\n\t\t (this[offset + 1] << 8) |\n\t\t (this[offset + 2] << 16)) +\n\t\t (this[offset + 3] * 0x1000000)\n\t\t};\n\n\t\tBuffer.prototype.readUint32BE =\n\t\tBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 4, this.length);\n\n\t\t return (this[offset] * 0x1000000) +\n\t\t ((this[offset + 1] << 16) |\n\t\t (this[offset + 2] << 8) |\n\t\t this[offset + 3])\n\t\t};\n\n\t\tBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n\t\t offset = offset >>> 0;\n\t\t validateNumber(offset, 'offset');\n\t\t const first = this[offset];\n\t\t const last = this[offset + 7];\n\t\t if (first === undefined || last === undefined) {\n\t\t boundsError(offset, this.length - 8);\n\t\t }\n\n\t\t const lo = first +\n\t\t this[++offset] * 2 ** 8 +\n\t\t this[++offset] * 2 ** 16 +\n\t\t this[++offset] * 2 ** 24;\n\n\t\t const hi = this[++offset] +\n\t\t this[++offset] * 2 ** 8 +\n\t\t this[++offset] * 2 ** 16 +\n\t\t last * 2 ** 24;\n\n\t\t return BigInt(lo) + (BigInt(hi) << BigInt(32))\n\t\t});\n\n\t\tBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n\t\t offset = offset >>> 0;\n\t\t validateNumber(offset, 'offset');\n\t\t const first = this[offset];\n\t\t const last = this[offset + 7];\n\t\t if (first === undefined || last === undefined) {\n\t\t boundsError(offset, this.length - 8);\n\t\t }\n\n\t\t const hi = first * 2 ** 24 +\n\t\t this[++offset] * 2 ** 16 +\n\t\t this[++offset] * 2 ** 8 +\n\t\t this[++offset];\n\n\t\t const lo = this[++offset] * 2 ** 24 +\n\t\t this[++offset] * 2 ** 16 +\n\t\t this[++offset] * 2 ** 8 +\n\t\t last;\n\n\t\t return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n\t\t});\n\n\t\tBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t byteLength = byteLength >>> 0;\n\t\t if (!noAssert) checkOffset(offset, byteLength, this.length);\n\n\t\t let val = this[offset];\n\t\t let mul = 1;\n\t\t let i = 0;\n\t\t while (++i < byteLength && (mul *= 0x100)) {\n\t\t val += this[offset + i] * mul;\n\t\t }\n\t\t mul *= 0x80;\n\n\t\t if (val >= mul) val -= Math.pow(2, 8 * byteLength);\n\n\t\t return val\n\t\t};\n\n\t\tBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t byteLength = byteLength >>> 0;\n\t\t if (!noAssert) checkOffset(offset, byteLength, this.length);\n\n\t\t let i = byteLength;\n\t\t let mul = 1;\n\t\t let val = this[offset + --i];\n\t\t while (i > 0 && (mul *= 0x100)) {\n\t\t val += this[offset + --i] * mul;\n\t\t }\n\t\t mul *= 0x80;\n\n\t\t if (val >= mul) val -= Math.pow(2, 8 * byteLength);\n\n\t\t return val\n\t\t};\n\n\t\tBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 1, this.length);\n\t\t if (!(this[offset] & 0x80)) return (this[offset])\n\t\t return ((0xff - this[offset] + 1) * -1)\n\t\t};\n\n\t\tBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 2, this.length);\n\t\t const val = this[offset] | (this[offset + 1] << 8);\n\t\t return (val & 0x8000) ? val | 0xFFFF0000 : val\n\t\t};\n\n\t\tBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 2, this.length);\n\t\t const val = this[offset + 1] | (this[offset] << 8);\n\t\t return (val & 0x8000) ? val | 0xFFFF0000 : val\n\t\t};\n\n\t\tBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 4, this.length);\n\n\t\t return (this[offset]) |\n\t\t (this[offset + 1] << 8) |\n\t\t (this[offset + 2] << 16) |\n\t\t (this[offset + 3] << 24)\n\t\t};\n\n\t\tBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 4, this.length);\n\n\t\t return (this[offset] << 24) |\n\t\t (this[offset + 1] << 16) |\n\t\t (this[offset + 2] << 8) |\n\t\t (this[offset + 3])\n\t\t};\n\n\t\tBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n\t\t offset = offset >>> 0;\n\t\t validateNumber(offset, 'offset');\n\t\t const first = this[offset];\n\t\t const last = this[offset + 7];\n\t\t if (first === undefined || last === undefined) {\n\t\t boundsError(offset, this.length - 8);\n\t\t }\n\n\t\t const val = this[offset + 4] +\n\t\t this[offset + 5] * 2 ** 8 +\n\t\t this[offset + 6] * 2 ** 16 +\n\t\t (last << 24); // Overflow\n\n\t\t return (BigInt(val) << BigInt(32)) +\n\t\t BigInt(first +\n\t\t this[++offset] * 2 ** 8 +\n\t\t this[++offset] * 2 ** 16 +\n\t\t this[++offset] * 2 ** 24)\n\t\t});\n\n\t\tBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n\t\t offset = offset >>> 0;\n\t\t validateNumber(offset, 'offset');\n\t\t const first = this[offset];\n\t\t const last = this[offset + 7];\n\t\t if (first === undefined || last === undefined) {\n\t\t boundsError(offset, this.length - 8);\n\t\t }\n\n\t\t const val = (first << 24) + // Overflow\n\t\t this[++offset] * 2 ** 16 +\n\t\t this[++offset] * 2 ** 8 +\n\t\t this[++offset];\n\n\t\t return (BigInt(val) << BigInt(32)) +\n\t\t BigInt(this[++offset] * 2 ** 24 +\n\t\t this[++offset] * 2 ** 16 +\n\t\t this[++offset] * 2 ** 8 +\n\t\t last)\n\t\t});\n\n\t\tBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 4, this.length);\n\t\t return ieee754.read(this, offset, true, 23, 4)\n\t\t};\n\n\t\tBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 4, this.length);\n\t\t return ieee754.read(this, offset, false, 23, 4)\n\t\t};\n\n\t\tBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 8, this.length);\n\t\t return ieee754.read(this, offset, true, 52, 8)\n\t\t};\n\n\t\tBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkOffset(offset, 8, this.length);\n\t\t return ieee754.read(this, offset, false, 52, 8)\n\t\t};\n\n\t\tfunction checkInt (buf, value, offset, ext, max, min) {\n\t\t if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n\t\t if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n\t\t if (offset + ext > buf.length) throw new RangeError('Index out of range')\n\t\t}\n\n\t\tBuffer.prototype.writeUintLE =\n\t\tBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t byteLength = byteLength >>> 0;\n\t\t if (!noAssert) {\n\t\t const maxBytes = Math.pow(2, 8 * byteLength) - 1;\n\t\t checkInt(this, value, offset, byteLength, maxBytes, 0);\n\t\t }\n\n\t\t let mul = 1;\n\t\t let i = 0;\n\t\t this[offset] = value & 0xFF;\n\t\t while (++i < byteLength && (mul *= 0x100)) {\n\t\t this[offset + i] = (value / mul) & 0xFF;\n\t\t }\n\n\t\t return offset + byteLength\n\t\t};\n\n\t\tBuffer.prototype.writeUintBE =\n\t\tBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t byteLength = byteLength >>> 0;\n\t\t if (!noAssert) {\n\t\t const maxBytes = Math.pow(2, 8 * byteLength) - 1;\n\t\t checkInt(this, value, offset, byteLength, maxBytes, 0);\n\t\t }\n\n\t\t let i = byteLength - 1;\n\t\t let mul = 1;\n\t\t this[offset + i] = value & 0xFF;\n\t\t while (--i >= 0 && (mul *= 0x100)) {\n\t\t this[offset + i] = (value / mul) & 0xFF;\n\t\t }\n\n\t\t return offset + byteLength\n\t\t};\n\n\t\tBuffer.prototype.writeUint8 =\n\t\tBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);\n\t\t this[offset] = (value & 0xff);\n\t\t return offset + 1\n\t\t};\n\n\t\tBuffer.prototype.writeUint16LE =\n\t\tBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);\n\t\t this[offset] = (value & 0xff);\n\t\t this[offset + 1] = (value >>> 8);\n\t\t return offset + 2\n\t\t};\n\n\t\tBuffer.prototype.writeUint16BE =\n\t\tBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);\n\t\t this[offset] = (value >>> 8);\n\t\t this[offset + 1] = (value & 0xff);\n\t\t return offset + 2\n\t\t};\n\n\t\tBuffer.prototype.writeUint32LE =\n\t\tBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);\n\t\t this[offset + 3] = (value >>> 24);\n\t\t this[offset + 2] = (value >>> 16);\n\t\t this[offset + 1] = (value >>> 8);\n\t\t this[offset] = (value & 0xff);\n\t\t return offset + 4\n\t\t};\n\n\t\tBuffer.prototype.writeUint32BE =\n\t\tBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);\n\t\t this[offset] = (value >>> 24);\n\t\t this[offset + 1] = (value >>> 16);\n\t\t this[offset + 2] = (value >>> 8);\n\t\t this[offset + 3] = (value & 0xff);\n\t\t return offset + 4\n\t\t};\n\n\t\tfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n\t\t checkIntBI(value, min, max, buf, offset, 7);\n\n\t\t let lo = Number(value & BigInt(0xffffffff));\n\t\t buf[offset++] = lo;\n\t\t lo = lo >> 8;\n\t\t buf[offset++] = lo;\n\t\t lo = lo >> 8;\n\t\t buf[offset++] = lo;\n\t\t lo = lo >> 8;\n\t\t buf[offset++] = lo;\n\t\t let hi = Number(value >> BigInt(32) & BigInt(0xffffffff));\n\t\t buf[offset++] = hi;\n\t\t hi = hi >> 8;\n\t\t buf[offset++] = hi;\n\t\t hi = hi >> 8;\n\t\t buf[offset++] = hi;\n\t\t hi = hi >> 8;\n\t\t buf[offset++] = hi;\n\t\t return offset\n\t\t}\n\n\t\tfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n\t\t checkIntBI(value, min, max, buf, offset, 7);\n\n\t\t let lo = Number(value & BigInt(0xffffffff));\n\t\t buf[offset + 7] = lo;\n\t\t lo = lo >> 8;\n\t\t buf[offset + 6] = lo;\n\t\t lo = lo >> 8;\n\t\t buf[offset + 5] = lo;\n\t\t lo = lo >> 8;\n\t\t buf[offset + 4] = lo;\n\t\t let hi = Number(value >> BigInt(32) & BigInt(0xffffffff));\n\t\t buf[offset + 3] = hi;\n\t\t hi = hi >> 8;\n\t\t buf[offset + 2] = hi;\n\t\t hi = hi >> 8;\n\t\t buf[offset + 1] = hi;\n\t\t hi = hi >> 8;\n\t\t buf[offset] = hi;\n\t\t return offset + 8\n\t\t}\n\n\t\tBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n\t\t return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n\t\t});\n\n\t\tBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n\t\t return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n\t\t});\n\n\t\tBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) {\n\t\t const limit = Math.pow(2, (8 * byteLength) - 1);\n\n\t\t checkInt(this, value, offset, byteLength, limit - 1, -limit);\n\t\t }\n\n\t\t let i = 0;\n\t\t let mul = 1;\n\t\t let sub = 0;\n\t\t this[offset] = value & 0xFF;\n\t\t while (++i < byteLength && (mul *= 0x100)) {\n\t\t if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n\t\t sub = 1;\n\t\t }\n\t\t this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;\n\t\t }\n\n\t\t return offset + byteLength\n\t\t};\n\n\t\tBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) {\n\t\t const limit = Math.pow(2, (8 * byteLength) - 1);\n\n\t\t checkInt(this, value, offset, byteLength, limit - 1, -limit);\n\t\t }\n\n\t\t let i = byteLength - 1;\n\t\t let mul = 1;\n\t\t let sub = 0;\n\t\t this[offset + i] = value & 0xFF;\n\t\t while (--i >= 0 && (mul *= 0x100)) {\n\t\t if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n\t\t sub = 1;\n\t\t }\n\t\t this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;\n\t\t }\n\n\t\t return offset + byteLength\n\t\t};\n\n\t\tBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -128);\n\t\t if (value < 0) value = 0xff + value + 1;\n\t\t this[offset] = (value & 0xff);\n\t\t return offset + 1\n\t\t};\n\n\t\tBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);\n\t\t this[offset] = (value & 0xff);\n\t\t this[offset + 1] = (value >>> 8);\n\t\t return offset + 2\n\t\t};\n\n\t\tBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);\n\t\t this[offset] = (value >>> 8);\n\t\t this[offset + 1] = (value & 0xff);\n\t\t return offset + 2\n\t\t};\n\n\t\tBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);\n\t\t this[offset] = (value & 0xff);\n\t\t this[offset + 1] = (value >>> 8);\n\t\t this[offset + 2] = (value >>> 16);\n\t\t this[offset + 3] = (value >>> 24);\n\t\t return offset + 4\n\t\t};\n\n\t\tBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);\n\t\t if (value < 0) value = 0xffffffff + value + 1;\n\t\t this[offset] = (value >>> 24);\n\t\t this[offset + 1] = (value >>> 16);\n\t\t this[offset + 2] = (value >>> 8);\n\t\t this[offset + 3] = (value & 0xff);\n\t\t return offset + 4\n\t\t};\n\n\t\tBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n\t\t return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n\t\t});\n\n\t\tBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n\t\t return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n\t\t});\n\n\t\tfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n\t\t if (offset + ext > buf.length) throw new RangeError('Index out of range')\n\t\t if (offset < 0) throw new RangeError('Index out of range')\n\t\t}\n\n\t\tfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) {\n\t\t checkIEEE754(buf, value, offset, 4);\n\t\t }\n\t\t ieee754.write(buf, value, offset, littleEndian, 23, 4);\n\t\t return offset + 4\n\t\t}\n\n\t\tBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n\t\t return writeFloat(this, value, offset, true, noAssert)\n\t\t};\n\n\t\tBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n\t\t return writeFloat(this, value, offset, false, noAssert)\n\t\t};\n\n\t\tfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n\t\t value = +value;\n\t\t offset = offset >>> 0;\n\t\t if (!noAssert) {\n\t\t checkIEEE754(buf, value, offset, 8);\n\t\t }\n\t\t ieee754.write(buf, value, offset, littleEndian, 52, 8);\n\t\t return offset + 8\n\t\t}\n\n\t\tBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n\t\t return writeDouble(this, value, offset, true, noAssert)\n\t\t};\n\n\t\tBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n\t\t return writeDouble(this, value, offset, false, noAssert)\n\t\t};\n\n\t\t// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\n\t\tBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n\t\t if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n\t\t if (!start) start = 0;\n\t\t if (!end && end !== 0) end = this.length;\n\t\t if (targetStart >= target.length) targetStart = target.length;\n\t\t if (!targetStart) targetStart = 0;\n\t\t if (end > 0 && end < start) end = start;\n\n\t\t // Copy 0 bytes; we're done\n\t\t if (end === start) return 0\n\t\t if (target.length === 0 || this.length === 0) return 0\n\n\t\t // Fatal error conditions\n\t\t if (targetStart < 0) {\n\t\t throw new RangeError('targetStart out of bounds')\n\t\t }\n\t\t if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n\t\t if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n\t\t // Are we oob?\n\t\t if (end > this.length) end = this.length;\n\t\t if (target.length - targetStart < end - start) {\n\t\t end = target.length - targetStart + start;\n\t\t }\n\n\t\t const len = end - start;\n\n\t\t if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n\t\t // Use built-in when available, missing from IE11\n\t\t this.copyWithin(targetStart, start, end);\n\t\t } else {\n\t\t Uint8Array.prototype.set.call(\n\t\t target,\n\t\t this.subarray(start, end),\n\t\t targetStart\n\t\t );\n\t\t }\n\n\t\t return len\n\t\t};\n\n\t\t// Usage:\n\t\t// buffer.fill(number[, offset[, end]])\n\t\t// buffer.fill(buffer[, offset[, end]])\n\t\t// buffer.fill(string[, offset[, end]][, encoding])\n\t\tBuffer.prototype.fill = function fill (val, start, end, encoding) {\n\t\t // Handle string cases:\n\t\t if (typeof val === 'string') {\n\t\t if (typeof start === 'string') {\n\t\t encoding = start;\n\t\t start = 0;\n\t\t end = this.length;\n\t\t } else if (typeof end === 'string') {\n\t\t encoding = end;\n\t\t end = this.length;\n\t\t }\n\t\t if (encoding !== undefined && typeof encoding !== 'string') {\n\t\t throw new TypeError('encoding must be a string')\n\t\t }\n\t\t if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n\t\t throw new TypeError('Unknown encoding: ' + encoding)\n\t\t }\n\t\t if (val.length === 1) {\n\t\t const code = val.charCodeAt(0);\n\t\t if ((encoding === 'utf8' && code < 128) ||\n\t\t encoding === 'latin1') {\n\t\t // Fast path: If `val` fits into a single byte, use that numeric value.\n\t\t val = code;\n\t\t }\n\t\t }\n\t\t } else if (typeof val === 'number') {\n\t\t val = val & 255;\n\t\t } else if (typeof val === 'boolean') {\n\t\t val = Number(val);\n\t\t }\n\n\t\t // Invalid ranges are not set to a default, so can range check early.\n\t\t if (start < 0 || this.length < start || this.length < end) {\n\t\t throw new RangeError('Out of range index')\n\t\t }\n\n\t\t if (end <= start) {\n\t\t return this\n\t\t }\n\n\t\t start = start >>> 0;\n\t\t end = end === undefined ? this.length : end >>> 0;\n\n\t\t if (!val) val = 0;\n\n\t\t let i;\n\t\t if (typeof val === 'number') {\n\t\t for (i = start; i < end; ++i) {\n\t\t this[i] = val;\n\t\t }\n\t\t } else {\n\t\t const bytes = Buffer.isBuffer(val)\n\t\t ? val\n\t\t : Buffer.from(val, encoding);\n\t\t const len = bytes.length;\n\t\t if (len === 0) {\n\t\t throw new TypeError('The value \"' + val +\n\t\t '\" is invalid for argument \"value\"')\n\t\t }\n\t\t for (i = 0; i < end - start; ++i) {\n\t\t this[i + start] = bytes[i % len];\n\t\t }\n\t\t }\n\n\t\t return this\n\t\t};\n\n\t\t// CUSTOM ERRORS\n\t\t// =============\n\n\t\t// Simplified versions from Node, changed for Buffer-only usage\n\t\tconst errors = {};\n\t\tfunction E (sym, getMessage, Base) {\n\t\t errors[sym] = class NodeError extends Base {\n\t\t constructor () {\n\t\t super();\n\n\t\t Object.defineProperty(this, 'message', {\n\t\t value: getMessage.apply(this, arguments),\n\t\t writable: true,\n\t\t configurable: true\n\t\t });\n\n\t\t // Add the error code to the name to include it in the stack trace.\n\t\t this.name = `${this.name} [${sym}]`;\n\t\t // Access the stack to generate the error message including the error code\n\t\t // from the name.\n\t\t this.stack; // eslint-disable-line no-unused-expressions\n\t\t // Reset the name to the actual name.\n\t\t delete this.name;\n\t\t }\n\n\t\t get code () {\n\t\t return sym\n\t\t }\n\n\t\t set code (value) {\n\t\t Object.defineProperty(this, 'code', {\n\t\t configurable: true,\n\t\t enumerable: true,\n\t\t value,\n\t\t writable: true\n\t\t });\n\t\t }\n\n\t\t toString () {\n\t\t return `${this.name} [${sym}]: ${this.message}`\n\t\t }\n\t\t };\n\t\t}\n\n\t\tE('ERR_BUFFER_OUT_OF_BOUNDS',\n\t\t function (name) {\n\t\t if (name) {\n\t\t return `${name} is outside of buffer bounds`\n\t\t }\n\n\t\t return 'Attempt to access memory outside buffer bounds'\n\t\t }, RangeError);\n\t\tE('ERR_INVALID_ARG_TYPE',\n\t\t function (name, actual) {\n\t\t return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n\t\t }, TypeError);\n\t\tE('ERR_OUT_OF_RANGE',\n\t\t function (str, range, input) {\n\t\t let msg = `The value of \"${str}\" is out of range.`;\n\t\t let received = input;\n\t\t if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n\t\t received = addNumericalSeparator(String(input));\n\t\t } else if (typeof input === 'bigint') {\n\t\t received = String(input);\n\t\t if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n\t\t received = addNumericalSeparator(received);\n\t\t }\n\t\t received += 'n';\n\t\t }\n\t\t msg += ` It must be ${range}. Received ${received}`;\n\t\t return msg\n\t\t }, RangeError);\n\n\t\tfunction addNumericalSeparator (val) {\n\t\t let res = '';\n\t\t let i = val.length;\n\t\t const start = val[0] === '-' ? 1 : 0;\n\t\t for (; i >= start + 4; i -= 3) {\n\t\t res = `_${val.slice(i - 3, i)}${res}`;\n\t\t }\n\t\t return `${val.slice(0, i)}${res}`\n\t\t}\n\n\t\t// CHECK FUNCTIONS\n\t\t// ===============\n\n\t\tfunction checkBounds (buf, offset, byteLength) {\n\t\t validateNumber(offset, 'offset');\n\t\t if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n\t\t boundsError(offset, buf.length - (byteLength + 1));\n\t\t }\n\t\t}\n\n\t\tfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n\t\t if (value > max || value < min) {\n\t\t const n = typeof min === 'bigint' ? 'n' : '';\n\t\t let range;\n\t\t {\n\t\t if (min === 0 || min === BigInt(0)) {\n\t\t range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`;\n\t\t } else {\n\t\t range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n\t\t `${(byteLength + 1) * 8 - 1}${n}`;\n\t\t }\n\t\t }\n\t\t throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n\t\t }\n\t\t checkBounds(buf, offset, byteLength);\n\t\t}\n\n\t\tfunction validateNumber (value, name) {\n\t\t if (typeof value !== 'number') {\n\t\t throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n\t\t }\n\t\t}\n\n\t\tfunction boundsError (value, length, type) {\n\t\t if (Math.floor(value) !== value) {\n\t\t validateNumber(value, type);\n\t\t throw new errors.ERR_OUT_OF_RANGE('offset', 'an integer', value)\n\t\t }\n\n\t\t if (length < 0) {\n\t\t throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n\t\t }\n\n\t\t throw new errors.ERR_OUT_OF_RANGE('offset',\n\t\t `>= ${0} and <= ${length}`,\n\t\t value)\n\t\t}\n\n\t\t// HELPER FUNCTIONS\n\t\t// ================\n\n\t\tconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;\n\n\t\tfunction base64clean (str) {\n\t\t // Node takes equal signs as end of the Base64 encoding\n\t\t str = str.split('=')[0];\n\t\t // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n\t\t str = str.trim().replace(INVALID_BASE64_RE, '');\n\t\t // Node converts strings with length < 2 to ''\n\t\t if (str.length < 2) return ''\n\t\t // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n\t\t while (str.length % 4 !== 0) {\n\t\t str = str + '=';\n\t\t }\n\t\t return str\n\t\t}\n\n\t\tfunction utf8ToBytes (string, units) {\n\t\t units = units || Infinity;\n\t\t let codePoint;\n\t\t const length = string.length;\n\t\t let leadSurrogate = null;\n\t\t const bytes = [];\n\n\t\t for (let i = 0; i < length; ++i) {\n\t\t codePoint = string.charCodeAt(i);\n\n\t\t // is surrogate component\n\t\t if (codePoint > 0xD7FF && codePoint < 0xE000) {\n\t\t // last char was a lead\n\t\t if (!leadSurrogate) {\n\t\t // no lead yet\n\t\t if (codePoint > 0xDBFF) {\n\t\t // unexpected trail\n\t\t if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n\t\t continue\n\t\t } else if (i + 1 === length) {\n\t\t // unpaired lead\n\t\t if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n\t\t continue\n\t\t }\n\n\t\t // valid lead\n\t\t leadSurrogate = codePoint;\n\n\t\t continue\n\t\t }\n\n\t\t // 2 leads in a row\n\t\t if (codePoint < 0xDC00) {\n\t\t if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n\t\t leadSurrogate = codePoint;\n\t\t continue\n\t\t }\n\n\t\t // valid surrogate pair\n\t\t codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;\n\t\t } else if (leadSurrogate) {\n\t\t // valid bmp char, but last char was a lead\n\t\t if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n\t\t }\n\n\t\t leadSurrogate = null;\n\n\t\t // encode utf8\n\t\t if (codePoint < 0x80) {\n\t\t if ((units -= 1) < 0) break\n\t\t bytes.push(codePoint);\n\t\t } else if (codePoint < 0x800) {\n\t\t if ((units -= 2) < 0) break\n\t\t bytes.push(\n\t\t codePoint >> 0x6 | 0xC0,\n\t\t codePoint & 0x3F | 0x80\n\t\t );\n\t\t } else if (codePoint < 0x10000) {\n\t\t if ((units -= 3) < 0) break\n\t\t bytes.push(\n\t\t codePoint >> 0xC | 0xE0,\n\t\t codePoint >> 0x6 & 0x3F | 0x80,\n\t\t codePoint & 0x3F | 0x80\n\t\t );\n\t\t } else if (codePoint < 0x110000) {\n\t\t if ((units -= 4) < 0) break\n\t\t bytes.push(\n\t\t codePoint >> 0x12 | 0xF0,\n\t\t codePoint >> 0xC & 0x3F | 0x80,\n\t\t codePoint >> 0x6 & 0x3F | 0x80,\n\t\t codePoint & 0x3F | 0x80\n\t\t );\n\t\t } else {\n\t\t throw new Error('Invalid code point')\n\t\t }\n\t\t }\n\n\t\t return bytes\n\t\t}\n\n\t\tfunction asciiToBytes (str) {\n\t\t const byteArray = [];\n\t\t for (let i = 0; i < str.length; ++i) {\n\t\t // Node's code seems to be doing this and not & 0x7F..\n\t\t byteArray.push(str.charCodeAt(i) & 0xFF);\n\t\t }\n\t\t return byteArray\n\t\t}\n\n\t\tfunction utf16leToBytes (str, units) {\n\t\t let c, hi, lo;\n\t\t const byteArray = [];\n\t\t for (let i = 0; i < str.length; ++i) {\n\t\t if ((units -= 2) < 0) break\n\n\t\t c = str.charCodeAt(i);\n\t\t hi = c >> 8;\n\t\t lo = c % 256;\n\t\t byteArray.push(lo);\n\t\t byteArray.push(hi);\n\t\t }\n\n\t\t return byteArray\n\t\t}\n\n\t\tfunction base64ToBytes (str) {\n\t\t return base64.toByteArray(base64clean(str))\n\t\t}\n\n\t\tfunction blitBuffer (src, dst, offset, length) {\n\t\t let i;\n\t\t for (i = 0; i < length; ++i) {\n\t\t if ((i + offset >= dst.length) || (i >= src.length)) break\n\t\t dst[i + offset] = src[i];\n\t\t }\n\t\t return i\n\t\t}\n\n\t\t// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n\t\t// the `instanceof` check but they should be treated as of that type.\n\t\t// See: https://github.com/feross/buffer/issues/166\n\t\tfunction isInstance (obj, type) {\n\t\t return obj instanceof type ||\n\t\t (obj != null && obj.constructor != null && obj.constructor.name != null &&\n\t\t obj.constructor.name === type.name)\n\t\t}\n\t\tfunction numberIsNaN (obj) {\n\t\t // For IE11 support\n\t\t return obj !== obj // eslint-disable-line no-self-compare\n\t\t}\n\n\t\t// Create lookup table for `toString('hex')`\n\t\t// See: https://github.com/feross/buffer/issues/219\n\t\tconst hexSliceLookupTable = (function () {\n\t\t const alphabet = '0123456789abcdef';\n\t\t const table = new Array(256);\n\t\t for (let i = 0; i < 16; ++i) {\n\t\t const i16 = i * 16;\n\t\t for (let j = 0; j < 16; ++j) {\n\t\t table[i16 + j] = alphabet[i] + alphabet[j];\n\t\t }\n\t\t }\n\t\t return table\n\t\t})();\n\n\t\t// Return not function with Error if BigInt not supported\n\t\tfunction defineBigIntMethod (fn) {\n\t\t return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n\t\t}\n\n\t\tfunction BufferBigIntNotDefined () {\n\t\t throw new Error('BigInt not supported')\n\t\t} \n\t} (buffer));\n\treturn buffer;\n}\n\nvar bufferExports = requireBuffer();\n\nvar dist = {};\n\nvar Codecs = {};\n\nvar Frames = {};\n\nvar hasRequiredFrames;\n\nfunction requireFrames () {\n\tif (hasRequiredFrames) return Frames;\n\thasRequiredFrames = 1;\n\t(function (exports$1) {\n\t\t/*\n\t\t * Copyright 2021-2022 the original author or authors.\n\t\t *\n\t\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t\t * you may not use this file except in compliance with the License.\n\t\t * You may obtain a copy of the License at\n\t\t *\n\t\t * http://www.apache.org/licenses/LICENSE-2.0\n\t\t *\n\t\t * Unless required by applicable law or agreed to in writing, software\n\t\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t\t * See the License for the specific language governing permissions and\n\t\t * limitations under the License.\n\t\t */\n\t\tObject.defineProperty(exports$1, \"__esModule\", { value: true });\n\t\texports$1.Frame = exports$1.Lengths = exports$1.Flags = exports$1.FrameTypes = void 0;\n\t\tvar FrameTypes;\n\t\t(function (FrameTypes) {\n\t\t FrameTypes[FrameTypes[\"RESERVED\"] = 0] = \"RESERVED\";\n\t\t FrameTypes[FrameTypes[\"SETUP\"] = 1] = \"SETUP\";\n\t\t FrameTypes[FrameTypes[\"LEASE\"] = 2] = \"LEASE\";\n\t\t FrameTypes[FrameTypes[\"KEEPALIVE\"] = 3] = \"KEEPALIVE\";\n\t\t FrameTypes[FrameTypes[\"REQUEST_RESPONSE\"] = 4] = \"REQUEST_RESPONSE\";\n\t\t FrameTypes[FrameTypes[\"REQUEST_FNF\"] = 5] = \"REQUEST_FNF\";\n\t\t FrameTypes[FrameTypes[\"REQUEST_STREAM\"] = 6] = \"REQUEST_STREAM\";\n\t\t FrameTypes[FrameTypes[\"REQUEST_CHANNEL\"] = 7] = \"REQUEST_CHANNEL\";\n\t\t FrameTypes[FrameTypes[\"REQUEST_N\"] = 8] = \"REQUEST_N\";\n\t\t FrameTypes[FrameTypes[\"CANCEL\"] = 9] = \"CANCEL\";\n\t\t FrameTypes[FrameTypes[\"PAYLOAD\"] = 10] = \"PAYLOAD\";\n\t\t FrameTypes[FrameTypes[\"ERROR\"] = 11] = \"ERROR\";\n\t\t FrameTypes[FrameTypes[\"METADATA_PUSH\"] = 12] = \"METADATA_PUSH\";\n\t\t FrameTypes[FrameTypes[\"RESUME\"] = 13] = \"RESUME\";\n\t\t FrameTypes[FrameTypes[\"RESUME_OK\"] = 14] = \"RESUME_OK\";\n\t\t FrameTypes[FrameTypes[\"EXT\"] = 63] = \"EXT\";\n\t\t})(FrameTypes = exports$1.FrameTypes || (exports$1.FrameTypes = {}));\n\t\t(function (Flags) {\n\t\t Flags[Flags[\"NONE\"] = 0] = \"NONE\";\n\t\t Flags[Flags[\"COMPLETE\"] = 64] = \"COMPLETE\";\n\t\t Flags[Flags[\"FOLLOWS\"] = 128] = \"FOLLOWS\";\n\t\t Flags[Flags[\"IGNORE\"] = 512] = \"IGNORE\";\n\t\t Flags[Flags[\"LEASE\"] = 64] = \"LEASE\";\n\t\t Flags[Flags[\"METADATA\"] = 256] = \"METADATA\";\n\t\t Flags[Flags[\"NEXT\"] = 32] = \"NEXT\";\n\t\t Flags[Flags[\"RESPOND\"] = 128] = \"RESPOND\";\n\t\t Flags[Flags[\"RESUME_ENABLE\"] = 128] = \"RESUME_ENABLE\";\n\t\t})(exports$1.Flags || (exports$1.Flags = {}));\n\t\t(function (Flags) {\n\t\t function hasMetadata(flags) {\n\t\t return (flags & Flags.METADATA) === Flags.METADATA;\n\t\t }\n\t\t Flags.hasMetadata = hasMetadata;\n\t\t function hasComplete(flags) {\n\t\t return (flags & Flags.COMPLETE) === Flags.COMPLETE;\n\t\t }\n\t\t Flags.hasComplete = hasComplete;\n\t\t function hasNext(flags) {\n\t\t return (flags & Flags.NEXT) === Flags.NEXT;\n\t\t }\n\t\t Flags.hasNext = hasNext;\n\t\t function hasFollows(flags) {\n\t\t return (flags & Flags.FOLLOWS) === Flags.FOLLOWS;\n\t\t }\n\t\t Flags.hasFollows = hasFollows;\n\t\t function hasIgnore(flags) {\n\t\t return (flags & Flags.IGNORE) === Flags.IGNORE;\n\t\t }\n\t\t Flags.hasIgnore = hasIgnore;\n\t\t function hasRespond(flags) {\n\t\t return (flags & Flags.RESPOND) === Flags.RESPOND;\n\t\t }\n\t\t Flags.hasRespond = hasRespond;\n\t\t function hasLease(flags) {\n\t\t return (flags & Flags.LEASE) === Flags.LEASE;\n\t\t }\n\t\t Flags.hasLease = hasLease;\n\t\t function hasResume(flags) {\n\t\t return (flags & Flags.RESUME_ENABLE) === Flags.RESUME_ENABLE;\n\t\t }\n\t\t Flags.hasResume = hasResume;\n\t\t})(exports$1.Flags || (exports$1.Flags = {}));\n\t\t(function (Lengths) {\n\t\t Lengths[Lengths[\"FRAME\"] = 3] = \"FRAME\";\n\t\t Lengths[Lengths[\"HEADER\"] = 6] = \"HEADER\";\n\t\t Lengths[Lengths[\"METADATA\"] = 3] = \"METADATA\";\n\t\t Lengths[Lengths[\"REQUEST\"] = 3] = \"REQUEST\";\n\t\t})(exports$1.Lengths || (exports$1.Lengths = {}));\n\t\t(function (Frame) {\n\t\t function isConnection(frame) {\n\t\t return frame.streamId === 0;\n\t\t }\n\t\t Frame.isConnection = isConnection;\n\t\t function isRequest(frame) {\n\t\t return (FrameTypes.REQUEST_RESPONSE <= frame.type &&\n\t\t frame.type <= FrameTypes.REQUEST_CHANNEL);\n\t\t }\n\t\t Frame.isRequest = isRequest;\n\t\t})(exports$1.Frame || (exports$1.Frame = {}));\n\t\t\n\t} (Frames));\n\treturn Frames;\n}\n\nvar hasRequiredCodecs;\n\nfunction requireCodecs () {\n\tif (hasRequiredCodecs) return Codecs;\n\thasRequiredCodecs = 1;\n\t(function (exports$1) {\n\t\tvar __generator = (Codecs && Codecs.__generator) || function (thisArg, body) {\n\t\t var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n\t\t return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n\t\t function verb(n) { return function (v) { return step([n, v]); }; }\n\t\t function step(op) {\n\t\t if (f) throw new TypeError(\"Generator is already executing.\");\n\t\t while (_) try {\n\t\t if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n\t\t if (y = 0, t) op = [op[0] & 2, t.value];\n\t\t switch (op[0]) {\n\t\t case 0: case 1: t = op; break;\n\t\t case 4: _.label++; return { value: op[1], done: false };\n\t\t case 5: _.label++; y = op[1]; op = [0]; continue;\n\t\t case 7: op = _.ops.pop(); _.trys.pop(); continue;\n\t\t default:\n\t\t if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n\t\t if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n\t\t if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n\t\t if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n\t\t if (t[2]) _.ops.pop();\n\t\t _.trys.pop(); continue;\n\t\t }\n\t\t op = body.call(thisArg, _);\n\t\t } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n\t\t if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n\t\t }\n\t\t};\n\t\tObject.defineProperty(exports$1, \"__esModule\", { value: true });\n\t\texports$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;\n\t\tvar Frames_1 = requireFrames();\n\t\texports$1.FLAGS_MASK = 0x3ff; // low 10 bits\n\t\texports$1.FRAME_TYPE_OFFFSET = 10; // frame type is offset 10 bytes within the uint16 containing type + flags\n\t\texports$1.MAX_CODE = 0x7fffffff; // uint31\n\t\texports$1.MAX_KEEPALIVE = 0x7fffffff; // uint31\n\t\texports$1.MAX_LIFETIME = 0x7fffffff; // uint31\n\t\texports$1.MAX_METADATA_LENGTH = 0xffffff; // uint24\n\t\texports$1.MAX_MIME_LENGTH = 0xff; // int8\n\t\texports$1.MAX_REQUEST_COUNT = 0x7fffffff; // uint31\n\t\texports$1.MAX_REQUEST_N = 0x7fffffff; // uint31\n\t\texports$1.MAX_RESUME_LENGTH = 0xffff; // uint16\n\t\texports$1.MAX_STREAM_ID = 0x7fffffff; // uint31\n\t\texports$1.MAX_TTL = 0x7fffffff; // uint31\n\t\texports$1.MAX_VERSION = 0xffff; // uint16\n\t\t/**\n\t\t * Mimimum value that would overflow bitwise operators (2^32).\n\t\t */\n\t\tvar BITWISE_OVERFLOW = 0x100000000;\n\t\t/**\n\t\t * Read a uint24 from a buffer starting at the given offset.\n\t\t */\n\t\tfunction readUInt24BE(buffer, offset) {\n\t\t var val1 = buffer.readUInt8(offset) << 16;\n\t\t var val2 = buffer.readUInt8(offset + 1) << 8;\n\t\t var val3 = buffer.readUInt8(offset + 2);\n\t\t return val1 | val2 | val3;\n\t\t}\n\t\texports$1.readUInt24BE = readUInt24BE;\n\t\t/**\n\t\t * Writes a uint24 to a buffer starting at the given offset, returning the\n\t\t * offset of the next byte.\n\t\t */\n\t\tfunction writeUInt24BE(buffer, value, offset) {\n\t\t offset = buffer.writeUInt8(value >>> 16, offset); // 3rd byte\n\t\t offset = buffer.writeUInt8((value >>> 8) & 0xff, offset); // 2nd byte\n\t\t return buffer.writeUInt8(value & 0xff, offset); // 1st byte\n\t\t}\n\t\texports$1.writeUInt24BE = writeUInt24BE;\n\t\t/**\n\t\t * Read a uint64 (technically supports up to 53 bits per JS number\n\t\t * representation).\n\t\t */\n\t\tfunction readUInt64BE(buffer, offset) {\n\t\t var high = buffer.readUInt32BE(offset);\n\t\t var low = buffer.readUInt32BE(offset + 4);\n\t\t return high * BITWISE_OVERFLOW + low;\n\t\t}\n\t\texports$1.readUInt64BE = readUInt64BE;\n\t\t/**\n\t\t * Write a uint64 (technically supports up to 53 bits per JS number\n\t\t * representation).\n\t\t */\n\t\tfunction writeUInt64BE(buffer, value, offset) {\n\t\t var high = (value / BITWISE_OVERFLOW) | 0;\n\t\t var low = value % BITWISE_OVERFLOW;\n\t\t offset = buffer.writeUInt32BE(high, offset); // first half of uint64\n\t\t return buffer.writeUInt32BE(low, offset); // second half of uint64\n\t\t}\n\t\texports$1.writeUInt64BE = writeUInt64BE;\n\t\t/**\n\t\t * Frame header is:\n\t\t * - stream id (uint32 = 4)\n\t\t * - type + flags (uint 16 = 2)\n\t\t */\n\t\tvar FRAME_HEADER_SIZE = 6;\n\t\t/**\n\t\t * Size of frame length and metadata length fields.\n\t\t */\n\t\tvar UINT24_SIZE = 3;\n\t\t/**\n\t\t * Reads a frame from a buffer that is prefixed with the frame length.\n\t\t */\n\t\tfunction deserializeFrameWithLength(buffer) {\n\t\t var frameLength = readUInt24BE(buffer, 0);\n\t\t return deserializeFrame(buffer.slice(UINT24_SIZE, UINT24_SIZE + frameLength));\n\t\t}\n\t\texports$1.deserializeFrameWithLength = deserializeFrameWithLength;\n\t\t/**\n\t\t * Given a buffer that may contain zero or more length-prefixed frames followed\n\t\t * by zero or more bytes of a (partial) subsequent frame, returns an array of\n\t\t * the frames and an int representing the buffer offset.\n\t\t */\n\t\tfunction deserializeFrames(buffer) {\n\t\t var offset, frameLength, frameStart, frameEnd, frameBuffer, frame;\n\t\t return __generator(this, function (_a) {\n\t\t switch (_a.label) {\n\t\t case 0:\n\t\t offset = 0;\n\t\t _a.label = 1;\n\t\t case 1:\n\t\t if (!(offset + UINT24_SIZE < buffer.length)) return [3 /*break*/, 3];\n\t\t frameLength = readUInt24BE(buffer, offset);\n\t\t frameStart = offset + UINT24_SIZE;\n\t\t frameEnd = frameStart + frameLength;\n\t\t if (frameEnd > buffer.length) {\n\t\t // not all bytes of next frame received\n\t\t return [3 /*break*/, 3];\n\t\t }\n\t\t frameBuffer = buffer.slice(frameStart, frameEnd);\n\t\t frame = deserializeFrame(frameBuffer);\n\t\t offset = frameEnd;\n\t\t return [4 /*yield*/, [frame, offset]];\n\t\t case 2:\n\t\t _a.sent();\n\t\t return [3 /*break*/, 1];\n\t\t case 3: return [2 /*return*/];\n\t\t }\n\t\t });\n\t\t}\n\t\texports$1.deserializeFrames = deserializeFrames;\n\t\t/**\n\t\t * Writes a frame to a buffer with a length prefix.\n\t\t */\n\t\tfunction serializeFrameWithLength(frame) {\n\t\t var buffer = serializeFrame(frame);\n\t\t var lengthPrefixed = bufferExports.Buffer.allocUnsafe(buffer.length + UINT24_SIZE);\n\t\t writeUInt24BE(lengthPrefixed, buffer.length, 0);\n\t\t buffer.copy(lengthPrefixed, UINT24_SIZE);\n\t\t return lengthPrefixed;\n\t\t}\n\t\texports$1.serializeFrameWithLength = serializeFrameWithLength;\n\t\t/**\n\t\t * Read a frame from the buffer.\n\t\t */\n\t\tfunction deserializeFrame(buffer) {\n\t\t var offset = 0;\n\t\t var streamId = buffer.readInt32BE(offset);\n\t\t offset += 4;\n\t\t // invariant(\n\t\t // streamId >= 0,\n\t\t // 'RSocketBinaryFraming: Invalid frame, expected a positive stream id, got `%s.',\n\t\t // streamId,\n\t\t // );\n\t\t var typeAndFlags = buffer.readUInt16BE(offset);\n\t\t offset += 2;\n\t\t var type = typeAndFlags >>> exports$1.FRAME_TYPE_OFFFSET; // keep highest 6 bits\n\t\t var flags = typeAndFlags & exports$1.FLAGS_MASK; // keep lowest 10 bits\n\t\t switch (type) {\n\t\t case Frames_1.FrameTypes.SETUP:\n\t\t return deserializeSetupFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.PAYLOAD:\n\t\t return deserializePayloadFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.ERROR:\n\t\t return deserializeErrorFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.KEEPALIVE:\n\t\t return deserializeKeepAliveFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.REQUEST_FNF:\n\t\t return deserializeRequestFnfFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.REQUEST_RESPONSE:\n\t\t return deserializeRequestResponseFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.REQUEST_STREAM:\n\t\t return deserializeRequestStreamFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.REQUEST_CHANNEL:\n\t\t return deserializeRequestChannelFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.METADATA_PUSH:\n\t\t return deserializeMetadataPushFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.REQUEST_N:\n\t\t return deserializeRequestNFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.RESUME:\n\t\t return deserializeResumeFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.RESUME_OK:\n\t\t return deserializeResumeOkFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.CANCEL:\n\t\t return deserializeCancelFrame(buffer, streamId, flags);\n\t\t case Frames_1.FrameTypes.LEASE:\n\t\t return deserializeLeaseFrame(buffer, streamId, flags);\n\t\t // invariant(\n\t\t // false,\n\t\t // \"RSocketBinaryFraming: Unsupported frame type `%s`.\",\n\t\t // getFrameTypeName(type)\n\t\t // );\n\t\t }\n\t\t}\n\t\texports$1.deserializeFrame = deserializeFrame;\n\t\t/**\n\t\t * Convert the frame to a (binary) buffer.\n\t\t */\n\t\tfunction serializeFrame(frame) {\n\t\t switch (frame.type) {\n\t\t case Frames_1.FrameTypes.SETUP:\n\t\t return serializeSetupFrame(frame);\n\t\t case Frames_1.FrameTypes.PAYLOAD:\n\t\t return serializePayloadFrame(frame);\n\t\t case Frames_1.FrameTypes.ERROR:\n\t\t return serializeErrorFrame(frame);\n\t\t case Frames_1.FrameTypes.KEEPALIVE:\n\t\t return serializeKeepAliveFrame(frame);\n\t\t case Frames_1.FrameTypes.REQUEST_FNF:\n\t\t case Frames_1.FrameTypes.REQUEST_RESPONSE:\n\t\t return serializeRequestFrame(frame);\n\t\t case Frames_1.FrameTypes.REQUEST_STREAM:\n\t\t case Frames_1.FrameTypes.REQUEST_CHANNEL:\n\t\t return serializeRequestManyFrame(frame);\n\t\t case Frames_1.FrameTypes.METADATA_PUSH:\n\t\t return serializeMetadataPushFrame(frame);\n\t\t case Frames_1.FrameTypes.REQUEST_N:\n\t\t return serializeRequestNFrame(frame);\n\t\t case Frames_1.FrameTypes.RESUME:\n\t\t return serializeResumeFrame(frame);\n\t\t case Frames_1.FrameTypes.RESUME_OK:\n\t\t return serializeResumeOkFrame(frame);\n\t\t case Frames_1.FrameTypes.CANCEL:\n\t\t return serializeCancelFrame(frame);\n\t\t case Frames_1.FrameTypes.LEASE:\n\t\t return serializeLeaseFrame(frame);\n\t\t // invariant(\n\t\t // false,\n\t\t // \"RSocketBinaryFraming: Unsupported frame type `%s`.\",\n\t\t // getFrameTypeName(frame.type)\n\t\t // );\n\t\t }\n\t\t}\n\t\texports$1.serializeFrame = serializeFrame;\n\t\t/**\n\t\t * Byte size of frame without size prefix\n\t\t */\n\t\tfunction sizeOfFrame(frame) {\n\t\t switch (frame.type) {\n\t\t case Frames_1.FrameTypes.SETUP:\n\t\t return sizeOfSetupFrame(frame);\n\t\t case Frames_1.FrameTypes.PAYLOAD:\n\t\t return sizeOfPayloadFrame(frame);\n\t\t case Frames_1.FrameTypes.ERROR:\n\t\t return sizeOfErrorFrame(frame);\n\t\t case Frames_1.FrameTypes.KEEPALIVE:\n\t\t return sizeOfKeepAliveFrame(frame);\n\t\t case Frames_1.FrameTypes.REQUEST_FNF:\n\t\t case Frames_1.FrameTypes.REQUEST_RESPONSE:\n\t\t return sizeOfRequestFrame(frame);\n\t\t case Frames_1.FrameTypes.REQUEST_STREAM:\n\t\t case Frames_1.FrameTypes.REQUEST_CHANNEL:\n\t\t return sizeOfRequestManyFrame(frame);\n\t\t case Frames_1.FrameTypes.METADATA_PUSH:\n\t\t return sizeOfMetadataPushFrame(frame);\n\t\t case Frames_1.FrameTypes.REQUEST_N:\n\t\t return sizeOfRequestNFrame();\n\t\t case Frames_1.FrameTypes.RESUME:\n\t\t return sizeOfResumeFrame(frame);\n\t\t case Frames_1.FrameTypes.RESUME_OK:\n\t\t return sizeOfResumeOkFrame();\n\t\t case Frames_1.FrameTypes.CANCEL:\n\t\t return sizeOfCancelFrame();\n\t\t case Frames_1.FrameTypes.LEASE:\n\t\t return sizeOfLeaseFrame(frame);\n\t\t // invariant(\n\t\t // false,\n\t\t // \"RSocketBinaryFraming: Unsupported frame type `%s`.\",\n\t\t // getFrameTypeName(frame.type)\n\t\t // );\n\t\t }\n\t\t}\n\t\texports$1.sizeOfFrame = sizeOfFrame;\n\t\t/**\n\t\t * Writes a SETUP frame into a new buffer and returns it.\n\t\t *\n\t\t * Prefix size is:\n\t\t * - version (2x uint16 = 4)\n\t\t * - keepalive (uint32 = 4)\n\t\t * - lifetime (uint32 = 4)\n\t\t * - mime lengths (2x uint8 = 2)\n\t\t */\n\t\tvar SETUP_FIXED_SIZE = 14;\n\t\tvar RESUME_TOKEN_LENGTH_SIZE = 2;\n\t\tfunction serializeSetupFrame(frame) {\n\t\t var resumeTokenLength = frame.resumeToken != null ? frame.resumeToken.byteLength : 0;\n\t\t var metadataMimeTypeLength = frame.metadataMimeType != null\n\t\t ? bufferExports.Buffer.byteLength(frame.metadataMimeType, \"ascii\")\n\t\t : 0;\n\t\t var dataMimeTypeLength = frame.dataMimeType != null\n\t\t ? bufferExports.Buffer.byteLength(frame.dataMimeType, \"ascii\")\n\t\t : 0;\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE +\n\t\t SETUP_FIXED_SIZE + //\n\t\t (resumeTokenLength ? RESUME_TOKEN_LENGTH_SIZE + resumeTokenLength : 0) +\n\t\t metadataMimeTypeLength +\n\t\t dataMimeTypeLength +\n\t\t payloadLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t offset = buffer.writeUInt16BE(frame.majorVersion, offset);\n\t\t offset = buffer.writeUInt16BE(frame.minorVersion, offset);\n\t\t offset = buffer.writeUInt32BE(frame.keepAlive, offset);\n\t\t offset = buffer.writeUInt32BE(frame.lifetime, offset);\n\t\t if (frame.flags & Frames_1.Flags.RESUME_ENABLE) {\n\t\t offset = buffer.writeUInt16BE(resumeTokenLength, offset);\n\t\t if (frame.resumeToken != null) {\n\t\t offset += frame.resumeToken.copy(buffer, offset);\n\t\t }\n\t\t }\n\t\t offset = buffer.writeUInt8(metadataMimeTypeLength, offset);\n\t\t if (frame.metadataMimeType != null) {\n\t\t offset += buffer.write(frame.metadataMimeType, offset, offset + metadataMimeTypeLength, \"ascii\");\n\t\t }\n\t\t offset = buffer.writeUInt8(dataMimeTypeLength, offset);\n\t\t if (frame.dataMimeType != null) {\n\t\t offset += buffer.write(frame.dataMimeType, offset, offset + dataMimeTypeLength, \"ascii\");\n\t\t }\n\t\t writePayload(frame, buffer, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfSetupFrame(frame) {\n\t\t var resumeTokenLength = frame.resumeToken != null ? frame.resumeToken.byteLength : 0;\n\t\t var metadataMimeTypeLength = frame.metadataMimeType != null\n\t\t ? bufferExports.Buffer.byteLength(frame.metadataMimeType, \"ascii\")\n\t\t : 0;\n\t\t var dataMimeTypeLength = frame.dataMimeType != null\n\t\t ? bufferExports.Buffer.byteLength(frame.dataMimeType, \"ascii\")\n\t\t : 0;\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t return (FRAME_HEADER_SIZE +\n\t\t SETUP_FIXED_SIZE + //\n\t\t (resumeTokenLength ? RESUME_TOKEN_LENGTH_SIZE + resumeTokenLength : 0) +\n\t\t metadataMimeTypeLength +\n\t\t dataMimeTypeLength +\n\t\t payloadLength);\n\t\t}\n\t\t/**\n\t\t * Reads a SETUP frame from the buffer and returns it.\n\t\t */\n\t\tfunction deserializeSetupFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId === 0,\n\t\t // 'RSocketBinaryFraming: Invalid SETUP frame, expected stream id to be 0.',\n\t\t // );\n\t\t buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var majorVersion = buffer.readUInt16BE(offset);\n\t\t offset += 2;\n\t\t var minorVersion = buffer.readUInt16BE(offset);\n\t\t offset += 2;\n\t\t var keepAlive = buffer.readInt32BE(offset);\n\t\t offset += 4;\n\t\t // invariant(\n\t\t // keepAlive >= 0 && keepAlive <= MAX_KEEPALIVE,\n\t\t // 'RSocketBinaryFraming: Invalid SETUP frame, expected keepAlive to be ' +\n\t\t // '>= 0 and <= %s. Got `%s`.',\n\t\t // MAX_KEEPALIVE,\n\t\t // keepAlive,\n\t\t // );\n\t\t var lifetime = buffer.readInt32BE(offset);\n\t\t offset += 4;\n\t\t // invariant(\n\t\t // lifetime >= 0 && lifetime <= MAX_LIFETIME,\n\t\t // 'RSocketBinaryFraming: Invalid SETUP frame, expected lifetime to be ' +\n\t\t // '>= 0 and <= %s. Got `%s`.',\n\t\t // MAX_LIFETIME,\n\t\t // lifetime,\n\t\t // );\n\t\t var resumeToken = null;\n\t\t if (flags & Frames_1.Flags.RESUME_ENABLE) {\n\t\t var resumeTokenLength = buffer.readInt16BE(offset);\n\t\t offset += 2;\n\t\t // invariant(\n\t\t // resumeTokenLength >= 0 && resumeTokenLength <= MAX_RESUME_LENGTH,\n\t\t // 'RSocketBinaryFraming: Invalid SETUP frame, expected resumeToken length ' +\n\t\t // 'to be >= 0 and <= %s. Got `%s`.',\n\t\t // MAX_RESUME_LENGTH,\n\t\t // resumeTokenLength,\n\t\t // );\n\t\t resumeToken = buffer.slice(offset, offset + resumeTokenLength);\n\t\t offset += resumeTokenLength;\n\t\t }\n\t\t var metadataMimeTypeLength = buffer.readUInt8(offset);\n\t\t offset += 1;\n\t\t var metadataMimeType = buffer.toString(\"ascii\", offset, offset + metadataMimeTypeLength);\n\t\t offset += metadataMimeTypeLength;\n\t\t var dataMimeTypeLength = buffer.readUInt8(offset);\n\t\t offset += 1;\n\t\t var dataMimeType = buffer.toString(\"ascii\", offset, offset + dataMimeTypeLength);\n\t\t offset += dataMimeTypeLength;\n\t\t var frame = {\n\t\t data: null,\n\t\t dataMimeType: dataMimeType,\n\t\t flags: flags,\n\t\t keepAlive: keepAlive,\n\t\t lifetime: lifetime,\n\t\t majorVersion: majorVersion,\n\t\t metadata: null,\n\t\t metadataMimeType: metadataMimeType,\n\t\t minorVersion: minorVersion,\n\t\t resumeToken: resumeToken,\n\t\t // streamId,\n\t\t streamId: 0,\n\t\t type: Frames_1.FrameTypes.SETUP,\n\t\t };\n\t\t readPayload(buffer, frame, offset);\n\t\t return frame;\n\t\t}\n\t\t/**\n\t\t * Writes an ERROR frame into a new buffer and returns it.\n\t\t *\n\t\t * Prefix size is for the error code (uint32 = 4).\n\t\t */\n\t\tvar ERROR_FIXED_SIZE = 4;\n\t\tfunction serializeErrorFrame(frame) {\n\t\t var messageLength = frame.message != null ? bufferExports.Buffer.byteLength(frame.message, \"utf8\") : 0;\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + ERROR_FIXED_SIZE + messageLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t offset = buffer.writeUInt32BE(frame.code, offset);\n\t\t if (frame.message != null) {\n\t\t buffer.write(frame.message, offset, offset + messageLength, \"utf8\");\n\t\t }\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfErrorFrame(frame) {\n\t\t var messageLength = frame.message != null ? bufferExports.Buffer.byteLength(frame.message, \"utf8\") : 0;\n\t\t return FRAME_HEADER_SIZE + ERROR_FIXED_SIZE + messageLength;\n\t\t}\n\t\t/**\n\t\t * Reads an ERROR frame from the buffer and returns it.\n\t\t */\n\t\tfunction deserializeErrorFrame(buffer, streamId, flags) {\n\t\t buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var code = buffer.readInt32BE(offset);\n\t\t offset += 4;\n\t\t // invariant(\n\t\t // code >= 0 && code <= MAX_CODE,\n\t\t // \"RSocketBinaryFraming: Invalid ERROR frame, expected code to be >= 0 and <= %s. Got `%s`.\",\n\t\t // MAX_CODE,\n\t\t // code\n\t\t // );\n\t\t var messageLength = buffer.length - offset;\n\t\t var message = \"\";\n\t\t if (messageLength > 0) {\n\t\t message = buffer.toString(\"utf8\", offset, offset + messageLength);\n\t\t offset += messageLength;\n\t\t }\n\t\t return {\n\t\t code: code,\n\t\t flags: flags,\n\t\t message: message,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.ERROR,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a KEEPALIVE frame into a new buffer and returns it.\n\t\t *\n\t\t * Prefix size is for the last received position (uint64 = 8).\n\t\t */\n\t\tvar KEEPALIVE_FIXED_SIZE = 8;\n\t\tfunction serializeKeepAliveFrame(frame) {\n\t\t var dataLength = frame.data != null ? frame.data.byteLength : 0;\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + KEEPALIVE_FIXED_SIZE + dataLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t offset = writeUInt64BE(buffer, frame.lastReceivedPosition, offset);\n\t\t if (frame.data != null) {\n\t\t frame.data.copy(buffer, offset);\n\t\t }\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfKeepAliveFrame(frame) {\n\t\t var dataLength = frame.data != null ? frame.data.byteLength : 0;\n\t\t return FRAME_HEADER_SIZE + KEEPALIVE_FIXED_SIZE + dataLength;\n\t\t}\n\t\t/**\n\t\t * Reads a KEEPALIVE frame from the buffer and returns it.\n\t\t */\n\t\tfunction deserializeKeepAliveFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId === 0,\n\t\t // \"RSocketBinaryFraming: Invalid KEEPALIVE frame, expected stream id to be 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var lastReceivedPosition = readUInt64BE(buffer, offset);\n\t\t offset += 8;\n\t\t var data = null;\n\t\t if (offset < buffer.length) {\n\t\t data = buffer.slice(offset, buffer.length);\n\t\t }\n\t\t return {\n\t\t data: data,\n\t\t flags: flags,\n\t\t lastReceivedPosition: lastReceivedPosition,\n\t\t // streamId,\n\t\t streamId: 0,\n\t\t type: Frames_1.FrameTypes.KEEPALIVE,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a LEASE frame into a new buffer and returns it.\n\t\t *\n\t\t * Prefix size is for the ttl (uint32) and requestcount (uint32).\n\t\t */\n\t\tvar LEASE_FIXED_SIZE = 8;\n\t\tfunction serializeLeaseFrame(frame) {\n\t\t var metaLength = frame.metadata != null ? frame.metadata.byteLength : 0;\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + LEASE_FIXED_SIZE + metaLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t offset = buffer.writeUInt32BE(frame.ttl, offset);\n\t\t offset = buffer.writeUInt32BE(frame.requestCount, offset);\n\t\t if (frame.metadata != null) {\n\t\t frame.metadata.copy(buffer, offset);\n\t\t }\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfLeaseFrame(frame) {\n\t\t var metaLength = frame.metadata != null ? frame.metadata.byteLength : 0;\n\t\t return FRAME_HEADER_SIZE + LEASE_FIXED_SIZE + metaLength;\n\t\t}\n\t\t/**\n\t\t * Reads a LEASE frame from the buffer and returns it.\n\t\t */\n\t\tfunction deserializeLeaseFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId === 0,\n\t\t // \"RSocketBinaryFraming: Invalid LEASE frame, expected stream id to be 0.\"\n\t\t // );\n\t\t // const length = buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var ttl = buffer.readUInt32BE(offset);\n\t\t offset += 4;\n\t\t var requestCount = buffer.readUInt32BE(offset);\n\t\t offset += 4;\n\t\t var metadata = null;\n\t\t if (offset < buffer.length) {\n\t\t metadata = buffer.slice(offset, buffer.length);\n\t\t }\n\t\t return {\n\t\t flags: flags,\n\t\t metadata: metadata,\n\t\t requestCount: requestCount,\n\t\t // streamId,\n\t\t streamId: 0,\n\t\t ttl: ttl,\n\t\t type: Frames_1.FrameTypes.LEASE,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a REQUEST_FNF or REQUEST_RESPONSE frame to a new buffer and returns\n\t\t * it.\n\t\t *\n\t\t * Note that these frames have the same shape and only differ in their type.\n\t\t */\n\t\tfunction serializeRequestFrame(frame) {\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + payloadLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t writePayload(frame, buffer, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfRequestFrame(frame) {\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t return FRAME_HEADER_SIZE + payloadLength;\n\t\t}\n\t\t/**\n\t\t * Writes a METADATA_PUSH frame to a new buffer and returns\n\t\t * it.\n\t\t */\n\t\tfunction serializeMetadataPushFrame(frame) {\n\t\t var metadata = frame.metadata;\n\t\t if (metadata != null) {\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + metadata.byteLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t metadata.copy(buffer, offset);\n\t\t return buffer;\n\t\t }\n\t\t else {\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE);\n\t\t writeHeader(frame, buffer);\n\t\t return buffer;\n\t\t }\n\t\t}\n\t\tfunction sizeOfMetadataPushFrame(frame) {\n\t\t return (FRAME_HEADER_SIZE + (frame.metadata != null ? frame.metadata.byteLength : 0));\n\t\t}\n\t\tfunction deserializeRequestFnfFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_FNF frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var frame = {\n\t\t data: null,\n\t\t flags: flags,\n\t\t // length,\n\t\t metadata: null,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.REQUEST_FNF,\n\t\t };\n\t\t readPayload(buffer, frame, FRAME_HEADER_SIZE);\n\t\t return frame;\n\t\t}\n\t\tfunction deserializeRequestResponseFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_RESPONSE frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t // const length = buffer.length;\n\t\t var frame = {\n\t\t data: null,\n\t\t flags: flags,\n\t\t // length,\n\t\t metadata: null,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.REQUEST_RESPONSE,\n\t\t };\n\t\t readPayload(buffer, frame, FRAME_HEADER_SIZE);\n\t\t return frame;\n\t\t}\n\t\tfunction deserializeMetadataPushFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId === 0,\n\t\t // \"RSocketBinaryFraming: Invalid METADATA_PUSH frame, expected stream id to be 0.\"\n\t\t // );\n\t\t // const length = buffer.length;\n\t\t return {\n\t\t flags: flags,\n\t\t // length,\n\t\t metadata: length === FRAME_HEADER_SIZE\n\t\t ? null\n\t\t : buffer.slice(FRAME_HEADER_SIZE, length),\n\t\t // streamId,\n\t\t streamId: 0,\n\t\t type: Frames_1.FrameTypes.METADATA_PUSH,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a REQUEST_STREAM or REQUEST_CHANNEL frame to a new buffer and returns\n\t\t * it.\n\t\t *\n\t\t * Note that these frames have the same shape and only differ in their type.\n\t\t *\n\t\t * Prefix size is for requestN (uint32 = 4).\n\t\t */\n\t\tvar REQUEST_MANY_HEADER = 4;\n\t\tfunction serializeRequestManyFrame(frame) {\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + REQUEST_MANY_HEADER + payloadLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t offset = buffer.writeUInt32BE(frame.requestN, offset);\n\t\t writePayload(frame, buffer, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfRequestManyFrame(frame) {\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t return FRAME_HEADER_SIZE + REQUEST_MANY_HEADER + payloadLength;\n\t\t}\n\t\tfunction deserializeRequestStreamFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_STREAM frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var requestN = buffer.readInt32BE(offset);\n\t\t offset += 4;\n\t\t // invariant(\n\t\t // requestN > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_STREAM frame, expected requestN to be > 0, got `%s`.\",\n\t\t // requestN\n\t\t // );\n\t\t var frame = {\n\t\t data: null,\n\t\t flags: flags,\n\t\t // length,\n\t\t metadata: null,\n\t\t requestN: requestN,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.REQUEST_STREAM,\n\t\t };\n\t\t readPayload(buffer, frame, offset);\n\t\t return frame;\n\t\t}\n\t\tfunction deserializeRequestChannelFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_CHANNEL frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var requestN = buffer.readInt32BE(offset);\n\t\t offset += 4;\n\t\t // invariant(\n\t\t // requestN > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_STREAM frame, expected requestN to be > 0, got `%s`.\",\n\t\t // requestN\n\t\t // );\n\t\t var frame = {\n\t\t data: null,\n\t\t flags: flags,\n\t\t // length,\n\t\t metadata: null,\n\t\t requestN: requestN,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.REQUEST_CHANNEL,\n\t\t };\n\t\t readPayload(buffer, frame, offset);\n\t\t return frame;\n\t\t}\n\t\t/**\n\t\t * Writes a REQUEST_N frame to a new buffer and returns it.\n\t\t *\n\t\t * Prefix size is for requestN (uint32 = 4).\n\t\t */\n\t\tvar REQUEST_N_HEADER = 4;\n\t\tfunction serializeRequestNFrame(frame) {\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + REQUEST_N_HEADER);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t buffer.writeUInt32BE(frame.requestN, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfRequestNFrame(frame) {\n\t\t return FRAME_HEADER_SIZE + REQUEST_N_HEADER;\n\t\t}\n\t\tfunction deserializeRequestNFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_N frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var requestN = buffer.readInt32BE(FRAME_HEADER_SIZE);\n\t\t // invariant(\n\t\t // requestN > 0,\n\t\t // \"RSocketBinaryFraming: Invalid REQUEST_STREAM frame, expected requestN to be > 0, got `%s`.\",\n\t\t // requestN\n\t\t // );\n\t\t return {\n\t\t flags: flags,\n\t\t // length,\n\t\t requestN: requestN,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.REQUEST_N,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a CANCEL frame to a new buffer and returns it.\n\t\t */\n\t\tfunction serializeCancelFrame(frame) {\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE);\n\t\t writeHeader(frame, buffer);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfCancelFrame(frame) {\n\t\t return FRAME_HEADER_SIZE;\n\t\t}\n\t\tfunction deserializeCancelFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid CANCEL frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t return {\n\t\t flags: flags,\n\t\t // length,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.CANCEL,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a PAYLOAD frame to a new buffer and returns it.\n\t\t */\n\t\tfunction serializePayloadFrame(frame) {\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + payloadLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t writePayload(frame, buffer, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfPayloadFrame(frame) {\n\t\t var payloadLength = getPayloadLength(frame);\n\t\t return FRAME_HEADER_SIZE + payloadLength;\n\t\t}\n\t\tfunction deserializePayloadFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId > 0,\n\t\t // \"RSocketBinaryFraming: Invalid PAYLOAD frame, expected stream id to be > 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var frame = {\n\t\t data: null,\n\t\t flags: flags,\n\t\t // length,\n\t\t metadata: null,\n\t\t streamId: streamId,\n\t\t type: Frames_1.FrameTypes.PAYLOAD,\n\t\t };\n\t\t readPayload(buffer, frame, FRAME_HEADER_SIZE);\n\t\t return frame;\n\t\t}\n\t\t/**\n\t\t * Writes a RESUME frame into a new buffer and returns it.\n\t\t *\n\t\t * Fixed size is:\n\t\t * - major version (uint16 = 2)\n\t\t * - minor version (uint16 = 2)\n\t\t * - token length (uint16 = 2)\n\t\t * - client position (uint64 = 8)\n\t\t * - server position (uint64 = 8)\n\t\t */\n\t\tvar RESUME_FIXED_SIZE = 22;\n\t\tfunction serializeResumeFrame(frame) {\n\t\t var resumeTokenLength = frame.resumeToken.byteLength;\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + RESUME_FIXED_SIZE + resumeTokenLength);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t offset = buffer.writeUInt16BE(frame.majorVersion, offset);\n\t\t offset = buffer.writeUInt16BE(frame.minorVersion, offset);\n\t\t offset = buffer.writeUInt16BE(resumeTokenLength, offset);\n\t\t offset += frame.resumeToken.copy(buffer, offset);\n\t\t offset = writeUInt64BE(buffer, frame.serverPosition, offset);\n\t\t writeUInt64BE(buffer, frame.clientPosition, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfResumeFrame(frame) {\n\t\t var resumeTokenLength = frame.resumeToken.byteLength;\n\t\t return FRAME_HEADER_SIZE + RESUME_FIXED_SIZE + resumeTokenLength;\n\t\t}\n\t\tfunction deserializeResumeFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId === 0,\n\t\t // \"RSocketBinaryFraming: Invalid RESUME frame, expected stream id to be 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var offset = FRAME_HEADER_SIZE;\n\t\t var majorVersion = buffer.readUInt16BE(offset);\n\t\t offset += 2;\n\t\t var minorVersion = buffer.readUInt16BE(offset);\n\t\t offset += 2;\n\t\t var resumeTokenLength = buffer.readInt16BE(offset);\n\t\t offset += 2;\n\t\t // invariant(\n\t\t // resumeTokenLength >= 0 && resumeTokenLength <= MAX_RESUME_LENGTH,\n\t\t // \"RSocketBinaryFraming: Invalid SETUP frame, expected resumeToken length \" +\n\t\t // \"to be >= 0 and <= %s. Got `%s`.\",\n\t\t // MAX_RESUME_LENGTH,\n\t\t // resumeTokenLength\n\t\t // );\n\t\t var resumeToken = buffer.slice(offset, offset + resumeTokenLength);\n\t\t offset += resumeTokenLength;\n\t\t var serverPosition = readUInt64BE(buffer, offset);\n\t\t offset += 8;\n\t\t var clientPosition = readUInt64BE(buffer, offset);\n\t\t offset += 8;\n\t\t return {\n\t\t clientPosition: clientPosition,\n\t\t flags: flags,\n\t\t // length,\n\t\t majorVersion: majorVersion,\n\t\t minorVersion: minorVersion,\n\t\t resumeToken: resumeToken,\n\t\t serverPosition: serverPosition,\n\t\t // streamId,\n\t\t streamId: 0,\n\t\t type: Frames_1.FrameTypes.RESUME,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Writes a RESUME_OK frame into a new buffer and returns it.\n\t\t *\n\t\t * Fixed size is:\n\t\t * - client position (uint64 = 8)\n\t\t */\n\t\tvar RESUME_OK_FIXED_SIZE = 8;\n\t\tfunction serializeResumeOkFrame(frame) {\n\t\t var buffer = bufferExports.Buffer.allocUnsafe(FRAME_HEADER_SIZE + RESUME_OK_FIXED_SIZE);\n\t\t var offset = writeHeader(frame, buffer);\n\t\t writeUInt64BE(buffer, frame.clientPosition, offset);\n\t\t return buffer;\n\t\t}\n\t\tfunction sizeOfResumeOkFrame(frame) {\n\t\t return FRAME_HEADER_SIZE + RESUME_OK_FIXED_SIZE;\n\t\t}\n\t\tfunction deserializeResumeOkFrame(buffer, streamId, flags) {\n\t\t // invariant(\n\t\t // streamId === 0,\n\t\t // \"RSocketBinaryFraming: Invalid RESUME frame, expected stream id to be 0.\"\n\t\t // );\n\t\t buffer.length;\n\t\t var clientPosition = readUInt64BE(buffer, FRAME_HEADER_SIZE);\n\t\t return {\n\t\t clientPosition: clientPosition,\n\t\t flags: flags,\n\t\t // length,\n\t\t // streamId,\n\t\t streamId: 0,\n\t\t type: Frames_1.FrameTypes.RESUME_OK,\n\t\t };\n\t\t}\n\t\t/**\n\t\t * Write the header of the frame into the buffer.\n\t\t */\n\t\tfunction writeHeader(frame, buffer) {\n\t\t var offset = buffer.writeInt32BE(frame.streamId, 0);\n\t\t // shift frame to high 6 bits, extract lowest 10 bits from flags\n\t\t return buffer.writeUInt16BE((frame.type << exports$1.FRAME_TYPE_OFFFSET) | (frame.flags & exports$1.FLAGS_MASK), offset);\n\t\t}\n\t\t/**\n\t\t * Determine the length of the payload section of a frame. Only applies to\n\t\t * frame types that MAY have both metadata and data.\n\t\t */\n\t\tfunction getPayloadLength(frame) {\n\t\t var payloadLength = 0;\n\t\t if (frame.data != null) {\n\t\t payloadLength += frame.data.byteLength;\n\t\t }\n\t\t if (Frames_1.Flags.hasMetadata(frame.flags)) {\n\t\t payloadLength += UINT24_SIZE;\n\t\t if (frame.metadata != null) {\n\t\t payloadLength += frame.metadata.byteLength;\n\t\t }\n\t\t }\n\t\t return payloadLength;\n\t\t}\n\t\t/**\n\t\t * Write the payload of a frame into the given buffer. Only applies to frame\n\t\t * types that MAY have both metadata and data.\n\t\t */\n\t\tfunction writePayload(frame, buffer, offset) {\n\t\t if (Frames_1.Flags.hasMetadata(frame.flags)) {\n\t\t if (frame.metadata != null) {\n\t\t var metaLength = frame.metadata.byteLength;\n\t\t offset = writeUInt24BE(buffer, metaLength, offset);\n\t\t offset += frame.metadata.copy(buffer, offset);\n\t\t }\n\t\t else {\n\t\t offset = writeUInt24BE(buffer, 0, offset);\n\t\t }\n\t\t }\n\t\t if (frame.data != null) {\n\t\t frame.data.copy(buffer, offset);\n\t\t }\n\t\t}\n\t\t/**\n\t\t * Read the payload from a buffer and write it into the frame. Only applies to\n\t\t * frame types that MAY have both metadata and data.\n\t\t */\n\t\tfunction readPayload(buffer, frame, offset) {\n\t\t if (Frames_1.Flags.hasMetadata(frame.flags)) {\n\t\t var metaLength = readUInt24BE(buffer, offset);\n\t\t offset += UINT24_SIZE;\n\t\t if (metaLength > 0) {\n\t\t frame.metadata = buffer.slice(offset, offset + metaLength);\n\t\t offset += metaLength;\n\t\t }\n\t\t }\n\t\t if (offset < buffer.length) {\n\t\t frame.data = buffer.slice(offset, buffer.length);\n\t\t }\n\t\t}\n\t\t// exported as class to facilitate testing\n\t\tvar Deserializer = /** @class */ (function () {\n\t\t function Deserializer() {\n\t\t }\n\t\t /**\n\t\t * Read a frame from the buffer.\n\t\t */\n\t\t Deserializer.prototype.deserializeFrame = function (buffer) {\n\t\t return deserializeFrame(buffer);\n\t\t };\n\t\t /**\n\t\t * Reads a frame from a buffer that is prefixed with the frame length.\n\t\t */\n\t\t Deserializer.prototype.deserializeFrameWithLength = function (buffer) {\n\t\t return deserializeFrameWithLength(buffer);\n\t\t };\n\t\t /**\n\t\t * Given a buffer that may contain zero or more length-prefixed frames followed\n\t\t * by zero or more bytes of a (partial) subsequent frame, returns an array of\n\t\t * the frames and a int representing the buffer offset.\n\t\t */\n\t\t Deserializer.prototype.deserializeFrames = function (buffer) {\n\t\t return deserializeFrames(buffer);\n\t\t };\n\t\t return Deserializer;\n\t\t}());\n\t\texports$1.Deserializer = Deserializer;\n\t\t\n\t} (Codecs));\n\treturn Codecs;\n}\n\nvar Common = {};\n\nvar hasRequiredCommon;\n\nfunction requireCommon () {\n\tif (hasRequiredCommon) return Common;\n\thasRequiredCommon = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tObject.defineProperty(Common, \"__esModule\", { value: true });\n\t\n\treturn Common;\n}\n\nvar Deferred = {};\n\nvar hasRequiredDeferred;\n\nfunction requireDeferred () {\n\tif (hasRequiredDeferred) return Deferred;\n\thasRequiredDeferred = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __values = (Deferred && Deferred.__values) || function(o) {\n\t var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n\t if (m) return m.call(o);\n\t if (o && typeof o.length === \"number\") return {\n\t next: function () {\n\t if (o && i >= o.length) o = void 0;\n\t return { value: o && o[i++], done: !o };\n\t }\n\t };\n\t throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n\t};\n\tObject.defineProperty(Deferred, \"__esModule\", { value: true });\n\tDeferred.Deferred = void 0;\n\tvar Deferred$1 = /** @class */ (function () {\n\t function Deferred() {\n\t this._done = false;\n\t this.onCloseCallbacks = [];\n\t }\n\t Object.defineProperty(Deferred.prototype, \"done\", {\n\t get: function () {\n\t return this._done;\n\t },\n\t enumerable: false,\n\t configurable: true\n\t });\n\t /**\n\t * Signals to an observer that the Deferred operation has been closed, which invokes\n\t * the provided `onClose` callback.\n\t */\n\t Deferred.prototype.close = function (error) {\n\t var e_1, _a, e_2, _b;\n\t if (this.done) {\n\t console.warn(\"Trying to close for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t this._done = true;\n\t this._error = error;\n\t if (error) {\n\t try {\n\t for (var _c = __values(this.onCloseCallbacks), _d = _c.next(); !_d.done; _d = _c.next()) {\n\t var callback = _d.value;\n\t callback(error);\n\t }\n\t }\n\t catch (e_1_1) { e_1 = { error: e_1_1 }; }\n\t finally {\n\t try {\n\t if (_d && !_d.done && (_a = _c.return)) _a.call(_c);\n\t }\n\t finally { if (e_1) throw e_1.error; }\n\t }\n\t return;\n\t }\n\t try {\n\t for (var _e = __values(this.onCloseCallbacks), _f = _e.next(); !_f.done; _f = _e.next()) {\n\t var callback = _f.value;\n\t callback();\n\t }\n\t }\n\t catch (e_2_1) { e_2 = { error: e_2_1 }; }\n\t finally {\n\t try {\n\t if (_f && !_f.done && (_b = _e.return)) _b.call(_e);\n\t }\n\t finally { if (e_2) throw e_2.error; }\n\t }\n\t };\n\t /**\n\t * Registers a callback to be called when the Closeable is closed. optionally with an Error.\n\t */\n\t Deferred.prototype.onClose = function (callback) {\n\t if (this._done) {\n\t callback(this._error);\n\t return;\n\t }\n\t this.onCloseCallbacks.push(callback);\n\t };\n\t return Deferred;\n\t}());\n\tDeferred.Deferred = Deferred$1;\n\t\n\treturn Deferred;\n}\n\nvar Errors = {};\n\nvar hasRequiredErrors;\n\nfunction requireErrors () {\n\tif (hasRequiredErrors) return Errors;\n\thasRequiredErrors = 1;\n\t(function (exports$1) {\n\t\t/*\n\t\t * Copyright 2021-2022 the original author or authors.\n\t\t *\n\t\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t\t * you may not use this file except in compliance with the License.\n\t\t * You may obtain a copy of the License at\n\t\t *\n\t\t * http://www.apache.org/licenses/LICENSE-2.0\n\t\t *\n\t\t * Unless required by applicable law or agreed to in writing, software\n\t\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t\t * See the License for the specific language governing permissions and\n\t\t * limitations under the License.\n\t\t */\n\t\tvar __extends = (Errors && Errors.__extends) || (function () {\n\t\t var extendStatics = function (d, b) {\n\t\t extendStatics = Object.setPrototypeOf ||\n\t\t ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n\t\t function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n\t\t return extendStatics(d, b);\n\t\t };\n\t\t return function (d, b) {\n\t\t if (typeof b !== \"function\" && b !== null)\n\t\t throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n\t\t extendStatics(d, b);\n\t\t function __() { this.constructor = d; }\n\t\t d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n\t\t };\n\t\t})();\n\t\tObject.defineProperty(exports$1, \"__esModule\", { value: true });\n\t\texports$1.ErrorCodes = exports$1.RSocketError = void 0;\n\t\tvar RSocketError = /** @class */ (function (_super) {\n\t\t __extends(RSocketError, _super);\n\t\t function RSocketError(code, message) {\n\t\t var _this = _super.call(this, message) || this;\n\t\t _this.code = code;\n\t\t return _this;\n\t\t }\n\t\t return RSocketError;\n\t\t}(Error));\n\t\texports$1.RSocketError = RSocketError;\n\t\t(function (ErrorCodes) {\n\t\t ErrorCodes[ErrorCodes[\"RESERVED\"] = 0] = \"RESERVED\";\n\t\t ErrorCodes[ErrorCodes[\"INVALID_SETUP\"] = 1] = \"INVALID_SETUP\";\n\t\t ErrorCodes[ErrorCodes[\"UNSUPPORTED_SETUP\"] = 2] = \"UNSUPPORTED_SETUP\";\n\t\t ErrorCodes[ErrorCodes[\"REJECTED_SETUP\"] = 3] = \"REJECTED_SETUP\";\n\t\t ErrorCodes[ErrorCodes[\"REJECTED_RESUME\"] = 4] = \"REJECTED_RESUME\";\n\t\t ErrorCodes[ErrorCodes[\"CONNECTION_CLOSE\"] = 258] = \"CONNECTION_CLOSE\";\n\t\t ErrorCodes[ErrorCodes[\"CONNECTION_ERROR\"] = 257] = \"CONNECTION_ERROR\";\n\t\t ErrorCodes[ErrorCodes[\"APPLICATION_ERROR\"] = 513] = \"APPLICATION_ERROR\";\n\t\t ErrorCodes[ErrorCodes[\"REJECTED\"] = 514] = \"REJECTED\";\n\t\t ErrorCodes[ErrorCodes[\"CANCELED\"] = 515] = \"CANCELED\";\n\t\t ErrorCodes[ErrorCodes[\"INVALID\"] = 516] = \"INVALID\";\n\t\t ErrorCodes[ErrorCodes[\"RESERVED_EXTENSION\"] = 4294967295] = \"RESERVED_EXTENSION\";\n\t\t})(exports$1.ErrorCodes || (exports$1.ErrorCodes = {}));\n\t\t\n\t} (Errors));\n\treturn Errors;\n}\n\nvar RSocket = {};\n\nvar hasRequiredRSocket;\n\nfunction requireRSocket () {\n\tif (hasRequiredRSocket) return RSocket;\n\thasRequiredRSocket = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tObject.defineProperty(RSocket, \"__esModule\", { value: true });\n\t\n\treturn RSocket;\n}\n\nvar RSocketConnector = {};\n\nvar ClientServerMultiplexerDemultiplexer = {};\n\nvar hasRequiredClientServerMultiplexerDemultiplexer;\n\nfunction requireClientServerMultiplexerDemultiplexer () {\n\tif (hasRequiredClientServerMultiplexerDemultiplexer) return ClientServerMultiplexerDemultiplexer;\n\thasRequiredClientServerMultiplexerDemultiplexer = 1;\n\t(function (exports$1) {\n\t\t/*\n\t\t * Copyright 2021-2022 the original author or authors.\n\t\t *\n\t\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t\t * you may not use this file except in compliance with the License.\n\t\t * You may obtain a copy of the License at\n\t\t *\n\t\t * http://www.apache.org/licenses/LICENSE-2.0\n\t\t *\n\t\t * Unless required by applicable law or agreed to in writing, software\n\t\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t\t * See the License for the specific language governing permissions and\n\t\t * limitations under the License.\n\t\t */\n\t\tvar __extends = (ClientServerMultiplexerDemultiplexer && ClientServerMultiplexerDemultiplexer.__extends) || (function () {\n\t\t var extendStatics = function (d, b) {\n\t\t extendStatics = Object.setPrototypeOf ||\n\t\t ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n\t\t function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n\t\t return extendStatics(d, b);\n\t\t };\n\t\t return function (d, b) {\n\t\t if (typeof b !== \"function\" && b !== null)\n\t\t throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n\t\t extendStatics(d, b);\n\t\t function __() { this.constructor = d; }\n\t\t d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n\t\t };\n\t\t})();\n\t\tvar __awaiter = (ClientServerMultiplexerDemultiplexer && ClientServerMultiplexerDemultiplexer.__awaiter) || function (thisArg, _arguments, P, generator) {\n\t\t function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n\t\t return new (P || (P = Promise))(function (resolve, reject) {\n\t\t function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n\t\t function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n\t\t function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n\t\t step((generator = generator.apply(thisArg, _arguments || [])).next());\n\t\t });\n\t\t};\n\t\tvar __generator = (ClientServerMultiplexerDemultiplexer && ClientServerMultiplexerDemultiplexer.__generator) || function (thisArg, body) {\n\t\t var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n\t\t return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n\t\t function verb(n) { return function (v) { return step([n, v]); }; }\n\t\t function step(op) {\n\t\t if (f) throw new TypeError(\"Generator is already executing.\");\n\t\t while (_) try {\n\t\t if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n\t\t if (y = 0, t) op = [op[0] & 2, t.value];\n\t\t switch (op[0]) {\n\t\t case 0: case 1: t = op; break;\n\t\t case 4: _.label++; return { value: op[1], done: false };\n\t\t case 5: _.label++; y = op[1]; op = [0]; continue;\n\t\t case 7: op = _.ops.pop(); _.trys.pop(); continue;\n\t\t default:\n\t\t if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n\t\t if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n\t\t if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n\t\t if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n\t\t if (t[2]) _.ops.pop();\n\t\t _.trys.pop(); continue;\n\t\t }\n\t\t op = body.call(thisArg, _);\n\t\t } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n\t\t if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n\t\t }\n\t\t};\n\t\tObject.defineProperty(exports$1, \"__esModule\", { value: true });\n\t\texports$1.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = exports$1.ResumableClientServerInputMultiplexerDemultiplexer = exports$1.ClientServerInputMultiplexerDemultiplexer = exports$1.StreamIdGenerator = void 0;\n\t\tvar _1 = requireDist();\n\t\tvar Deferred_1 = requireDeferred();\n\t\tvar Errors_1 = requireErrors();\n\t\tvar Frames_1 = requireFrames();\n\t\t(function (StreamIdGenerator) {\n\t\t function create(seedId) {\n\t\t return new StreamIdGeneratorImpl(seedId);\n\t\t }\n\t\t StreamIdGenerator.create = create;\n\t\t var StreamIdGeneratorImpl = /** @class */ (function () {\n\t\t function StreamIdGeneratorImpl(currentId) {\n\t\t this.currentId = currentId;\n\t\t }\n\t\t StreamIdGeneratorImpl.prototype.next = function (handler) {\n\t\t var nextId = this.currentId + 2;\n\t\t if (!handler(nextId)) {\n\t\t return;\n\t\t }\n\t\t this.currentId = nextId;\n\t\t };\n\t\t return StreamIdGeneratorImpl;\n\t\t }());\n\t\t})(exports$1.StreamIdGenerator || (exports$1.StreamIdGenerator = {}));\n\t\tvar ClientServerInputMultiplexerDemultiplexer = /** @class */ (function (_super) {\n\t\t __extends(ClientServerInputMultiplexerDemultiplexer, _super);\n\t\t function ClientServerInputMultiplexerDemultiplexer(streamIdSupplier, outbound, closeable) {\n\t\t var _this = _super.call(this) || this;\n\t\t _this.streamIdSupplier = streamIdSupplier;\n\t\t _this.outbound = outbound;\n\t\t _this.closeable = closeable;\n\t\t _this.registry = {};\n\t\t closeable.onClose(_this.close.bind(_this));\n\t\t return _this;\n\t\t }\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.handle = function (frame) {\n\t\t if (Frames_1.Frame.isConnection(frame)) {\n\t\t if (frame.type === _1.FrameTypes.RESERVED) {\n\t\t // TODO: throw\n\t\t return;\n\t\t }\n\t\t this.connectionFramesHandler.handle(frame);\n\t\t // TODO: Connection Handler\n\t\t }\n\t\t else if (Frames_1.Frame.isRequest(frame)) {\n\t\t if (this.registry[frame.streamId]) {\n\t\t // TODO: Send error and close connection\n\t\t return;\n\t\t }\n\t\t this.requestFramesHandler.handle(frame, this);\n\t\t }\n\t\t else {\n\t\t var handler = this.registry[frame.streamId];\n\t\t if (!handler) {\n\t\t // TODO: add validation\n\t\t return;\n\t\t }\n\t\t handler.handle(frame);\n\t\t }\n\t\t // TODO: add extensions support\n\t\t };\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.connectionInbound = function (handler) {\n\t\t if (this.connectionFramesHandler) {\n\t\t throw new Error(\"Connection frame handler has already been installed\");\n\t\t }\n\t\t this.connectionFramesHandler = handler;\n\t\t };\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.handleRequestStream = function (handler) {\n\t\t if (this.requestFramesHandler) {\n\t\t throw new Error(\"Stream handler has already been installed\");\n\t\t }\n\t\t this.requestFramesHandler = handler;\n\t\t };\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.send = function (frame) {\n\t\t this.outbound.send(frame);\n\t\t };\n\t\t Object.defineProperty(ClientServerInputMultiplexerDemultiplexer.prototype, \"connectionOutbound\", {\n\t\t get: function () {\n\t\t return this;\n\t\t },\n\t\t enumerable: false,\n\t\t configurable: true\n\t\t });\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.createRequestStream = function (streamHandler) {\n\t\t var _this = this;\n\t\t // handle requester side stream registration\n\t\t if (this.done) {\n\t\t streamHandler.handleReject(new Error(\"Already closed\"));\n\t\t return;\n\t\t }\n\t\t var registry = this.registry;\n\t\t this.streamIdSupplier.next(function (streamId) { return streamHandler.handleReady(streamId, _this); }, Object.keys(registry));\n\t\t };\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.connect = function (handler) {\n\t\t this.registry[handler.streamId] = handler;\n\t\t };\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.disconnect = function (stream) {\n\t\t delete this.registry[stream.streamId];\n\t\t };\n\t\t ClientServerInputMultiplexerDemultiplexer.prototype.close = function (error) {\n\t\t if (this.done) {\n\t\t _super.prototype.close.call(this, error);\n\t\t return;\n\t\t }\n\t\t for (var streamId in this.registry) {\n\t\t var stream = this.registry[streamId];\n\t\t stream.close(new Error(\"Closed. \".concat(error ? \"Original cause [\".concat(error, \"].\") : \"\")));\n\t\t }\n\t\t _super.prototype.close.call(this, error);\n\t\t };\n\t\t return ClientServerInputMultiplexerDemultiplexer;\n\t\t}(Deferred_1.Deferred));\n\t\texports$1.ClientServerInputMultiplexerDemultiplexer = ClientServerInputMultiplexerDemultiplexer;\n\t\tvar ResumableClientServerInputMultiplexerDemultiplexer = /** @class */ (function (_super) {\n\t\t __extends(ResumableClientServerInputMultiplexerDemultiplexer, _super);\n\t\t function ResumableClientServerInputMultiplexerDemultiplexer(streamIdSupplier, outbound, closeable, frameStore, token, sessionStoreOrReconnector, sessionTimeout) {\n\t\t var _this = _super.call(this, streamIdSupplier, outbound, new Deferred_1.Deferred()) || this;\n\t\t _this.frameStore = frameStore;\n\t\t _this.token = token;\n\t\t _this.sessionTimeout = sessionTimeout;\n\t\t if (sessionStoreOrReconnector instanceof Function) {\n\t\t _this.reconnector = sessionStoreOrReconnector;\n\t\t }\n\t\t else {\n\t\t _this.sessionStore = sessionStoreOrReconnector;\n\t\t }\n\t\t closeable.onClose(_this.handleConnectionClose.bind(_this));\n\t\t return _this;\n\t\t }\n\t\t ResumableClientServerInputMultiplexerDemultiplexer.prototype.send = function (frame) {\n\t\t if (Frames_1.Frame.isConnection(frame)) {\n\t\t if (frame.type === _1.FrameTypes.KEEPALIVE) {\n\t\t frame.lastReceivedPosition = this.frameStore.lastReceivedFramePosition;\n\t\t }\n\t\t else if (frame.type === _1.FrameTypes.ERROR) {\n\t\t this.outbound.send(frame);\n\t\t if (this.sessionStore) {\n\t\t delete this.sessionStore[this.token];\n\t\t }\n\t\t _super.prototype.close.call(this, new Errors_1.RSocketError(frame.code, frame.message));\n\t\t return;\n\t\t }\n\t\t }\n\t\t else {\n\t\t this.frameStore.store(frame);\n\t\t }\n\t\t this.outbound.send(frame);\n\t\t };\n\t\t ResumableClientServerInputMultiplexerDemultiplexer.prototype.handle = function (frame) {\n\t\t if (Frames_1.Frame.isConnection(frame)) {\n\t\t if (frame.type === _1.FrameTypes.KEEPALIVE) {\n\t\t try {\n\t\t this.frameStore.dropTo(frame.lastReceivedPosition);\n\t\t }\n\t\t catch (re) {\n\t\t this.outbound.send({\n\t\t type: _1.FrameTypes.ERROR,\n\t\t streamId: 0,\n\t\t flags: _1.Flags.NONE,\n\t\t code: re.code,\n\t\t message: re.message,\n\t\t });\n\t\t this.close(re);\n\t\t }\n\t\t }\n\t\t else if (frame.type === _1.FrameTypes.ERROR) {\n\t\t _super.prototype.handle.call(this, frame);\n\t\t if (this.sessionStore) {\n\t\t delete this.sessionStore[this.token];\n\t\t }\n\t\t _super.prototype.close.call(this, new Errors_1.RSocketError(frame.code, frame.message));\n\t\t return;\n\t\t }\n\t\t }\n\t\t else {\n\t\t this.frameStore.record(frame);\n\t\t }\n\t\t _super.prototype.handle.call(this, frame);\n\t\t };\n\t\t ResumableClientServerInputMultiplexerDemultiplexer.prototype.resume = function (frame, outbound, closeable) {\n\t\t this.outbound = outbound;\n\t\t switch (frame.type) {\n\t\t case _1.FrameTypes.RESUME: {\n\t\t clearTimeout(this.timeoutId);\n\t\t if (this.frameStore.lastReceivedFramePosition < frame.clientPosition) {\n\t\t var e = new Errors_1.RSocketError(_1.ErrorCodes.REJECTED_RESUME, \"Impossible to resume since first available client frame position is greater than last received server frame position\");\n\t\t this.outbound.send({\n\t\t type: _1.FrameTypes.ERROR,\n\t\t streamId: 0,\n\t\t flags: _1.Flags.NONE,\n\t\t code: e.code,\n\t\t message: e.message,\n\t\t });\n\t\t this.close(e);\n\t\t return;\n\t\t }\n\t\t try {\n\t\t this.frameStore.dropTo(frame.serverPosition);\n\t\t }\n\t\t catch (re) {\n\t\t this.outbound.send({\n\t\t type: _1.FrameTypes.ERROR,\n\t\t streamId: 0,\n\t\t flags: _1.Flags.NONE,\n\t\t code: re.code,\n\t\t message: re.message,\n\t\t });\n\t\t this.close(re);\n\t\t return;\n\t\t }\n\t\t this.outbound.send({\n\t\t type: _1.FrameTypes.RESUME_OK,\n\t\t streamId: 0,\n\t\t flags: _1.Flags.NONE,\n\t\t clientPosition: this.frameStore.lastReceivedFramePosition,\n\t\t });\n\t\t break;\n\t\t }\n\t\t case _1.FrameTypes.RESUME_OK: {\n\t\t try {\n\t\t this.frameStore.dropTo(frame.clientPosition);\n\t\t }\n\t\t catch (re) {\n\t\t this.outbound.send({\n\t\t type: _1.FrameTypes.ERROR,\n\t\t streamId: 0,\n\t\t flags: _1.Flags.NONE,\n\t\t code: re.code,\n\t\t message: re.message,\n\t\t });\n\t\t this.close(re);\n\t\t }\n\t\t break;\n\t\t }\n\t\t }\n\t\t this.frameStore.drain(this.outbound.send.bind(this.outbound));\n\t\t closeable.onClose(this.handleConnectionClose.bind(this));\n\t\t this.connectionFramesHandler.resume();\n\t\t };\n\t\t ResumableClientServerInputMultiplexerDemultiplexer.prototype.handleConnectionClose = function (_error) {\n\t\t return __awaiter(this, void 0, void 0, function () {\n\t\t var e_1;\n\t\t return __generator(this, function (_a) {\n\t\t switch (_a.label) {\n\t\t case 0:\n\t\t this.connectionFramesHandler.pause();\n\t\t if (!this.reconnector) return [3 /*break*/, 5];\n\t\t _a.label = 1;\n\t\t case 1:\n\t\t _a.trys.push([1, 3, , 4]);\n\t\t return [4 /*yield*/, this.reconnector(this, this.frameStore)];\n\t\t case 2:\n\t\t _a.sent();\n\t\t return [3 /*break*/, 4];\n\t\t case 3:\n\t\t e_1 = _a.sent();\n\t\t this.close(e_1);\n\t\t return [3 /*break*/, 4];\n\t\t case 4: return [3 /*break*/, 6];\n\t\t case 5:\n\t\t this.timeoutId = setTimeout(this.close.bind(this), this.sessionTimeout);\n\t\t _a.label = 6;\n\t\t case 6: return [2 /*return*/];\n\t\t }\n\t\t });\n\t\t });\n\t\t };\n\t\t return ResumableClientServerInputMultiplexerDemultiplexer;\n\t\t}(ClientServerInputMultiplexerDemultiplexer));\n\t\texports$1.ResumableClientServerInputMultiplexerDemultiplexer = ResumableClientServerInputMultiplexerDemultiplexer;\n\t\tvar ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = /** @class */ (function () {\n\t\t function ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer(outbound, closeable, delegate) {\n\t\t this.outbound = outbound;\n\t\t this.closeable = closeable;\n\t\t this.delegate = delegate;\n\t\t this.resumed = false;\n\t\t }\n\t\t ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype.close = function () {\n\t\t this.delegate.close();\n\t\t };\n\t\t ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype.onClose = function (callback) {\n\t\t this.delegate.onClose(callback);\n\t\t };\n\t\t Object.defineProperty(ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype, \"connectionOutbound\", {\n\t\t get: function () {\n\t\t return this.delegate.connectionOutbound;\n\t\t },\n\t\t enumerable: false,\n\t\t configurable: true\n\t\t });\n\t\t ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype.createRequestStream = function (streamHandler) {\n\t\t this.delegate.createRequestStream(streamHandler);\n\t\t };\n\t\t ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype.connectionInbound = function (handler) {\n\t\t this.delegate.connectionInbound(handler);\n\t\t };\n\t\t ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype.handleRequestStream = function (handler) {\n\t\t this.delegate.handleRequestStream(handler);\n\t\t };\n\t\t ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer.prototype.handle = function (frame) {\n\t\t var _this = this;\n\t\t if (!this.resumed) {\n\t\t if (frame.type === _1.FrameTypes.RESUME_OK) {\n\t\t this.resumed = true;\n\t\t this.delegate.resume(frame, this.outbound, this.closeable);\n\t\t return;\n\t\t }\n\t\t else {\n\t\t this.outbound.send({\n\t\t type: _1.FrameTypes.ERROR,\n\t\t streamId: 0,\n\t\t code: _1.ErrorCodes.CONNECTION_ERROR,\n\t\t message: \"Incomplete RESUME handshake. Unexpected frame \".concat(frame.type, \" received\"),\n\t\t flags: _1.Flags.NONE,\n\t\t });\n\t\t this.closeable.close();\n\t\t this.closeable.onClose(function () {\n\t\t return _this.delegate.close(new Errors_1.RSocketError(_1.ErrorCodes.CONNECTION_ERROR, \"Incomplete RESUME handshake. Unexpected frame \".concat(frame.type, \" received\")));\n\t\t });\n\t\t }\n\t\t return;\n\t\t }\n\t\t this.delegate.handle(frame);\n\t\t };\n\t\t return ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer;\n\t\t}());\n\t\texports$1.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer;\n\t\t\n\t} (ClientServerMultiplexerDemultiplexer));\n\treturn ClientServerMultiplexerDemultiplexer;\n}\n\nvar RSocketSupport = {};\n\nvar RequestChannelStream = {};\n\nvar Fragmenter = {};\n\nvar hasRequiredFragmenter;\n\nfunction requireFragmenter () {\n\tif (hasRequiredFragmenter) return Fragmenter;\n\thasRequiredFragmenter = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __generator = (Fragmenter && Fragmenter.__generator) || function (thisArg, body) {\n\t var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n\t return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n\t function verb(n) { return function (v) { return step([n, v]); }; }\n\t function step(op) {\n\t if (f) throw new TypeError(\"Generator is already executing.\");\n\t while (_) try {\n\t if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n\t if (y = 0, t) op = [op[0] & 2, t.value];\n\t switch (op[0]) {\n\t case 0: case 1: t = op; break;\n\t case 4: _.label++; return { value: op[1], done: false };\n\t case 5: _.label++; y = op[1]; op = [0]; continue;\n\t case 7: op = _.ops.pop(); _.trys.pop(); continue;\n\t default:\n\t if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n\t if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n\t if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n\t if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n\t if (t[2]) _.ops.pop();\n\t _.trys.pop(); continue;\n\t }\n\t op = body.call(thisArg, _);\n\t } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n\t if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n\t }\n\t};\n\tObject.defineProperty(Fragmenter, \"__esModule\", { value: true });\n\tFragmenter.fragmentWithRequestN = Fragmenter.fragment = Fragmenter.isFragmentable = void 0;\n\tvar Frames_1 = requireFrames();\n\tfunction isFragmentable(payload, fragmentSize, frameType) {\n\t if (fragmentSize === 0) {\n\t return false;\n\t }\n\t return (payload.data.byteLength +\n\t (payload.metadata ? payload.metadata.byteLength + Frames_1.Lengths.METADATA : 0) +\n\t (frameType == Frames_1.FrameTypes.REQUEST_STREAM ||\n\t frameType == Frames_1.FrameTypes.REQUEST_CHANNEL\n\t ? Frames_1.Lengths.REQUEST\n\t : 0) >\n\t fragmentSize);\n\t}\n\tFragmenter.isFragmentable = isFragmentable;\n\tfunction fragment(streamId, payload, fragmentSize, frameType, isComplete) {\n\t var dataLength, firstFrame, remaining, metadata, metadataLength, metadataPosition, nextMetadataPosition, nextMetadataPosition, dataPosition, data, nextDataPosition, nextDataPosition;\n\t var _a, _b;\n\t if (isComplete === void 0) { isComplete = false; }\n\t return __generator(this, function (_c) {\n\t switch (_c.label) {\n\t case 0:\n\t dataLength = (_b = (_a = payload.data) === null || _a === void 0 ? void 0 : _a.byteLength) !== null && _b !== void 0 ? _b : 0;\n\t firstFrame = frameType !== Frames_1.FrameTypes.PAYLOAD;\n\t remaining = fragmentSize;\n\t if (!payload.metadata) return [3 /*break*/, 6];\n\t metadataLength = payload.metadata.byteLength;\n\t if (!(metadataLength === 0)) return [3 /*break*/, 1];\n\t remaining -= Frames_1.Lengths.METADATA;\n\t metadata = bufferExports.Buffer.allocUnsafe(0);\n\t return [3 /*break*/, 6];\n\t case 1:\n\t metadataPosition = 0;\n\t if (!firstFrame) return [3 /*break*/, 3];\n\t remaining -= Frames_1.Lengths.METADATA;\n\t nextMetadataPosition = Math.min(metadataLength, metadataPosition + remaining);\n\t metadata = payload.metadata.slice(metadataPosition, nextMetadataPosition);\n\t remaining -= metadata.byteLength;\n\t metadataPosition = nextMetadataPosition;\n\t if (!(remaining === 0)) return [3 /*break*/, 3];\n\t firstFrame = false;\n\t return [4 /*yield*/, {\n\t type: frameType,\n\t flags: Frames_1.Flags.FOLLOWS | Frames_1.Flags.METADATA,\n\t data: undefined,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 2:\n\t _c.sent();\n\t metadata = undefined;\n\t remaining = fragmentSize;\n\t _c.label = 3;\n\t case 3:\n\t if (!(metadataPosition < metadataLength)) return [3 /*break*/, 6];\n\t remaining -= Frames_1.Lengths.METADATA;\n\t nextMetadataPosition = Math.min(metadataLength, metadataPosition + remaining);\n\t metadata = payload.metadata.slice(metadataPosition, nextMetadataPosition);\n\t remaining -= metadata.byteLength;\n\t metadataPosition = nextMetadataPosition;\n\t if (!(remaining === 0 || dataLength === 0)) return [3 /*break*/, 5];\n\t return [4 /*yield*/, {\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.NEXT |\n\t Frames_1.Flags.METADATA |\n\t (metadataPosition === metadataLength &&\n\t isComplete &&\n\t dataLength === 0\n\t ? Frames_1.Flags.COMPLETE\n\t : Frames_1.Flags.FOLLOWS),\n\t data: undefined,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 4:\n\t _c.sent();\n\t metadata = undefined;\n\t remaining = fragmentSize;\n\t _c.label = 5;\n\t case 5: return [3 /*break*/, 3];\n\t case 6:\n\t dataPosition = 0;\n\t if (!firstFrame) return [3 /*break*/, 8];\n\t nextDataPosition = Math.min(dataLength, dataPosition + remaining);\n\t data = payload.data.slice(dataPosition, nextDataPosition);\n\t remaining -= data.byteLength;\n\t dataPosition = nextDataPosition;\n\t return [4 /*yield*/, {\n\t type: frameType,\n\t flags: Frames_1.Flags.FOLLOWS | (metadata ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE),\n\t data: data,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 7:\n\t _c.sent();\n\t metadata = undefined;\n\t data = undefined;\n\t remaining = fragmentSize;\n\t _c.label = 8;\n\t case 8:\n\t if (!(dataPosition < dataLength)) return [3 /*break*/, 10];\n\t nextDataPosition = Math.min(dataLength, dataPosition + remaining);\n\t data = payload.data.slice(dataPosition, nextDataPosition);\n\t remaining -= data.byteLength;\n\t dataPosition = nextDataPosition;\n\t return [4 /*yield*/, {\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: dataPosition === dataLength\n\t ? (isComplete ? Frames_1.Flags.COMPLETE : Frames_1.Flags.NONE) |\n\t Frames_1.Flags.NEXT |\n\t (metadata ? Frames_1.Flags.METADATA : 0)\n\t : Frames_1.Flags.FOLLOWS | Frames_1.Flags.NEXT | (metadata ? Frames_1.Flags.METADATA : 0),\n\t data: data,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 9:\n\t _c.sent();\n\t metadata = undefined;\n\t data = undefined;\n\t remaining = fragmentSize;\n\t return [3 /*break*/, 8];\n\t case 10: return [2 /*return*/];\n\t }\n\t });\n\t}\n\tFragmenter.fragment = fragment;\n\tfunction fragmentWithRequestN(streamId, payload, fragmentSize, frameType, requestN, isComplete) {\n\t var dataLength, firstFrame, remaining, metadata, metadataLength, metadataPosition, nextMetadataPosition, nextMetadataPosition, dataPosition, data, nextDataPosition, nextDataPosition;\n\t var _a, _b;\n\t if (isComplete === void 0) { isComplete = false; }\n\t return __generator(this, function (_c) {\n\t switch (_c.label) {\n\t case 0:\n\t dataLength = (_b = (_a = payload.data) === null || _a === void 0 ? void 0 : _a.byteLength) !== null && _b !== void 0 ? _b : 0;\n\t firstFrame = true;\n\t remaining = fragmentSize;\n\t if (!payload.metadata) return [3 /*break*/, 6];\n\t metadataLength = payload.metadata.byteLength;\n\t if (!(metadataLength === 0)) return [3 /*break*/, 1];\n\t remaining -= Frames_1.Lengths.METADATA;\n\t metadata = bufferExports.Buffer.allocUnsafe(0);\n\t return [3 /*break*/, 6];\n\t case 1:\n\t metadataPosition = 0;\n\t if (!firstFrame) return [3 /*break*/, 3];\n\t remaining -= Frames_1.Lengths.METADATA + Frames_1.Lengths.REQUEST;\n\t nextMetadataPosition = Math.min(metadataLength, metadataPosition + remaining);\n\t metadata = payload.metadata.slice(metadataPosition, nextMetadataPosition);\n\t remaining -= metadata.byteLength;\n\t metadataPosition = nextMetadataPosition;\n\t if (!(remaining === 0)) return [3 /*break*/, 3];\n\t firstFrame = false;\n\t return [4 /*yield*/, {\n\t type: frameType,\n\t flags: Frames_1.Flags.FOLLOWS | Frames_1.Flags.METADATA,\n\t data: undefined,\n\t requestN: requestN,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 2:\n\t _c.sent();\n\t metadata = undefined;\n\t remaining = fragmentSize;\n\t _c.label = 3;\n\t case 3:\n\t if (!(metadataPosition < metadataLength)) return [3 /*break*/, 6];\n\t remaining -= Frames_1.Lengths.METADATA;\n\t nextMetadataPosition = Math.min(metadataLength, metadataPosition + remaining);\n\t metadata = payload.metadata.slice(metadataPosition, nextMetadataPosition);\n\t remaining -= metadata.byteLength;\n\t metadataPosition = nextMetadataPosition;\n\t if (!(remaining === 0 || dataLength === 0)) return [3 /*break*/, 5];\n\t return [4 /*yield*/, {\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.NEXT |\n\t Frames_1.Flags.METADATA |\n\t (metadataPosition === metadataLength &&\n\t isComplete &&\n\t dataLength === 0\n\t ? Frames_1.Flags.COMPLETE\n\t : Frames_1.Flags.FOLLOWS),\n\t data: undefined,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 4:\n\t _c.sent();\n\t metadata = undefined;\n\t remaining = fragmentSize;\n\t _c.label = 5;\n\t case 5: return [3 /*break*/, 3];\n\t case 6:\n\t dataPosition = 0;\n\t if (!firstFrame) return [3 /*break*/, 8];\n\t remaining -= Frames_1.Lengths.REQUEST;\n\t nextDataPosition = Math.min(dataLength, dataPosition + remaining);\n\t data = payload.data.slice(dataPosition, nextDataPosition);\n\t remaining -= data.byteLength;\n\t dataPosition = nextDataPosition;\n\t return [4 /*yield*/, {\n\t type: frameType,\n\t flags: Frames_1.Flags.FOLLOWS | (metadata ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE),\n\t data: data,\n\t requestN: requestN,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 7:\n\t _c.sent();\n\t metadata = undefined;\n\t data = undefined;\n\t remaining = fragmentSize;\n\t _c.label = 8;\n\t case 8:\n\t if (!(dataPosition < dataLength)) return [3 /*break*/, 10];\n\t nextDataPosition = Math.min(dataLength, dataPosition + remaining);\n\t data = payload.data.slice(dataPosition, nextDataPosition);\n\t remaining -= data.byteLength;\n\t dataPosition = nextDataPosition;\n\t return [4 /*yield*/, {\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: dataPosition === dataLength\n\t ? (isComplete ? Frames_1.Flags.COMPLETE : Frames_1.Flags.NONE) |\n\t Frames_1.Flags.NEXT |\n\t (metadata ? Frames_1.Flags.METADATA : 0)\n\t : Frames_1.Flags.FOLLOWS | Frames_1.Flags.NEXT | (metadata ? Frames_1.Flags.METADATA : 0),\n\t data: data,\n\t metadata: metadata,\n\t streamId: streamId,\n\t }];\n\t case 9:\n\t _c.sent();\n\t metadata = undefined;\n\t data = undefined;\n\t remaining = fragmentSize;\n\t return [3 /*break*/, 8];\n\t case 10: return [2 /*return*/];\n\t }\n\t });\n\t}\n\tFragmenter.fragmentWithRequestN = fragmentWithRequestN;\n\t\n\treturn Fragmenter;\n}\n\nvar Reassembler = {};\n\nvar hasRequiredReassembler;\n\nfunction requireReassembler () {\n\tif (hasRequiredReassembler) return Reassembler;\n\thasRequiredReassembler = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tObject.defineProperty(Reassembler, \"__esModule\", { value: true });\n\tReassembler.cancel = Reassembler.reassemble = Reassembler.add = void 0;\n\tfunction add(holder, dataFragment, metadataFragment) {\n\t if (!holder.hasFragments) {\n\t holder.hasFragments = true;\n\t holder.data = dataFragment;\n\t if (metadataFragment) {\n\t holder.metadata = metadataFragment;\n\t }\n\t return true;\n\t }\n\t // TODO: add validation\n\t holder.data = holder.data\n\t ? bufferExports.Buffer.concat([holder.data, dataFragment])\n\t : dataFragment;\n\t if (holder.metadata && metadataFragment) {\n\t holder.metadata = bufferExports.Buffer.concat([holder.metadata, metadataFragment]);\n\t }\n\t return true;\n\t}\n\tReassembler.add = add;\n\tfunction reassemble(holder, dataFragment, metadataFragment) {\n\t // TODO: add validation\n\t holder.hasFragments = false;\n\t var data = holder.data\n\t ? bufferExports.Buffer.concat([holder.data, dataFragment])\n\t : dataFragment;\n\t holder.data = undefined;\n\t if (holder.metadata) {\n\t var metadata = metadataFragment\n\t ? bufferExports.Buffer.concat([holder.metadata, metadataFragment])\n\t : holder.metadata;\n\t holder.metadata = undefined;\n\t return {\n\t data: data,\n\t metadata: metadata,\n\t };\n\t }\n\t return {\n\t data: data,\n\t };\n\t}\n\tReassembler.reassemble = reassemble;\n\tfunction cancel(holder) {\n\t holder.hasFragments = false;\n\t holder.data = undefined;\n\t holder.metadata = undefined;\n\t}\n\tReassembler.cancel = cancel;\n\t\n\treturn Reassembler;\n}\n\nvar hasRequiredRequestChannelStream;\n\nfunction requireRequestChannelStream () {\n\tif (hasRequiredRequestChannelStream) return RequestChannelStream;\n\thasRequiredRequestChannelStream = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __createBinding = (RequestChannelStream && RequestChannelStream.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n\t}) : (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t o[k2] = m[k];\n\t}));\n\tvar __setModuleDefault = (RequestChannelStream && RequestChannelStream.__setModuleDefault) || (Object.create ? (function(o, v) {\n\t Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n\t}) : function(o, v) {\n\t o[\"default\"] = v;\n\t});\n\tvar __importStar = (RequestChannelStream && RequestChannelStream.__importStar) || function (mod) {\n\t if (mod && mod.__esModule) return mod;\n\t var result = {};\n\t if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\t __setModuleDefault(result, mod);\n\t return result;\n\t};\n\tvar __values = (RequestChannelStream && RequestChannelStream.__values) || function(o) {\n\t var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n\t if (m) return m.call(o);\n\t if (o && typeof o.length === \"number\") return {\n\t next: function () {\n\t if (o && i >= o.length) o = void 0;\n\t return { value: o && o[i++], done: !o };\n\t }\n\t };\n\t throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n\t};\n\tObject.defineProperty(RequestChannelStream, \"__esModule\", { value: true });\n\tRequestChannelStream.RequestChannelResponderStream = RequestChannelStream.RequestChannelRequesterStream = void 0;\n\tvar Errors_1 = requireErrors();\n\tvar Fragmenter_1 = requireFragmenter();\n\tvar Frames_1 = requireFrames();\n\tvar Reassembler = __importStar(requireReassembler());\n\tvar RequestChannelRequesterStream = /** @class */ (function () {\n\t function RequestChannelRequesterStream(payload, isComplete, receiver, fragmentSize, initialRequestN, leaseManager) {\n\t this.payload = payload;\n\t this.isComplete = isComplete;\n\t this.receiver = receiver;\n\t this.fragmentSize = fragmentSize;\n\t this.initialRequestN = initialRequestN;\n\t this.leaseManager = leaseManager;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_CHANNEL;\n\t // TODO: add payload size validation\n\t }\n\t RequestChannelRequesterStream.prototype.handleReady = function (streamId, stream) {\n\t var e_1, _a;\n\t if (this.outboundDone) {\n\t return false;\n\t }\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t stream.connect(this);\n\t var isCompleted = this.isComplete;\n\t if (isCompleted) {\n\t this.outboundDone = isCompleted;\n\t }\n\t if ((0, Fragmenter_1.isFragmentable)(this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_CHANNEL)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragmentWithRequestN)(streamId, this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_CHANNEL, this.initialRequestN, isCompleted)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_1_1) { e_1 = { error: e_1_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_1) throw e_1.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_CHANNEL,\n\t data: this.payload.data,\n\t metadata: this.payload.metadata,\n\t requestN: this.initialRequestN,\n\t flags: (this.payload.metadata !== undefined ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE) |\n\t (isCompleted ? Frames_1.Flags.COMPLETE : Frames_1.Flags.NONE),\n\t streamId: streamId,\n\t });\n\t }\n\t if (this.hasExtension) {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.EXT,\n\t streamId: streamId,\n\t extendedContent: this.extendedContent,\n\t extendedType: this.extendedType,\n\t flags: this.flags,\n\t });\n\t }\n\t return true;\n\t };\n\t RequestChannelRequesterStream.prototype.handleReject = function (error) {\n\t if (this.inboundDone) {\n\t return;\n\t }\n\t this.inboundDone = true;\n\t this.outboundDone = true;\n\t this.receiver.onError(error);\n\t };\n\t RequestChannelRequesterStream.prototype.handle = function (frame) {\n\t var errorMessage;\n\t var frameType = frame.type;\n\t switch (frameType) {\n\t case Frames_1.FrameTypes.PAYLOAD: {\n\t var hasComplete = Frames_1.Flags.hasComplete(frame.flags);\n\t var hasNext = Frames_1.Flags.hasNext(frame.flags);\n\t if (hasComplete || !Frames_1.Flags.hasFollows(frame.flags)) {\n\t if (hasComplete) {\n\t this.inboundDone = true;\n\t if (this.outboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t if (!hasNext) {\n\t // TODO: add validation no frame in reassembly\n\t this.receiver.onComplete();\n\t return;\n\t }\n\t }\n\t var payload = this.hasFragments\n\t ? Reassembler.reassemble(this, frame.data, frame.metadata)\n\t : {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t this.receiver.onNext(payload, hasComplete);\n\t return;\n\t }\n\t if (Reassembler.add(this, frame.data, frame.metadata)) {\n\t return;\n\t }\n\t errorMessage = \"Unexpected frame size\";\n\t break;\n\t }\n\t case Frames_1.FrameTypes.CANCEL: {\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t this.outboundDone = true;\n\t if (this.inboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t this.receiver.cancel();\n\t return;\n\t }\n\t case Frames_1.FrameTypes.REQUEST_N: {\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t if (this.hasFragments) {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"] during reassembly\");\n\t break;\n\t }\n\t this.receiver.request(frame.requestN);\n\t return;\n\t }\n\t case Frames_1.FrameTypes.ERROR: {\n\t var outboundDone = this.outboundDone;\n\t this.inboundDone = true;\n\t this.outboundDone = true;\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t if (!outboundDone) {\n\t this.receiver.cancel();\n\t }\n\t this.receiver.onError(new Errors_1.RSocketError(frame.code, frame.message));\n\t return;\n\t }\n\t case Frames_1.FrameTypes.EXT:\n\t this.receiver.onExtension(frame.extendedType, frame.extendedContent, Frames_1.Flags.hasIgnore(frame.flags));\n\t return;\n\t default: {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"]\");\n\t }\n\t }\n\t this.close(new Errors_1.RSocketError(Errors_1.ErrorCodes.CANCELED, errorMessage));\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.CANCEL,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t this.stream.disconnect(this);\n\t };\n\t RequestChannelRequesterStream.prototype.request = function (n) {\n\t if (this.inboundDone) {\n\t return;\n\t }\n\t if (!this.streamId) {\n\t this.initialRequestN += n;\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_N,\n\t flags: Frames_1.Flags.NONE,\n\t requestN: n,\n\t streamId: this.streamId,\n\t });\n\t };\n\t RequestChannelRequesterStream.prototype.cancel = function () {\n\t var _a;\n\t var inboundDone = this.inboundDone;\n\t var outboundDone = this.outboundDone;\n\t if (inboundDone && outboundDone) {\n\t return;\n\t }\n\t this.inboundDone = true;\n\t this.outboundDone = true;\n\t if (!outboundDone) {\n\t this.receiver.cancel();\n\t }\n\t if (!this.streamId) {\n\t (_a = this.leaseManager) === null || _a === void 0 ? void 0 : _a.cancelRequest(this);\n\t return;\n\t }\n\t this.stream.send({\n\t type: inboundDone ? Frames_1.FrameTypes.ERROR : Frames_1.FrameTypes.CANCEL,\n\t flags: Frames_1.Flags.NONE,\n\t streamId: this.streamId,\n\t code: Errors_1.ErrorCodes.CANCELED,\n\t message: \"Cancelled\",\n\t });\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t };\n\t RequestChannelRequesterStream.prototype.onNext = function (payload, isComplete) {\n\t var e_2, _a;\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t if (isComplete) {\n\t this.outboundDone = true;\n\t if (this.inboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t }\n\t if ((0, Fragmenter_1.isFragmentable)(payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragment)(this.streamId, payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD, isComplete)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_2_1) { e_2 = { error: e_2_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_2) throw e_2.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.NEXT |\n\t (payload.metadata ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE) |\n\t (isComplete ? Frames_1.Flags.COMPLETE : Frames_1.Flags.NONE),\n\t data: payload.data,\n\t metadata: payload.metadata,\n\t });\n\t }\n\t };\n\t RequestChannelRequesterStream.prototype.onComplete = function () {\n\t if (!this.streamId) {\n\t this.isComplete = true;\n\t return;\n\t }\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t this.outboundDone = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.COMPLETE,\n\t data: null,\n\t metadata: null,\n\t });\n\t if (this.inboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t };\n\t RequestChannelRequesterStream.prototype.onError = function (error) {\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t var inboundDone = this.inboundDone;\n\t this.outboundDone = true;\n\t this.inboundDone = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.NONE,\n\t code: error instanceof Errors_1.RSocketError\n\t ? error.code\n\t : Errors_1.ErrorCodes.APPLICATION_ERROR,\n\t message: error.message,\n\t });\n\t this.stream.disconnect(this);\n\t if (!inboundDone) {\n\t this.receiver.onError(error);\n\t }\n\t };\n\t RequestChannelRequesterStream.prototype.onExtension = function (extendedType, content, canBeIgnored) {\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t if (!this.streamId) {\n\t this.hasExtension = true;\n\t this.extendedType = extendedType;\n\t this.extendedContent = content;\n\t this.flags = canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE;\n\t return;\n\t }\n\t this.stream.send({\n\t streamId: this.streamId,\n\t type: Frames_1.FrameTypes.EXT,\n\t extendedType: extendedType,\n\t extendedContent: content,\n\t flags: canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE,\n\t });\n\t };\n\t RequestChannelRequesterStream.prototype.close = function (error) {\n\t if (this.inboundDone && this.outboundDone) {\n\t return;\n\t }\n\t var inboundDone = this.inboundDone;\n\t var outboundDone = this.outboundDone;\n\t this.inboundDone = true;\n\t this.outboundDone = true;\n\t Reassembler.cancel(this);\n\t if (!outboundDone) {\n\t this.receiver.cancel();\n\t }\n\t if (!inboundDone) {\n\t if (error) {\n\t this.receiver.onError(error);\n\t }\n\t else {\n\t this.receiver.onComplete();\n\t }\n\t }\n\t };\n\t return RequestChannelRequesterStream;\n\t}());\n\tRequestChannelStream.RequestChannelRequesterStream = RequestChannelRequesterStream;\n\tvar RequestChannelResponderStream = /** @class */ (function () {\n\t function RequestChannelResponderStream(streamId, stream, fragmentSize, handler, frame) {\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t this.fragmentSize = fragmentSize;\n\t this.handler = handler;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_CHANNEL;\n\t stream.connect(this);\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t Reassembler.add(this, frame.data, frame.metadata);\n\t this.initialRequestN = frame.requestN;\n\t this.isComplete = Frames_1.Flags.hasComplete(frame.flags);\n\t return;\n\t }\n\t var payload = {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t var hasComplete = Frames_1.Flags.hasComplete(frame.flags);\n\t this.inboundDone = hasComplete;\n\t try {\n\t this.receiver = handler(payload, frame.requestN, hasComplete, this);\n\t if (this.outboundDone && this.defferedError) {\n\t this.receiver.onError(this.defferedError);\n\t }\n\t }\n\t catch (error) {\n\t if (this.outboundDone && !this.inboundDone) {\n\t this.cancel();\n\t }\n\t else {\n\t this.inboundDone = true;\n\t }\n\t this.onError(error);\n\t }\n\t }\n\t RequestChannelResponderStream.prototype.handle = function (frame) {\n\t var errorMessage;\n\t var frameType = frame.type;\n\t switch (frameType) {\n\t case Frames_1.FrameTypes.PAYLOAD: {\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t if (Reassembler.add(this, frame.data, frame.metadata)) {\n\t return;\n\t }\n\t errorMessage = \"Unexpected frame size\";\n\t break;\n\t }\n\t var payload = this.hasFragments\n\t ? Reassembler.reassemble(this, frame.data, frame.metadata)\n\t : {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t var hasComplete = Frames_1.Flags.hasComplete(frame.flags);\n\t if (!this.receiver) {\n\t var inboundDone = this.isComplete || hasComplete;\n\t if (inboundDone) {\n\t this.inboundDone = true;\n\t if (this.outboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t }\n\t try {\n\t this.receiver = this.handler(payload, this.initialRequestN, inboundDone, this);\n\t if (this.outboundDone && this.defferedError) {\n\t }\n\t }\n\t catch (error) {\n\t if (this.outboundDone && !this.inboundDone) {\n\t this.cancel();\n\t }\n\t else {\n\t this.inboundDone = true;\n\t }\n\t this.onError(error);\n\t }\n\t }\n\t else {\n\t if (hasComplete) {\n\t this.inboundDone = true;\n\t if (this.outboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t if (!Frames_1.Flags.hasNext(frame.flags)) {\n\t this.receiver.onComplete();\n\t return;\n\t }\n\t }\n\t this.receiver.onNext(payload, hasComplete);\n\t }\n\t return;\n\t }\n\t case Frames_1.FrameTypes.REQUEST_N: {\n\t if (!this.receiver || this.hasFragments) {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"] during reassembly\");\n\t break;\n\t }\n\t this.receiver.request(frame.requestN);\n\t return;\n\t }\n\t case Frames_1.FrameTypes.ERROR:\n\t case Frames_1.FrameTypes.CANCEL: {\n\t var inboundDone = this.inboundDone;\n\t var outboundDone = this.outboundDone;\n\t this.inboundDone = true;\n\t this.outboundDone = true;\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t if (!this.receiver) {\n\t return;\n\t }\n\t if (!outboundDone) {\n\t this.receiver.cancel();\n\t }\n\t if (!inboundDone) {\n\t var error = frameType === Frames_1.FrameTypes.CANCEL\n\t ? new Errors_1.RSocketError(Errors_1.ErrorCodes.CANCELED, \"Cancelled\")\n\t : new Errors_1.RSocketError(frame.code, frame.message);\n\t this.receiver.onError(error);\n\t }\n\t return;\n\t }\n\t case Frames_1.FrameTypes.EXT: {\n\t if (!this.receiver || this.hasFragments) {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"] during reassembly\");\n\t break;\n\t }\n\t this.receiver.onExtension(frame.extendedType, frame.extendedContent, Frames_1.Flags.hasIgnore(frame.flags));\n\t return;\n\t }\n\t default: {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"]\");\n\t // TODO: throws if strict\n\t }\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t flags: Frames_1.Flags.NONE,\n\t code: Errors_1.ErrorCodes.CANCELED,\n\t message: errorMessage,\n\t streamId: this.streamId,\n\t });\n\t this.stream.disconnect(this);\n\t this.close(new Errors_1.RSocketError(Errors_1.ErrorCodes.CANCELED, errorMessage));\n\t };\n\t RequestChannelResponderStream.prototype.onError = function (error) {\n\t if (this.outboundDone) {\n\t console.warn(\"Trying to error for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t var inboundDone = this.inboundDone;\n\t this.outboundDone = true;\n\t this.inboundDone = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t flags: Frames_1.Flags.NONE,\n\t code: error instanceof Errors_1.RSocketError\n\t ? error.code\n\t : Errors_1.ErrorCodes.APPLICATION_ERROR,\n\t message: error.message,\n\t streamId: this.streamId,\n\t });\n\t this.stream.disconnect(this);\n\t if (!inboundDone) {\n\t if (this.receiver) {\n\t this.receiver.onError(error);\n\t }\n\t else {\n\t this.defferedError = error;\n\t }\n\t }\n\t };\n\t RequestChannelResponderStream.prototype.onNext = function (payload, isCompletion) {\n\t var e_3, _a;\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t if (isCompletion) {\n\t this.outboundDone = true;\n\t }\n\t // TODO: add payload size validation\n\t if ((0, Fragmenter_1.isFragmentable)(payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragment)(this.streamId, payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD, isCompletion)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_3_1) { e_3 = { error: e_3_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_3) throw e_3.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.NEXT |\n\t (isCompletion ? Frames_1.Flags.COMPLETE : Frames_1.Flags.NONE) |\n\t (payload.metadata ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE),\n\t data: payload.data,\n\t metadata: payload.metadata,\n\t streamId: this.streamId,\n\t });\n\t }\n\t if (isCompletion && this.inboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t };\n\t RequestChannelResponderStream.prototype.onComplete = function () {\n\t if (this.outboundDone) {\n\t return;\n\t }\n\t this.outboundDone = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.COMPLETE,\n\t streamId: this.streamId,\n\t data: null,\n\t metadata: null,\n\t });\n\t if (this.inboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t };\n\t RequestChannelResponderStream.prototype.onExtension = function (extendedType, content, canBeIgnored) {\n\t if (this.outboundDone && this.inboundDone) {\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.EXT,\n\t streamId: this.streamId,\n\t flags: canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE,\n\t extendedType: extendedType,\n\t extendedContent: content,\n\t });\n\t };\n\t RequestChannelResponderStream.prototype.request = function (n) {\n\t if (this.inboundDone) {\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_N,\n\t flags: Frames_1.Flags.NONE,\n\t streamId: this.streamId,\n\t requestN: n,\n\t });\n\t };\n\t RequestChannelResponderStream.prototype.cancel = function () {\n\t if (this.inboundDone) {\n\t return;\n\t }\n\t this.inboundDone = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.CANCEL,\n\t flags: Frames_1.Flags.NONE,\n\t streamId: this.streamId,\n\t });\n\t if (this.outboundDone) {\n\t this.stream.disconnect(this);\n\t }\n\t };\n\t RequestChannelResponderStream.prototype.close = function (error) {\n\t if (this.inboundDone && this.outboundDone) {\n\t console.warn(\"Trying to close for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t var inboundDone = this.inboundDone;\n\t var outboundDone = this.outboundDone;\n\t this.inboundDone = true;\n\t this.outboundDone = true;\n\t Reassembler.cancel(this);\n\t var receiver = this.receiver;\n\t if (!receiver) {\n\t return;\n\t }\n\t if (!outboundDone) {\n\t receiver.cancel();\n\t }\n\t if (!inboundDone) {\n\t if (error) {\n\t receiver.onError(error);\n\t }\n\t else {\n\t receiver.onComplete();\n\t }\n\t }\n\t };\n\t return RequestChannelResponderStream;\n\t}());\n\tRequestChannelStream.RequestChannelResponderStream = RequestChannelResponderStream;\n\t\n\treturn RequestChannelStream;\n}\n\nvar RequestFnFStream = {};\n\nvar hasRequiredRequestFnFStream;\n\nfunction requireRequestFnFStream () {\n\tif (hasRequiredRequestFnFStream) return RequestFnFStream;\n\thasRequiredRequestFnFStream = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __createBinding = (RequestFnFStream && RequestFnFStream.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n\t}) : (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t o[k2] = m[k];\n\t}));\n\tvar __setModuleDefault = (RequestFnFStream && RequestFnFStream.__setModuleDefault) || (Object.create ? (function(o, v) {\n\t Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n\t}) : function(o, v) {\n\t o[\"default\"] = v;\n\t});\n\tvar __importStar = (RequestFnFStream && RequestFnFStream.__importStar) || function (mod) {\n\t if (mod && mod.__esModule) return mod;\n\t var result = {};\n\t if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\t __setModuleDefault(result, mod);\n\t return result;\n\t};\n\tvar __values = (RequestFnFStream && RequestFnFStream.__values) || function(o) {\n\t var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n\t if (m) return m.call(o);\n\t if (o && typeof o.length === \"number\") return {\n\t next: function () {\n\t if (o && i >= o.length) o = void 0;\n\t return { value: o && o[i++], done: !o };\n\t }\n\t };\n\t throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n\t};\n\tObject.defineProperty(RequestFnFStream, \"__esModule\", { value: true });\n\tRequestFnFStream.RequestFnfResponderStream = RequestFnFStream.RequestFnFRequesterStream = void 0;\n\tvar Errors_1 = requireErrors();\n\tvar Fragmenter_1 = requireFragmenter();\n\tvar Frames_1 = requireFrames();\n\tvar Reassembler = __importStar(requireReassembler());\n\tvar RequestFnFRequesterStream = /** @class */ (function () {\n\t function RequestFnFRequesterStream(payload, receiver, fragmentSize, leaseManager) {\n\t this.payload = payload;\n\t this.receiver = receiver;\n\t this.fragmentSize = fragmentSize;\n\t this.leaseManager = leaseManager;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_FNF;\n\t }\n\t RequestFnFRequesterStream.prototype.handleReady = function (streamId, stream) {\n\t var e_1, _a;\n\t if (this.done) {\n\t return false;\n\t }\n\t this.streamId = streamId;\n\t if ((0, Fragmenter_1.isFragmentable)(this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_FNF)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragment)(streamId, this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_FNF)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t stream.send(frame);\n\t }\n\t }\n\t catch (e_1_1) { e_1 = { error: e_1_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_1) throw e_1.error; }\n\t }\n\t }\n\t else {\n\t stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_FNF,\n\t data: this.payload.data,\n\t metadata: this.payload.metadata,\n\t flags: this.payload.metadata ? Frames_1.Flags.METADATA : 0,\n\t streamId: streamId,\n\t });\n\t }\n\t this.done = true;\n\t this.receiver.onComplete();\n\t return true;\n\t };\n\t RequestFnFRequesterStream.prototype.handleReject = function (error) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t this.receiver.onError(error);\n\t };\n\t RequestFnFRequesterStream.prototype.cancel = function () {\n\t var _a;\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t (_a = this.leaseManager) === null || _a === void 0 ? void 0 : _a.cancelRequest(this);\n\t };\n\t RequestFnFRequesterStream.prototype.handle = function (frame) {\n\t if (frame.type == Frames_1.FrameTypes.ERROR) {\n\t this.close(new Errors_1.RSocketError(frame.code, frame.message));\n\t return;\n\t }\n\t this.close(new Errors_1.RSocketError(Errors_1.ErrorCodes.CANCELED, \"Received invalid frame\"));\n\t };\n\t RequestFnFRequesterStream.prototype.close = function (error) {\n\t if (this.done) {\n\t console.warn(\"Trying to close for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t if (error) {\n\t this.receiver.onError(error);\n\t }\n\t else {\n\t this.receiver.onComplete();\n\t }\n\t };\n\t return RequestFnFRequesterStream;\n\t}());\n\tRequestFnFStream.RequestFnFRequesterStream = RequestFnFRequesterStream;\n\tvar RequestFnfResponderStream = /** @class */ (function () {\n\t function RequestFnfResponderStream(streamId, stream, handler, frame) {\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t this.handler = handler;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_FNF;\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t Reassembler.add(this, frame.data, frame.metadata);\n\t stream.connect(this);\n\t return;\n\t }\n\t var payload = {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t try {\n\t this.cancellable = handler(payload, this);\n\t }\n\t catch (e) {\n\t // do nothing\n\t }\n\t }\n\t RequestFnfResponderStream.prototype.handle = function (frame) {\n\t var errorMessage;\n\t if (frame.type == Frames_1.FrameTypes.PAYLOAD) {\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t if (Reassembler.add(this, frame.data, frame.metadata)) {\n\t return;\n\t }\n\t errorMessage = \"Unexpected fragment size\";\n\t }\n\t else {\n\t this.stream.disconnect(this);\n\t var payload = Reassembler.reassemble(this, frame.data, frame.metadata);\n\t try {\n\t this.cancellable = this.handler(payload, this);\n\t }\n\t catch (e) {\n\t // do nothing\n\t }\n\t return;\n\t }\n\t }\n\t else {\n\t errorMessage = \"Unexpected frame type [\".concat(frame.type, \"]\");\n\t }\n\t this.done = true;\n\t if (frame.type != Frames_1.FrameTypes.CANCEL && frame.type != Frames_1.FrameTypes.ERROR) {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.NONE,\n\t code: Errors_1.ErrorCodes.CANCELED,\n\t message: errorMessage,\n\t });\n\t }\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t // TODO: throws if strict\n\t };\n\t RequestFnfResponderStream.prototype.close = function (error) {\n\t var _a;\n\t if (this.done) {\n\t console.warn(\"Trying to close for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t this.done = true;\n\t Reassembler.cancel(this);\n\t (_a = this.cancellable) === null || _a === void 0 ? void 0 : _a.cancel();\n\t };\n\t RequestFnfResponderStream.prototype.onError = function (error) { };\n\t RequestFnfResponderStream.prototype.onComplete = function () { };\n\t return RequestFnfResponderStream;\n\t}());\n\tRequestFnFStream.RequestFnfResponderStream = RequestFnfResponderStream;\n\t/*\n\texport function request(\n\t payload: Payload,\n\t responderStream: UnidirectionalStream\n\t): Handler<Cancellable> {\n\t return {\n\t create: (r) => {\n\t const response = new RequestFnFRequesterHandler(\n\t payload,\n\t responderStream,\n\t r\n\t );\n\n\t r.add(response);\n\n\t return response;\n\t },\n\t };\n\t}\n\n\texport function response(\n\t handler: (payload: Payload, responderStream: UnidirectionalStream,) => void\n\t): Handler<void> {\n\t return {\n\t create: (r) => new RequestFnfResponderHandler(),\n\t };\n\t} */\n\t\n\treturn RequestFnFStream;\n}\n\nvar RequestResponseStream = {};\n\nvar hasRequiredRequestResponseStream;\n\nfunction requireRequestResponseStream () {\n\tif (hasRequiredRequestResponseStream) return RequestResponseStream;\n\thasRequiredRequestResponseStream = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __createBinding = (RequestResponseStream && RequestResponseStream.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n\t}) : (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t o[k2] = m[k];\n\t}));\n\tvar __setModuleDefault = (RequestResponseStream && RequestResponseStream.__setModuleDefault) || (Object.create ? (function(o, v) {\n\t Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n\t}) : function(o, v) {\n\t o[\"default\"] = v;\n\t});\n\tvar __importStar = (RequestResponseStream && RequestResponseStream.__importStar) || function (mod) {\n\t if (mod && mod.__esModule) return mod;\n\t var result = {};\n\t if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\t __setModuleDefault(result, mod);\n\t return result;\n\t};\n\tvar __values = (RequestResponseStream && RequestResponseStream.__values) || function(o) {\n\t var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n\t if (m) return m.call(o);\n\t if (o && typeof o.length === \"number\") return {\n\t next: function () {\n\t if (o && i >= o.length) o = void 0;\n\t return { value: o && o[i++], done: !o };\n\t }\n\t };\n\t throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n\t};\n\tObject.defineProperty(RequestResponseStream, \"__esModule\", { value: true });\n\tRequestResponseStream.RequestResponseResponderStream = RequestResponseStream.RequestResponseRequesterStream = void 0;\n\tvar Errors_1 = requireErrors();\n\tvar Fragmenter_1 = requireFragmenter();\n\tvar Frames_1 = requireFrames();\n\tvar Reassembler = __importStar(requireReassembler());\n\tvar RequestResponseRequesterStream = /** @class */ (function () {\n\t function RequestResponseRequesterStream(payload, receiver, fragmentSize, leaseManager) {\n\t this.payload = payload;\n\t this.receiver = receiver;\n\t this.fragmentSize = fragmentSize;\n\t this.leaseManager = leaseManager;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_RESPONSE;\n\t }\n\t RequestResponseRequesterStream.prototype.handleReady = function (streamId, stream) {\n\t var e_1, _a;\n\t if (this.done) {\n\t return false;\n\t }\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t stream.connect(this);\n\t if ((0, Fragmenter_1.isFragmentable)(this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_RESPONSE)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragment)(streamId, this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_RESPONSE)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_1_1) { e_1 = { error: e_1_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_1) throw e_1.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_RESPONSE,\n\t data: this.payload.data,\n\t metadata: this.payload.metadata,\n\t flags: this.payload.metadata ? Frames_1.Flags.METADATA : 0,\n\t streamId: streamId,\n\t });\n\t }\n\t if (this.hasExtension) {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.EXT,\n\t streamId: streamId,\n\t extendedContent: this.extendedContent,\n\t extendedType: this.extendedType,\n\t flags: this.flags,\n\t });\n\t }\n\t return true;\n\t };\n\t RequestResponseRequesterStream.prototype.handleReject = function (error) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t this.receiver.onError(error);\n\t };\n\t RequestResponseRequesterStream.prototype.handle = function (frame) {\n\t var errorMessage;\n\t var frameType = frame.type;\n\t switch (frameType) {\n\t case Frames_1.FrameTypes.PAYLOAD: {\n\t var hasComplete = Frames_1.Flags.hasComplete(frame.flags);\n\t var hasPayload = Frames_1.Flags.hasNext(frame.flags);\n\t if (hasComplete || !Frames_1.Flags.hasFollows(frame.flags)) {\n\t this.done = true;\n\t this.stream.disconnect(this);\n\t if (!hasPayload) {\n\t // TODO: add validation no frame in reassembly\n\t this.receiver.onComplete();\n\t return;\n\t }\n\t var payload = this.hasFragments\n\t ? Reassembler.reassemble(this, frame.data, frame.metadata)\n\t : {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t this.receiver.onNext(payload, true);\n\t return;\n\t }\n\t if (!Reassembler.add(this, frame.data, frame.metadata)) {\n\t errorMessage = \"Unexpected fragment size\";\n\t break;\n\t }\n\t return;\n\t }\n\t case Frames_1.FrameTypes.ERROR: {\n\t this.done = true;\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t this.receiver.onError(new Errors_1.RSocketError(frame.code, frame.message));\n\t return;\n\t }\n\t case Frames_1.FrameTypes.EXT: {\n\t if (this.hasFragments) {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"] during reassembly\");\n\t break;\n\t }\n\t this.receiver.onExtension(frame.extendedType, frame.extendedContent, Frames_1.Flags.hasIgnore(frame.flags));\n\t return;\n\t }\n\t default: {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"]\");\n\t }\n\t }\n\t this.close(new Errors_1.RSocketError(Errors_1.ErrorCodes.CANCELED, errorMessage));\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.CANCEL,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t this.stream.disconnect(this);\n\t // TODO: throw an exception if strict frame handling mode\n\t };\n\t RequestResponseRequesterStream.prototype.cancel = function () {\n\t var _a;\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t if (!this.streamId) {\n\t (_a = this.leaseManager) === null || _a === void 0 ? void 0 : _a.cancelRequest(this);\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.CANCEL,\n\t flags: Frames_1.Flags.NONE,\n\t streamId: this.streamId,\n\t });\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t };\n\t RequestResponseRequesterStream.prototype.onExtension = function (extendedType, content, canBeIgnored) {\n\t if (this.done) {\n\t return;\n\t }\n\t if (!this.streamId) {\n\t this.hasExtension = true;\n\t this.extendedType = extendedType;\n\t this.extendedContent = content;\n\t this.flags = canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE;\n\t return;\n\t }\n\t this.stream.send({\n\t streamId: this.streamId,\n\t type: Frames_1.FrameTypes.EXT,\n\t extendedType: extendedType,\n\t extendedContent: content,\n\t flags: canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE,\n\t });\n\t };\n\t RequestResponseRequesterStream.prototype.close = function (error) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t Reassembler.cancel(this);\n\t if (error) {\n\t this.receiver.onError(error);\n\t }\n\t else {\n\t this.receiver.onComplete();\n\t }\n\t };\n\t return RequestResponseRequesterStream;\n\t}());\n\tRequestResponseStream.RequestResponseRequesterStream = RequestResponseRequesterStream;\n\tvar RequestResponseResponderStream = /** @class */ (function () {\n\t function RequestResponseResponderStream(streamId, stream, fragmentSize, handler, frame) {\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t this.fragmentSize = fragmentSize;\n\t this.handler = handler;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_RESPONSE;\n\t stream.connect(this);\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t Reassembler.add(this, frame.data, frame.metadata);\n\t return;\n\t }\n\t var payload = {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t try {\n\t this.receiver = handler(payload, this);\n\t }\n\t catch (error) {\n\t this.onError(error);\n\t }\n\t }\n\t RequestResponseResponderStream.prototype.handle = function (frame) {\n\t var _a;\n\t var errorMessage;\n\t if (!this.receiver || this.hasFragments) {\n\t if (frame.type === Frames_1.FrameTypes.PAYLOAD) {\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t if (Reassembler.add(this, frame.data, frame.metadata)) {\n\t return;\n\t }\n\t errorMessage = \"Unexpected fragment size\";\n\t }\n\t else {\n\t var payload = Reassembler.reassemble(this, frame.data, frame.metadata);\n\t try {\n\t this.receiver = this.handler(payload, this);\n\t }\n\t catch (error) {\n\t this.onError(error);\n\t }\n\t return;\n\t }\n\t }\n\t else {\n\t errorMessage = \"Unexpected frame type [\".concat(frame.type, \"] during reassembly\");\n\t }\n\t }\n\t else if (frame.type === Frames_1.FrameTypes.EXT) {\n\t this.receiver.onExtension(frame.extendedType, frame.extendedContent, Frames_1.Flags.hasIgnore(frame.flags));\n\t return;\n\t }\n\t else {\n\t errorMessage = \"Unexpected frame type [\".concat(frame.type, \"]\");\n\t }\n\t this.done = true;\n\t (_a = this.receiver) === null || _a === void 0 ? void 0 : _a.cancel();\n\t if (frame.type !== Frames_1.FrameTypes.CANCEL && frame.type !== Frames_1.FrameTypes.ERROR) {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t flags: Frames_1.Flags.NONE,\n\t code: Errors_1.ErrorCodes.CANCELED,\n\t message: errorMessage,\n\t streamId: this.streamId,\n\t });\n\t }\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t // TODO: throws if strict\n\t };\n\t RequestResponseResponderStream.prototype.onError = function (error) {\n\t if (this.done) {\n\t console.warn(\"Trying to error for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t this.done = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t flags: Frames_1.Flags.NONE,\n\t code: error instanceof Errors_1.RSocketError\n\t ? error.code\n\t : Errors_1.ErrorCodes.APPLICATION_ERROR,\n\t message: error.message,\n\t streamId: this.streamId,\n\t });\n\t this.stream.disconnect(this);\n\t };\n\t RequestResponseResponderStream.prototype.onNext = function (payload, isCompletion) {\n\t var e_2, _a;\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t // TODO: add payload size validation\n\t if ((0, Fragmenter_1.isFragmentable)(payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragment)(this.streamId, payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD, true)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_2_1) { e_2 = { error: e_2_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_2) throw e_2.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.NEXT | Frames_1.Flags.COMPLETE | (payload.metadata ? Frames_1.Flags.METADATA : 0),\n\t data: payload.data,\n\t metadata: payload.metadata,\n\t streamId: this.streamId,\n\t });\n\t }\n\t this.stream.disconnect(this);\n\t };\n\t RequestResponseResponderStream.prototype.onComplete = function () {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.COMPLETE,\n\t streamId: this.streamId,\n\t data: null,\n\t metadata: null,\n\t });\n\t this.stream.disconnect(this);\n\t };\n\t RequestResponseResponderStream.prototype.onExtension = function (extendedType, content, canBeIgnored) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.EXT,\n\t streamId: this.streamId,\n\t flags: canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE,\n\t extendedType: extendedType,\n\t extendedContent: content,\n\t });\n\t };\n\t RequestResponseResponderStream.prototype.close = function (error) {\n\t var _a;\n\t if (this.done) {\n\t console.warn(\"Trying to close for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t Reassembler.cancel(this);\n\t (_a = this.receiver) === null || _a === void 0 ? void 0 : _a.cancel();\n\t };\n\t return RequestResponseResponderStream;\n\t}());\n\tRequestResponseStream.RequestResponseResponderStream = RequestResponseResponderStream;\n\t\n\treturn RequestResponseStream;\n}\n\nvar RequestStreamStream = {};\n\nvar hasRequiredRequestStreamStream;\n\nfunction requireRequestStreamStream () {\n\tif (hasRequiredRequestStreamStream) return RequestStreamStream;\n\thasRequiredRequestStreamStream = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __createBinding = (RequestStreamStream && RequestStreamStream.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n\t}) : (function(o, m, k, k2) {\n\t if (k2 === undefined) k2 = k;\n\t o[k2] = m[k];\n\t}));\n\tvar __setModuleDefault = (RequestStreamStream && RequestStreamStream.__setModuleDefault) || (Object.create ? (function(o, v) {\n\t Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n\t}) : function(o, v) {\n\t o[\"default\"] = v;\n\t});\n\tvar __importStar = (RequestStreamStream && RequestStreamStream.__importStar) || function (mod) {\n\t if (mod && mod.__esModule) return mod;\n\t var result = {};\n\t if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\t __setModuleDefault(result, mod);\n\t return result;\n\t};\n\tvar __values = (RequestStreamStream && RequestStreamStream.__values) || function(o) {\n\t var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n\t if (m) return m.call(o);\n\t if (o && typeof o.length === \"number\") return {\n\t next: function () {\n\t if (o && i >= o.length) o = void 0;\n\t return { value: o && o[i++], done: !o };\n\t }\n\t };\n\t throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n\t};\n\tObject.defineProperty(RequestStreamStream, \"__esModule\", { value: true });\n\tRequestStreamStream.RequestStreamResponderStream = RequestStreamStream.RequestStreamRequesterStream = void 0;\n\tvar Errors_1 = requireErrors();\n\tvar Fragmenter_1 = requireFragmenter();\n\tvar Frames_1 = requireFrames();\n\tvar Reassembler = __importStar(requireReassembler());\n\tvar RequestStreamRequesterStream = /** @class */ (function () {\n\t function RequestStreamRequesterStream(payload, receiver, fragmentSize, initialRequestN, leaseManager) {\n\t this.payload = payload;\n\t this.receiver = receiver;\n\t this.fragmentSize = fragmentSize;\n\t this.initialRequestN = initialRequestN;\n\t this.leaseManager = leaseManager;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_STREAM;\n\t // TODO: add payload size validation\n\t }\n\t RequestStreamRequesterStream.prototype.handleReady = function (streamId, stream) {\n\t var e_1, _a;\n\t if (this.done) {\n\t return false;\n\t }\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t stream.connect(this);\n\t if ((0, Fragmenter_1.isFragmentable)(this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_STREAM)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragmentWithRequestN)(streamId, this.payload, this.fragmentSize, Frames_1.FrameTypes.REQUEST_STREAM, this.initialRequestN)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_1_1) { e_1 = { error: e_1_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_1) throw e_1.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_STREAM,\n\t data: this.payload.data,\n\t metadata: this.payload.metadata,\n\t requestN: this.initialRequestN,\n\t flags: this.payload.metadata !== undefined ? Frames_1.Flags.METADATA : 0,\n\t streamId: streamId,\n\t });\n\t }\n\t if (this.hasExtension) {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.EXT,\n\t streamId: streamId,\n\t extendedContent: this.extendedContent,\n\t extendedType: this.extendedType,\n\t flags: this.flags,\n\t });\n\t }\n\t return true;\n\t };\n\t RequestStreamRequesterStream.prototype.handleReject = function (error) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t this.receiver.onError(error);\n\t };\n\t RequestStreamRequesterStream.prototype.handle = function (frame) {\n\t var errorMessage;\n\t var frameType = frame.type;\n\t switch (frameType) {\n\t case Frames_1.FrameTypes.PAYLOAD: {\n\t var hasComplete = Frames_1.Flags.hasComplete(frame.flags);\n\t var hasNext = Frames_1.Flags.hasNext(frame.flags);\n\t if (hasComplete || !Frames_1.Flags.hasFollows(frame.flags)) {\n\t if (hasComplete) {\n\t this.done = true;\n\t this.stream.disconnect(this);\n\t if (!hasNext) {\n\t // TODO: add validation no frame in reassembly\n\t this.receiver.onComplete();\n\t return;\n\t }\n\t }\n\t var payload = this.hasFragments\n\t ? Reassembler.reassemble(this, frame.data, frame.metadata)\n\t : {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t this.receiver.onNext(payload, hasComplete);\n\t return;\n\t }\n\t if (!Reassembler.add(this, frame.data, frame.metadata)) {\n\t errorMessage = \"Unexpected fragment size\";\n\t break;\n\t }\n\t return;\n\t }\n\t case Frames_1.FrameTypes.ERROR: {\n\t this.done = true;\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t this.receiver.onError(new Errors_1.RSocketError(frame.code, frame.message));\n\t return;\n\t }\n\t case Frames_1.FrameTypes.EXT: {\n\t if (this.hasFragments) {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"] during reassembly\");\n\t break;\n\t }\n\t this.receiver.onExtension(frame.extendedType, frame.extendedContent, Frames_1.Flags.hasIgnore(frame.flags));\n\t return;\n\t }\n\t default: {\n\t errorMessage = \"Unexpected frame type [\".concat(frameType, \"]\");\n\t }\n\t }\n\t this.close(new Errors_1.RSocketError(Errors_1.ErrorCodes.CANCELED, errorMessage));\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.CANCEL,\n\t streamId: this.streamId,\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t this.stream.disconnect(this);\n\t // TODO: throw an exception if strict frame handling mode\n\t };\n\t RequestStreamRequesterStream.prototype.request = function (n) {\n\t if (this.done) {\n\t return;\n\t }\n\t if (!this.streamId) {\n\t this.initialRequestN += n;\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.REQUEST_N,\n\t flags: Frames_1.Flags.NONE,\n\t requestN: n,\n\t streamId: this.streamId,\n\t });\n\t };\n\t RequestStreamRequesterStream.prototype.cancel = function () {\n\t var _a;\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t if (!this.streamId) {\n\t (_a = this.leaseManager) === null || _a === void 0 ? void 0 : _a.cancelRequest(this);\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.CANCEL,\n\t flags: Frames_1.Flags.NONE,\n\t streamId: this.streamId,\n\t });\n\t this.stream.disconnect(this);\n\t Reassembler.cancel(this);\n\t };\n\t RequestStreamRequesterStream.prototype.onExtension = function (extendedType, content, canBeIgnored) {\n\t if (this.done) {\n\t return;\n\t }\n\t if (!this.streamId) {\n\t this.hasExtension = true;\n\t this.extendedType = extendedType;\n\t this.extendedContent = content;\n\t this.flags = canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE;\n\t return;\n\t }\n\t this.stream.send({\n\t streamId: this.streamId,\n\t type: Frames_1.FrameTypes.EXT,\n\t extendedType: extendedType,\n\t extendedContent: content,\n\t flags: canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE,\n\t });\n\t };\n\t RequestStreamRequesterStream.prototype.close = function (error) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t Reassembler.cancel(this);\n\t if (error) {\n\t this.receiver.onError(error);\n\t }\n\t else {\n\t this.receiver.onComplete();\n\t }\n\t };\n\t return RequestStreamRequesterStream;\n\t}());\n\tRequestStreamStream.RequestStreamRequesterStream = RequestStreamRequesterStream;\n\tvar RequestStreamResponderStream = /** @class */ (function () {\n\t function RequestStreamResponderStream(streamId, stream, fragmentSize, handler, frame) {\n\t this.streamId = streamId;\n\t this.stream = stream;\n\t this.fragmentSize = fragmentSize;\n\t this.handler = handler;\n\t this.streamType = Frames_1.FrameTypes.REQUEST_STREAM;\n\t stream.connect(this);\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t this.initialRequestN = frame.requestN;\n\t Reassembler.add(this, frame.data, frame.metadata);\n\t return;\n\t }\n\t var payload = {\n\t data: frame.data,\n\t metadata: frame.metadata,\n\t };\n\t try {\n\t this.receiver = handler(payload, frame.requestN, this);\n\t }\n\t catch (error) {\n\t this.onError(error);\n\t }\n\t }\n\t RequestStreamResponderStream.prototype.handle = function (frame) {\n\t var _a;\n\t var errorMessage;\n\t if (!this.receiver || this.hasFragments) {\n\t if (frame.type === Frames_1.FrameTypes.PAYLOAD) {\n\t if (Frames_1.Flags.hasFollows(frame.flags)) {\n\t if (Reassembler.add(this, frame.data, frame.metadata)) {\n\t return;\n\t }\n\t errorMessage = \"Unexpected frame size\";\n\t }\n\t else {\n\t var payload = Reassembler.reassemble(this, frame.data, frame.metadata);\n\t try {\n\t this.receiver = this.handler(payload, this.initialRequestN, this);\n\t }\n\t catch (error) {\n\t this.onError(error);\n\t }\n\t return;\n\t }\n\t }\n\t else {\n\t errorMessage = \"Unexpected frame type [\".concat(frame.type, \"] during reassembly\");\n\t }\n\t }\n\t else if (frame.type === Frames_1.FrameTypes.REQUEST_N) {\n\t this.receiver.request(frame.requestN);\n\t return;\n\t }\n\t else if (frame.type === Frames_1.FrameTypes.EXT) {\n\t this.receiver.onExtension(frame.extendedType, frame.extendedContent, Frames_1.Flags.hasIgnore(frame.flags));\n\t return;\n\t }\n\t else {\n\t errorMessage = \"Unexpected frame type [\".concat(frame.type, \"]\");\n\t }\n\t this.done = true;\n\t Reassembler.cancel(this);\n\t (_a = this.receiver) === null || _a === void 0 ? void 0 : _a.cancel();\n\t if (frame.type !== Frames_1.FrameTypes.CANCEL && frame.type !== Frames_1.FrameTypes.ERROR) {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t flags: Frames_1.Flags.NONE,\n\t code: Errors_1.ErrorCodes.CANCELED,\n\t message: errorMessage,\n\t streamId: this.streamId,\n\t });\n\t }\n\t this.stream.disconnect(this);\n\t // TODO: throws if strict\n\t };\n\t RequestStreamResponderStream.prototype.onError = function (error) {\n\t if (this.done) {\n\t console.warn(\"Trying to error for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t this.done = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t flags: Frames_1.Flags.NONE,\n\t code: error instanceof Errors_1.RSocketError\n\t ? error.code\n\t : Errors_1.ErrorCodes.APPLICATION_ERROR,\n\t message: error.message,\n\t streamId: this.streamId,\n\t });\n\t this.stream.disconnect(this);\n\t };\n\t RequestStreamResponderStream.prototype.onNext = function (payload, isCompletion) {\n\t var e_2, _a;\n\t if (this.done) {\n\t return;\n\t }\n\t if (isCompletion) {\n\t this.done = true;\n\t }\n\t // TODO: add payload size validation\n\t if ((0, Fragmenter_1.isFragmentable)(payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD)) {\n\t try {\n\t for (var _b = __values((0, Fragmenter_1.fragment)(this.streamId, payload, this.fragmentSize, Frames_1.FrameTypes.PAYLOAD, isCompletion)), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t this.stream.send(frame);\n\t }\n\t }\n\t catch (e_2_1) { e_2 = { error: e_2_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_2) throw e_2.error; }\n\t }\n\t }\n\t else {\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.NEXT |\n\t (isCompletion ? Frames_1.Flags.COMPLETE : Frames_1.Flags.NONE) |\n\t (payload.metadata ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE),\n\t data: payload.data,\n\t metadata: payload.metadata,\n\t streamId: this.streamId,\n\t });\n\t }\n\t if (isCompletion) {\n\t this.stream.disconnect(this);\n\t }\n\t };\n\t RequestStreamResponderStream.prototype.onComplete = function () {\n\t if (this.done) {\n\t return;\n\t }\n\t this.done = true;\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.PAYLOAD,\n\t flags: Frames_1.Flags.COMPLETE,\n\t streamId: this.streamId,\n\t data: null,\n\t metadata: null,\n\t });\n\t this.stream.disconnect(this);\n\t };\n\t RequestStreamResponderStream.prototype.onExtension = function (extendedType, content, canBeIgnored) {\n\t if (this.done) {\n\t return;\n\t }\n\t this.stream.send({\n\t type: Frames_1.FrameTypes.EXT,\n\t streamId: this.streamId,\n\t flags: canBeIgnored ? Frames_1.Flags.IGNORE : Frames_1.Flags.NONE,\n\t extendedType: extendedType,\n\t extendedContent: content,\n\t });\n\t };\n\t RequestStreamResponderStream.prototype.close = function (error) {\n\t var _a;\n\t if (this.done) {\n\t console.warn(\"Trying to close for the second time. \".concat(error ? \"Dropping error [\".concat(error, \"].\") : \"\"));\n\t return;\n\t }\n\t Reassembler.cancel(this);\n\t (_a = this.receiver) === null || _a === void 0 ? void 0 : _a.cancel();\n\t };\n\t return RequestStreamResponderStream;\n\t}());\n\tRequestStreamStream.RequestStreamResponderStream = RequestStreamResponderStream;\n\t\n\treturn RequestStreamStream;\n}\n\nvar hasRequiredRSocketSupport;\n\nfunction requireRSocketSupport () {\n\tif (hasRequiredRSocketSupport) return RSocketSupport;\n\thasRequiredRSocketSupport = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tObject.defineProperty(RSocketSupport, \"__esModule\", { value: true });\n\tRSocketSupport.KeepAliveSender = RSocketSupport.KeepAliveHandler = RSocketSupport.DefaultConnectionFrameHandler = RSocketSupport.DefaultStreamRequestHandler = RSocketSupport.LeaseHandler = RSocketSupport.RSocketRequester = void 0;\n\tvar Errors_1 = requireErrors();\n\tvar Frames_1 = requireFrames();\n\tvar RequestChannelStream_1 = requireRequestChannelStream();\n\tvar RequestFnFStream_1 = requireRequestFnFStream();\n\tvar RequestResponseStream_1 = requireRequestResponseStream();\n\tvar RequestStreamStream_1 = requireRequestStreamStream();\n\tvar RSocketRequester = /** @class */ (function () {\n\t function RSocketRequester(connection, fragmentSize, leaseManager) {\n\t this.connection = connection;\n\t this.fragmentSize = fragmentSize;\n\t this.leaseManager = leaseManager;\n\t }\n\t RSocketRequester.prototype.fireAndForget = function (payload, responderStream) {\n\t var handler = new RequestFnFStream_1.RequestFnFRequesterStream(payload, responderStream, this.fragmentSize, this.leaseManager);\n\t if (this.leaseManager) {\n\t this.leaseManager.requestLease(handler);\n\t }\n\t else {\n\t this.connection.multiplexerDemultiplexer.createRequestStream(handler);\n\t }\n\t return handler;\n\t };\n\t RSocketRequester.prototype.requestResponse = function (payload, responderStream) {\n\t var handler = new RequestResponseStream_1.RequestResponseRequesterStream(payload, responderStream, this.fragmentSize, this.leaseManager);\n\t if (this.leaseManager) {\n\t this.leaseManager.requestLease(handler);\n\t }\n\t else {\n\t this.connection.multiplexerDemultiplexer.createRequestStream(handler);\n\t }\n\t return handler;\n\t };\n\t RSocketRequester.prototype.requestStream = function (payload, initialRequestN, responderStream) {\n\t var handler = new RequestStreamStream_1.RequestStreamRequesterStream(payload, responderStream, this.fragmentSize, initialRequestN, this.leaseManager);\n\t if (this.leaseManager) {\n\t this.leaseManager.requestLease(handler);\n\t }\n\t else {\n\t this.connection.multiplexerDemultiplexer.createRequestStream(handler);\n\t }\n\t return handler;\n\t };\n\t RSocketRequester.prototype.requestChannel = function (payload, initialRequestN, isCompleted, responderStream) {\n\t var handler = new RequestChannelStream_1.RequestChannelRequesterStream(payload, isCompleted, responderStream, this.fragmentSize, initialRequestN, this.leaseManager);\n\t if (this.leaseManager) {\n\t this.leaseManager.requestLease(handler);\n\t }\n\t else {\n\t this.connection.multiplexerDemultiplexer.createRequestStream(handler);\n\t }\n\t return handler;\n\t };\n\t RSocketRequester.prototype.metadataPush = function (metadata, responderStream) {\n\t throw new Error(\"Method not implemented.\");\n\t };\n\t RSocketRequester.prototype.close = function (error) {\n\t this.connection.close(error);\n\t };\n\t RSocketRequester.prototype.onClose = function (callback) {\n\t this.connection.onClose(callback);\n\t };\n\t return RSocketRequester;\n\t}());\n\tRSocketSupport.RSocketRequester = RSocketRequester;\n\tvar LeaseHandler = /** @class */ (function () {\n\t function LeaseHandler(maxPendingRequests, multiplexer) {\n\t this.maxPendingRequests = maxPendingRequests;\n\t this.multiplexer = multiplexer;\n\t this.pendingRequests = [];\n\t this.expirationTime = 0;\n\t this.availableLease = 0;\n\t }\n\t LeaseHandler.prototype.handle = function (frame) {\n\t this.expirationTime = frame.ttl + Date.now();\n\t this.availableLease = frame.requestCount;\n\t while (this.availableLease > 0 && this.pendingRequests.length > 0) {\n\t var handler = this.pendingRequests.shift();\n\t this.availableLease--;\n\t this.multiplexer.createRequestStream(handler);\n\t }\n\t };\n\t LeaseHandler.prototype.requestLease = function (handler) {\n\t var availableLease = this.availableLease;\n\t if (availableLease > 0 && Date.now() < this.expirationTime) {\n\t this.availableLease = availableLease - 1;\n\t this.multiplexer.createRequestStream(handler);\n\t return;\n\t }\n\t if (this.pendingRequests.length >= this.maxPendingRequests) {\n\t handler.handleReject(new Errors_1.RSocketError(Errors_1.ErrorCodes.REJECTED, \"No available lease given\"));\n\t return;\n\t }\n\t this.pendingRequests.push(handler);\n\t };\n\t LeaseHandler.prototype.cancelRequest = function (handler) {\n\t var index = this.pendingRequests.indexOf(handler);\n\t if (index > -1) {\n\t this.pendingRequests.splice(index, 1);\n\t }\n\t };\n\t return LeaseHandler;\n\t}());\n\tRSocketSupport.LeaseHandler = LeaseHandler;\n\tvar DefaultStreamRequestHandler = /** @class */ (function () {\n\t function DefaultStreamRequestHandler(rsocket, fragmentSize) {\n\t this.rsocket = rsocket;\n\t this.fragmentSize = fragmentSize;\n\t }\n\t DefaultStreamRequestHandler.prototype.handle = function (frame, stream) {\n\t switch (frame.type) {\n\t case Frames_1.FrameTypes.REQUEST_FNF:\n\t if (this.rsocket.fireAndForget) {\n\t new RequestFnFStream_1.RequestFnfResponderStream(frame.streamId, stream, this.rsocket.fireAndForget.bind(this.rsocket), frame);\n\t }\n\t return;\n\t case Frames_1.FrameTypes.REQUEST_RESPONSE:\n\t if (this.rsocket.requestResponse) {\n\t new RequestResponseStream_1.RequestResponseResponderStream(frame.streamId, stream, this.fragmentSize, this.rsocket.requestResponse.bind(this.rsocket), frame);\n\t return;\n\t }\n\t this.rejectRequest(frame.streamId, stream);\n\t return;\n\t case Frames_1.FrameTypes.REQUEST_STREAM:\n\t if (this.rsocket.requestStream) {\n\t new RequestStreamStream_1.RequestStreamResponderStream(frame.streamId, stream, this.fragmentSize, this.rsocket.requestStream.bind(this.rsocket), frame);\n\t return;\n\t }\n\t this.rejectRequest(frame.streamId, stream);\n\t return;\n\t case Frames_1.FrameTypes.REQUEST_CHANNEL:\n\t if (this.rsocket.requestChannel) {\n\t new RequestChannelStream_1.RequestChannelResponderStream(frame.streamId, stream, this.fragmentSize, this.rsocket.requestChannel.bind(this.rsocket), frame);\n\t return;\n\t }\n\t this.rejectRequest(frame.streamId, stream);\n\t return;\n\t }\n\t };\n\t DefaultStreamRequestHandler.prototype.rejectRequest = function (streamId, stream) {\n\t stream.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: streamId,\n\t flags: Frames_1.Flags.NONE,\n\t code: Errors_1.ErrorCodes.REJECTED,\n\t message: \"No available handler found\",\n\t });\n\t };\n\t DefaultStreamRequestHandler.prototype.close = function () { };\n\t return DefaultStreamRequestHandler;\n\t}());\n\tRSocketSupport.DefaultStreamRequestHandler = DefaultStreamRequestHandler;\n\tvar DefaultConnectionFrameHandler = /** @class */ (function () {\n\t function DefaultConnectionFrameHandler(connection, keepAliveHandler, keepAliveSender, leaseHandler, rsocket) {\n\t this.connection = connection;\n\t this.keepAliveHandler = keepAliveHandler;\n\t this.keepAliveSender = keepAliveSender;\n\t this.leaseHandler = leaseHandler;\n\t this.rsocket = rsocket;\n\t }\n\t DefaultConnectionFrameHandler.prototype.handle = function (frame) {\n\t switch (frame.type) {\n\t case Frames_1.FrameTypes.KEEPALIVE:\n\t this.keepAliveHandler.handle(frame);\n\t return;\n\t case Frames_1.FrameTypes.LEASE:\n\t if (this.leaseHandler) {\n\t this.leaseHandler.handle(frame);\n\t return;\n\t }\n\t // TODO throw exception and close connection\n\t return;\n\t case Frames_1.FrameTypes.ERROR:\n\t // TODO: add code validation\n\t this.connection.close(new Errors_1.RSocketError(frame.code, frame.message));\n\t return;\n\t case Frames_1.FrameTypes.METADATA_PUSH:\n\t if (this.rsocket.metadataPush) ;\n\t return;\n\t default:\n\t this.connection.multiplexerDemultiplexer.connectionOutbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t flags: Frames_1.Flags.NONE,\n\t message: \"Received unknown frame type\",\n\t code: Errors_1.ErrorCodes.CONNECTION_ERROR,\n\t });\n\t // TODO: throw an exception and close connection\n\t }\n\t };\n\t DefaultConnectionFrameHandler.prototype.pause = function () {\n\t var _a;\n\t this.keepAliveHandler.pause();\n\t (_a = this.keepAliveSender) === null || _a === void 0 ? void 0 : _a.pause();\n\t };\n\t DefaultConnectionFrameHandler.prototype.resume = function () {\n\t var _a;\n\t this.keepAliveHandler.start();\n\t (_a = this.keepAliveSender) === null || _a === void 0 ? void 0 : _a.start();\n\t };\n\t DefaultConnectionFrameHandler.prototype.close = function (error) {\n\t var _a;\n\t this.keepAliveHandler.close();\n\t (_a = this.rsocket.close) === null || _a === void 0 ? void 0 : _a.call(this.rsocket, error);\n\t };\n\t return DefaultConnectionFrameHandler;\n\t}());\n\tRSocketSupport.DefaultConnectionFrameHandler = DefaultConnectionFrameHandler;\n\tvar KeepAliveHandlerStates;\n\t(function (KeepAliveHandlerStates) {\n\t KeepAliveHandlerStates[KeepAliveHandlerStates[\"Paused\"] = 0] = \"Paused\";\n\t KeepAliveHandlerStates[KeepAliveHandlerStates[\"Running\"] = 1] = \"Running\";\n\t KeepAliveHandlerStates[KeepAliveHandlerStates[\"Closed\"] = 2] = \"Closed\";\n\t})(KeepAliveHandlerStates || (KeepAliveHandlerStates = {}));\n\tvar KeepAliveHandler = /** @class */ (function () {\n\t function KeepAliveHandler(connection, keepAliveTimeoutDuration) {\n\t this.connection = connection;\n\t this.keepAliveTimeoutDuration = keepAliveTimeoutDuration;\n\t this.state = KeepAliveHandlerStates.Paused;\n\t this.outbound = connection.multiplexerDemultiplexer.connectionOutbound;\n\t }\n\t KeepAliveHandler.prototype.handle = function (frame) {\n\t this.keepAliveLastReceivedMillis = Date.now();\n\t if (Frames_1.Flags.hasRespond(frame.flags)) {\n\t this.outbound.send({\n\t type: Frames_1.FrameTypes.KEEPALIVE,\n\t streamId: 0,\n\t data: frame.data,\n\t flags: frame.flags ^ Frames_1.Flags.RESPOND,\n\t lastReceivedPosition: 0,\n\t });\n\t }\n\t };\n\t KeepAliveHandler.prototype.start = function () {\n\t if (this.state !== KeepAliveHandlerStates.Paused) {\n\t return;\n\t }\n\t this.keepAliveLastReceivedMillis = Date.now();\n\t this.state = KeepAliveHandlerStates.Running;\n\t this.activeTimeout = setTimeout(this.timeoutCheck.bind(this), this.keepAliveTimeoutDuration);\n\t };\n\t KeepAliveHandler.prototype.pause = function () {\n\t if (this.state !== KeepAliveHandlerStates.Running) {\n\t return;\n\t }\n\t this.state = KeepAliveHandlerStates.Paused;\n\t clearTimeout(this.activeTimeout);\n\t };\n\t KeepAliveHandler.prototype.close = function () {\n\t this.state = KeepAliveHandlerStates.Closed;\n\t clearTimeout(this.activeTimeout);\n\t };\n\t KeepAliveHandler.prototype.timeoutCheck = function () {\n\t var now = Date.now();\n\t var noKeepAliveDuration = now - this.keepAliveLastReceivedMillis;\n\t if (noKeepAliveDuration >= this.keepAliveTimeoutDuration) {\n\t this.connection.close(new Error(\"No keep-alive acks for \".concat(this.keepAliveTimeoutDuration, \" millis\")));\n\t }\n\t else {\n\t this.activeTimeout = setTimeout(this.timeoutCheck.bind(this), Math.max(100, this.keepAliveTimeoutDuration - noKeepAliveDuration));\n\t }\n\t };\n\t return KeepAliveHandler;\n\t}());\n\tRSocketSupport.KeepAliveHandler = KeepAliveHandler;\n\tvar KeepAliveSenderStates;\n\t(function (KeepAliveSenderStates) {\n\t KeepAliveSenderStates[KeepAliveSenderStates[\"Paused\"] = 0] = \"Paused\";\n\t KeepAliveSenderStates[KeepAliveSenderStates[\"Running\"] = 1] = \"Running\";\n\t KeepAliveSenderStates[KeepAliveSenderStates[\"Closed\"] = 2] = \"Closed\";\n\t})(KeepAliveSenderStates || (KeepAliveSenderStates = {}));\n\tvar KeepAliveSender = /** @class */ (function () {\n\t function KeepAliveSender(outbound, keepAlivePeriodDuration) {\n\t this.outbound = outbound;\n\t this.keepAlivePeriodDuration = keepAlivePeriodDuration;\n\t this.state = KeepAliveSenderStates.Paused;\n\t }\n\t KeepAliveSender.prototype.sendKeepAlive = function () {\n\t this.outbound.send({\n\t type: Frames_1.FrameTypes.KEEPALIVE,\n\t streamId: 0,\n\t data: undefined,\n\t flags: Frames_1.Flags.RESPOND,\n\t lastReceivedPosition: 0,\n\t });\n\t };\n\t KeepAliveSender.prototype.start = function () {\n\t if (this.state !== KeepAliveSenderStates.Paused) {\n\t return;\n\t }\n\t this.state = KeepAliveSenderStates.Running;\n\t this.activeInterval = setInterval(this.sendKeepAlive.bind(this), this.keepAlivePeriodDuration);\n\t };\n\t KeepAliveSender.prototype.pause = function () {\n\t if (this.state !== KeepAliveSenderStates.Running) {\n\t return;\n\t }\n\t this.state = KeepAliveSenderStates.Paused;\n\t clearInterval(this.activeInterval);\n\t };\n\t KeepAliveSender.prototype.close = function () {\n\t this.state = KeepAliveSenderStates.Closed;\n\t clearInterval(this.activeInterval);\n\t };\n\t return KeepAliveSender;\n\t}());\n\tRSocketSupport.KeepAliveSender = KeepAliveSender;\n\t\n\treturn RSocketSupport;\n}\n\nvar Resume = {};\n\nvar hasRequiredResume;\n\nfunction requireResume () {\n\tif (hasRequiredResume) return Resume;\n\thasRequiredResume = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __values = (Resume && Resume.__values) || function(o) {\n\t var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n\t if (m) return m.call(o);\n\t if (o && typeof o.length === \"number\") return {\n\t next: function () {\n\t if (o && i >= o.length) o = void 0;\n\t return { value: o && o[i++], done: !o };\n\t }\n\t };\n\t throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n\t};\n\tObject.defineProperty(Resume, \"__esModule\", { value: true });\n\tResume.FrameStore = void 0;\n\tvar _1 = requireDist();\n\tvar Codecs_1 = requireCodecs();\n\tvar FrameStore = /** @class */ (function () {\n\t function FrameStore() {\n\t this.storedFrames = [];\n\t this._lastReceivedFramePosition = 0;\n\t this._firstAvailableFramePosition = 0;\n\t this._lastSentFramePosition = 0;\n\t }\n\t Object.defineProperty(FrameStore.prototype, \"lastReceivedFramePosition\", {\n\t get: function () {\n\t return this._lastReceivedFramePosition;\n\t },\n\t enumerable: false,\n\t configurable: true\n\t });\n\t Object.defineProperty(FrameStore.prototype, \"firstAvailableFramePosition\", {\n\t get: function () {\n\t return this._firstAvailableFramePosition;\n\t },\n\t enumerable: false,\n\t configurable: true\n\t });\n\t Object.defineProperty(FrameStore.prototype, \"lastSentFramePosition\", {\n\t get: function () {\n\t return this._lastSentFramePosition;\n\t },\n\t enumerable: false,\n\t configurable: true\n\t });\n\t FrameStore.prototype.store = function (frame) {\n\t this._lastSentFramePosition += (0, Codecs_1.sizeOfFrame)(frame);\n\t this.storedFrames.push(frame);\n\t };\n\t FrameStore.prototype.record = function (frame) {\n\t this._lastReceivedFramePosition += (0, Codecs_1.sizeOfFrame)(frame);\n\t };\n\t FrameStore.prototype.dropTo = function (lastReceivedPosition) {\n\t var bytesToDrop = lastReceivedPosition - this._firstAvailableFramePosition;\n\t while (bytesToDrop > 0 && this.storedFrames.length > 0) {\n\t var storedFrame = this.storedFrames.shift();\n\t bytesToDrop -= (0, Codecs_1.sizeOfFrame)(storedFrame);\n\t }\n\t if (bytesToDrop !== 0) {\n\t throw new _1.RSocketError(_1.ErrorCodes.CONNECTION_ERROR, \"State inconsistency. Expected bytes to drop \".concat(lastReceivedPosition - this._firstAvailableFramePosition, \" but actual \").concat(bytesToDrop));\n\t }\n\t this._firstAvailableFramePosition = lastReceivedPosition;\n\t };\n\t FrameStore.prototype.drain = function (consumer) {\n\t var e_1, _a;\n\t try {\n\t for (var _b = __values(this.storedFrames), _c = _b.next(); !_c.done; _c = _b.next()) {\n\t var frame = _c.value;\n\t consumer(frame);\n\t }\n\t }\n\t catch (e_1_1) { e_1 = { error: e_1_1 }; }\n\t finally {\n\t try {\n\t if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n\t }\n\t finally { if (e_1) throw e_1.error; }\n\t }\n\t };\n\t return FrameStore;\n\t}());\n\tResume.FrameStore = FrameStore;\n\t\n\treturn Resume;\n}\n\nvar hasRequiredRSocketConnector;\n\nfunction requireRSocketConnector () {\n\tif (hasRequiredRSocketConnector) return RSocketConnector;\n\thasRequiredRSocketConnector = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __awaiter = (RSocketConnector && RSocketConnector.__awaiter) || function (thisArg, _arguments, P, generator) {\n\t function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n\t return new (P || (P = Promise))(function (resolve, reject) {\n\t function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n\t function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n\t function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n\t step((generator = generator.apply(thisArg, _arguments || [])).next());\n\t });\n\t};\n\tvar __generator = (RSocketConnector && RSocketConnector.__generator) || function (thisArg, body) {\n\t var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n\t return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n\t function verb(n) { return function (v) { return step([n, v]); }; }\n\t function step(op) {\n\t if (f) throw new TypeError(\"Generator is already executing.\");\n\t while (_) try {\n\t if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n\t if (y = 0, t) op = [op[0] & 2, t.value];\n\t switch (op[0]) {\n\t case 0: case 1: t = op; break;\n\t case 4: _.label++; return { value: op[1], done: false };\n\t case 5: _.label++; y = op[1]; op = [0]; continue;\n\t case 7: op = _.ops.pop(); _.trys.pop(); continue;\n\t default:\n\t if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n\t if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n\t if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n\t if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n\t if (t[2]) _.ops.pop();\n\t _.trys.pop(); continue;\n\t }\n\t op = body.call(thisArg, _);\n\t } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n\t if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n\t }\n\t};\n\tObject.defineProperty(RSocketConnector, \"__esModule\", { value: true });\n\tRSocketConnector.RSocketConnector = void 0;\n\tvar ClientServerMultiplexerDemultiplexer_1 = requireClientServerMultiplexerDemultiplexer();\n\tvar Frames_1 = requireFrames();\n\tvar RSocketSupport_1 = requireRSocketSupport();\n\tvar Resume_1 = requireResume();\n\tvar RSocketConnector$1 = /** @class */ (function () {\n\t function RSocketConnector(config) {\n\t this.config = config;\n\t }\n\t RSocketConnector.prototype.connect = function () {\n\t var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;\n\t return __awaiter(this, void 0, void 0, function () {\n\t var config, setupFrame, connection, keepAliveSender, keepAliveHandler, leaseHandler, responder, connectionFrameHandler, streamsHandler;\n\t var _this = this;\n\t return __generator(this, function (_w) {\n\t switch (_w.label) {\n\t case 0:\n\t config = this.config;\n\t setupFrame = {\n\t type: Frames_1.FrameTypes.SETUP,\n\t dataMimeType: (_b = (_a = config.setup) === null || _a === void 0 ? void 0 : _a.dataMimeType) !== null && _b !== void 0 ? _b : \"application/octet-stream\",\n\t metadataMimeType: (_d = (_c = config.setup) === null || _c === void 0 ? void 0 : _c.metadataMimeType) !== null && _d !== void 0 ? _d : \"application/octet-stream\",\n\t keepAlive: (_f = (_e = config.setup) === null || _e === void 0 ? void 0 : _e.keepAlive) !== null && _f !== void 0 ? _f : 60000,\n\t lifetime: (_h = (_g = config.setup) === null || _g === void 0 ? void 0 : _g.lifetime) !== null && _h !== void 0 ? _h : 300000,\n\t metadata: (_k = (_j = config.setup) === null || _j === void 0 ? void 0 : _j.payload) === null || _k === void 0 ? void 0 : _k.metadata,\n\t data: (_m = (_l = config.setup) === null || _l === void 0 ? void 0 : _l.payload) === null || _m === void 0 ? void 0 : _m.data,\n\t resumeToken: (_p = (_o = config.resume) === null || _o === void 0 ? void 0 : _o.tokenGenerator()) !== null && _p !== void 0 ? _p : null,\n\t streamId: 0,\n\t majorVersion: 1,\n\t minorVersion: 0,\n\t flags: (((_r = (_q = config.setup) === null || _q === void 0 ? void 0 : _q.payload) === null || _r === void 0 ? void 0 : _r.metadata) ? Frames_1.Flags.METADATA : Frames_1.Flags.NONE) |\n\t (config.lease ? Frames_1.Flags.LEASE : Frames_1.Flags.NONE) |\n\t (config.resume ? Frames_1.Flags.RESUME_ENABLE : Frames_1.Flags.NONE),\n\t };\n\t return [4 /*yield*/, config.transport.connect(function (outbound) {\n\t return config.resume\n\t ? new ClientServerMultiplexerDemultiplexer_1.ResumableClientServerInputMultiplexerDemultiplexer(ClientServerMultiplexerDemultiplexer_1.StreamIdGenerator.create(-1), outbound, outbound, new Resume_1.FrameStore(), // TODO: add size control\n\t setupFrame.resumeToken.toString(), function (self, frameStore) { return __awaiter(_this, void 0, void 0, function () {\n\t var multiplexerDemultiplexerProvider, reconnectionAttempts, reconnector;\n\t return __generator(this, function (_a) {\n\t switch (_a.label) {\n\t case 0:\n\t multiplexerDemultiplexerProvider = function (outbound) {\n\t outbound.send({\n\t type: Frames_1.FrameTypes.RESUME,\n\t streamId: 0,\n\t flags: Frames_1.Flags.NONE,\n\t clientPosition: frameStore.firstAvailableFramePosition,\n\t serverPosition: frameStore.lastReceivedFramePosition,\n\t majorVersion: setupFrame.minorVersion,\n\t minorVersion: setupFrame.majorVersion,\n\t resumeToken: setupFrame.resumeToken,\n\t });\n\t return new ClientServerMultiplexerDemultiplexer_1.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer(outbound, outbound, self);\n\t };\n\t reconnectionAttempts = -1;\n\t reconnector = function () {\n\t reconnectionAttempts++;\n\t return config.resume\n\t .reconnectFunction(reconnectionAttempts)\n\t .then(function () {\n\t return config.transport\n\t .connect(multiplexerDemultiplexerProvider)\n\t .catch(reconnector);\n\t });\n\t };\n\t return [4 /*yield*/, reconnector()];\n\t case 1:\n\t _a.sent();\n\t return [2 /*return*/];\n\t }\n\t });\n\t }); })\n\t : new ClientServerMultiplexerDemultiplexer_1.ClientServerInputMultiplexerDemultiplexer(ClientServerMultiplexerDemultiplexer_1.StreamIdGenerator.create(-1), outbound, outbound);\n\t })];\n\t case 1:\n\t connection = _w.sent();\n\t keepAliveSender = new RSocketSupport_1.KeepAliveSender(connection.multiplexerDemultiplexer.connectionOutbound, setupFrame.keepAlive);\n\t keepAliveHandler = new RSocketSupport_1.KeepAliveHandler(connection, setupFrame.lifetime);\n\t leaseHandler = config.lease\n\t ? new RSocketSupport_1.LeaseHandler((_s = config.lease.maxPendingRequests) !== null && _s !== void 0 ? _s : 256, connection.multiplexerDemultiplexer)\n\t : undefined;\n\t responder = (_t = config.responder) !== null && _t !== void 0 ? _t : {};\n\t connectionFrameHandler = new RSocketSupport_1.DefaultConnectionFrameHandler(connection, keepAliveHandler, keepAliveSender, leaseHandler, responder);\n\t streamsHandler = new RSocketSupport_1.DefaultStreamRequestHandler(responder, 0);\n\t connection.onClose(function (e) {\n\t keepAliveSender.close();\n\t keepAliveHandler.close();\n\t connectionFrameHandler.close(e);\n\t });\n\t connection.multiplexerDemultiplexer.connectionInbound(connectionFrameHandler);\n\t connection.multiplexerDemultiplexer.handleRequestStream(streamsHandler);\n\t connection.multiplexerDemultiplexer.connectionOutbound.send(setupFrame);\n\t keepAliveHandler.start();\n\t keepAliveSender.start();\n\t return [2 /*return*/, new RSocketSupport_1.RSocketRequester(connection, (_v = (_u = config.fragmentation) === null || _u === void 0 ? void 0 : _u.maxOutboundFragmentSize) !== null && _v !== void 0 ? _v : 0, leaseHandler)];\n\t }\n\t });\n\t });\n\t };\n\t return RSocketConnector;\n\t}());\n\tRSocketConnector.RSocketConnector = RSocketConnector$1;\n\t\n\treturn RSocketConnector;\n}\n\nvar RSocketServer = {};\n\nvar hasRequiredRSocketServer;\n\nfunction requireRSocketServer () {\n\tif (hasRequiredRSocketServer) return RSocketServer;\n\thasRequiredRSocketServer = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __awaiter = (RSocketServer && RSocketServer.__awaiter) || function (thisArg, _arguments, P, generator) {\n\t function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n\t return new (P || (P = Promise))(function (resolve, reject) {\n\t function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n\t function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n\t function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n\t step((generator = generator.apply(thisArg, _arguments || [])).next());\n\t });\n\t};\n\tvar __generator = (RSocketServer && RSocketServer.__generator) || function (thisArg, body) {\n\t var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n\t return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n\t function verb(n) { return function (v) { return step([n, v]); }; }\n\t function step(op) {\n\t if (f) throw new TypeError(\"Generator is already executing.\");\n\t while (_) try {\n\t if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n\t if (y = 0, t) op = [op[0] & 2, t.value];\n\t switch (op[0]) {\n\t case 0: case 1: t = op; break;\n\t case 4: _.label++; return { value: op[1], done: false };\n\t case 5: _.label++; y = op[1]; op = [0]; continue;\n\t case 7: op = _.ops.pop(); _.trys.pop(); continue;\n\t default:\n\t if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n\t if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n\t if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n\t if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n\t if (t[2]) _.ops.pop();\n\t _.trys.pop(); continue;\n\t }\n\t op = body.call(thisArg, _);\n\t } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n\t if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n\t }\n\t};\n\tObject.defineProperty(RSocketServer, \"__esModule\", { value: true });\n\tRSocketServer.RSocketServer = void 0;\n\tvar ClientServerMultiplexerDemultiplexer_1 = requireClientServerMultiplexerDemultiplexer();\n\tvar Errors_1 = requireErrors();\n\tvar Frames_1 = requireFrames();\n\tvar RSocketSupport_1 = requireRSocketSupport();\n\tvar Resume_1 = requireResume();\n\tvar RSocketServer$1 = /** @class */ (function () {\n\t function RSocketServer(config) {\n\t var _a, _b;\n\t this.acceptor = config.acceptor;\n\t this.transport = config.transport;\n\t this.lease = config.lease;\n\t this.serverSideKeepAlive = config.serverSideKeepAlive;\n\t this.sessionStore = config.resume ? {} : undefined;\n\t this.sessionTimeout = (_b = (_a = config.resume) === null || _a === void 0 ? void 0 : _a.sessionTimeout) !== null && _b !== void 0 ? _b : undefined;\n\t }\n\t RSocketServer.prototype.bind = function () {\n\t return __awaiter(this, void 0, void 0, function () {\n\t var _this = this;\n\t return __generator(this, function (_a) {\n\t switch (_a.label) {\n\t case 0: return [4 /*yield*/, this.transport.bind(function (frame, connection) { return __awaiter(_this, void 0, void 0, function () {\n\t var _a, error, error, leaseHandler, requester, responder, keepAliveHandler_1, keepAliveSender_1, connectionFrameHandler_1, streamsHandler, e_1;\n\t var _b, _c, _d, _e;\n\t return __generator(this, function (_f) {\n\t switch (_f.label) {\n\t case 0:\n\t _a = frame.type;\n\t switch (_a) {\n\t case Frames_1.FrameTypes.SETUP: return [3 /*break*/, 1];\n\t case Frames_1.FrameTypes.RESUME: return [3 /*break*/, 5];\n\t }\n\t return [3 /*break*/, 6];\n\t case 1:\n\t _f.trys.push([1, 3, , 4]);\n\t if (this.lease && !Frames_1.Flags.hasLease(frame.flags)) {\n\t error = new Errors_1.RSocketError(Errors_1.ErrorCodes.REJECTED_SETUP, \"Lease has to be enabled\");\n\t connection.multiplexerDemultiplexer.connectionOutbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t flags: Frames_1.Flags.NONE,\n\t code: error.code,\n\t message: error.message,\n\t });\n\t connection.close(error);\n\t return [2 /*return*/];\n\t }\n\t if (Frames_1.Flags.hasLease(frame.flags) && !this.lease) {\n\t error = new Errors_1.RSocketError(Errors_1.ErrorCodes.REJECTED_SETUP, \"Lease has to be disabled\");\n\t connection.multiplexerDemultiplexer.connectionOutbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t flags: Frames_1.Flags.NONE,\n\t code: error.code,\n\t message: error.message,\n\t });\n\t connection.close(error);\n\t return [2 /*return*/];\n\t }\n\t leaseHandler = Frames_1.Flags.hasLease(frame.flags)\n\t ? new RSocketSupport_1.LeaseHandler((_b = this.lease.maxPendingRequests) !== null && _b !== void 0 ? _b : 256, connection.multiplexerDemultiplexer)\n\t : undefined;\n\t requester = new RSocketSupport_1.RSocketRequester(connection, (_d = (_c = this.fragmentation) === null || _c === void 0 ? void 0 : _c.maxOutboundFragmentSize) !== null && _d !== void 0 ? _d : 0, leaseHandler);\n\t return [4 /*yield*/, this.acceptor.accept({\n\t data: frame.data,\n\t dataMimeType: frame.dataMimeType,\n\t metadata: frame.metadata,\n\t metadataMimeType: frame.metadataMimeType,\n\t flags: frame.flags,\n\t keepAliveMaxLifetime: frame.lifetime,\n\t keepAliveInterval: frame.keepAlive,\n\t resumeToken: frame.resumeToken,\n\t }, requester)];\n\t case 2:\n\t responder = _f.sent();\n\t keepAliveHandler_1 = new RSocketSupport_1.KeepAliveHandler(connection, frame.lifetime);\n\t keepAliveSender_1 = this.serverSideKeepAlive\n\t ? new RSocketSupport_1.KeepAliveSender(connection.multiplexerDemultiplexer.connectionOutbound, frame.keepAlive)\n\t : undefined;\n\t connectionFrameHandler_1 = new RSocketSupport_1.DefaultConnectionFrameHandler(connection, keepAliveHandler_1, keepAliveSender_1, leaseHandler, responder);\n\t streamsHandler = new RSocketSupport_1.DefaultStreamRequestHandler(responder, 0);\n\t connection.onClose(function (e) {\n\t keepAliveSender_1 === null || keepAliveSender_1 === void 0 ? void 0 : keepAliveSender_1.close();\n\t keepAliveHandler_1.close();\n\t connectionFrameHandler_1.close(e);\n\t });\n\t connection.multiplexerDemultiplexer.connectionInbound(connectionFrameHandler_1);\n\t connection.multiplexerDemultiplexer.handleRequestStream(streamsHandler);\n\t keepAliveHandler_1.start();\n\t keepAliveSender_1 === null || keepAliveSender_1 === void 0 ? void 0 : keepAliveSender_1.start();\n\t return [3 /*break*/, 4];\n\t case 3:\n\t e_1 = _f.sent();\n\t connection.multiplexerDemultiplexer.connectionOutbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t code: Errors_1.ErrorCodes.REJECTED_SETUP,\n\t message: (_e = e_1.message) !== null && _e !== void 0 ? _e : \"\",\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t connection.close(e_1 instanceof Errors_1.RSocketError\n\t ? e_1\n\t : new Errors_1.RSocketError(Errors_1.ErrorCodes.REJECTED_SETUP, e_1.message));\n\t return [3 /*break*/, 4];\n\t case 4: return [2 /*return*/];\n\t case 5:\n\t {\n\t // frame should be handled earlier\n\t return [2 /*return*/];\n\t }\n\t case 6:\n\t {\n\t connection.multiplexerDemultiplexer.connectionOutbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t code: Errors_1.ErrorCodes.UNSUPPORTED_SETUP,\n\t message: \"Unsupported setup\",\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t connection.close(new Errors_1.RSocketError(Errors_1.ErrorCodes.UNSUPPORTED_SETUP));\n\t }\n\t _f.label = 7;\n\t case 7: return [2 /*return*/];\n\t }\n\t });\n\t }); }, function (frame, outbound) {\n\t if (frame.type === Frames_1.FrameTypes.RESUME) {\n\t if (_this.sessionStore) {\n\t var multiplexerDemultiplexer = _this.sessionStore[frame.resumeToken.toString()];\n\t if (!multiplexerDemultiplexer) {\n\t outbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t code: Errors_1.ErrorCodes.REJECTED_RESUME,\n\t message: \"No session found for the given resume token\",\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t outbound.close();\n\t return;\n\t }\n\t multiplexerDemultiplexer.resume(frame, outbound, outbound);\n\t return multiplexerDemultiplexer;\n\t }\n\t outbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t code: Errors_1.ErrorCodes.REJECTED_RESUME,\n\t message: \"Resume is not enabled\",\n\t flags: Frames_1.Flags.NONE,\n\t });\n\t outbound.close();\n\t return;\n\t }\n\t else if (frame.type === Frames_1.FrameTypes.SETUP) {\n\t if (Frames_1.Flags.hasResume(frame.flags)) {\n\t if (!_this.sessionStore) {\n\t var error = new Errors_1.RSocketError(Errors_1.ErrorCodes.REJECTED_SETUP, \"No resume support\");\n\t outbound.send({\n\t type: Frames_1.FrameTypes.ERROR,\n\t streamId: 0,\n\t flags: Frames_1.Flags.NONE,\n\t code: error.code,\n\t message: error.message,\n\t });\n\t outbound.close(error);\n\t return;\n\t }\n\t var multiplexerDumiltiplexer = new ClientServerMultiplexerDemultiplexer_1.ResumableClientServerInputMultiplexerDemultiplexer(ClientServerMultiplexerDemultiplexer_1.StreamIdGenerator.create(0), outbound, outbound, new Resume_1.FrameStore(), // TODO: add size parameter\n\t frame.resumeToken.toString(), _this.sessionStore, _this.sessionTimeout);\n\t _this.sessionStore[frame.resumeToken.toString()] =\n\t multiplexerDumiltiplexer;\n\t return multiplexerDumiltiplexer;\n\t }\n\t }\n\t return new ClientServerMultiplexerDemultiplexer_1.ClientServerInputMultiplexerDemultiplexer(ClientServerMultiplexerDemultiplexer_1.StreamIdGenerator.create(0), outbound, outbound);\n\t })];\n\t case 1: return [2 /*return*/, _a.sent()];\n\t }\n\t });\n\t });\n\t };\n\t return RSocketServer;\n\t}());\n\tRSocketServer.RSocketServer = RSocketServer$1;\n\t\n\treturn RSocketServer;\n}\n\nvar Transport = {};\n\nvar hasRequiredTransport;\n\nfunction requireTransport () {\n\tif (hasRequiredTransport) return Transport;\n\thasRequiredTransport = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tObject.defineProperty(Transport, \"__esModule\", { value: true });\n\t\n\treturn Transport;\n}\n\nvar hasRequiredDist;\n\nfunction requireDist () {\n\tif (hasRequiredDist) return dist;\n\thasRequiredDist = 1;\n\t(function (exports$1) {\n\t\t/*\n\t\t * Copyright 2021-2022 the original author or authors.\n\t\t *\n\t\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t\t * you may not use this file except in compliance with the License.\n\t\t * You may obtain a copy of the License at\n\t\t *\n\t\t * http://www.apache.org/licenses/LICENSE-2.0\n\t\t *\n\t\t * Unless required by applicable law or agreed to in writing, software\n\t\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t\t * See the License for the specific language governing permissions and\n\t\t * limitations under the License.\n\t\t */\n\t\tvar __createBinding = (dist && dist.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n\t\t if (k2 === undefined) k2 = k;\n\t\t Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n\t\t}) : (function(o, m, k, k2) {\n\t\t if (k2 === undefined) k2 = k;\n\t\t o[k2] = m[k];\n\t\t}));\n\t\tvar __exportStar = (dist && dist.__exportStar) || function(m, exports$1) {\n\t\t for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);\n\t\t};\n\t\tObject.defineProperty(exports$1, \"__esModule\", { value: true });\n\t\t__exportStar(requireCodecs(), exports$1);\n\t\t__exportStar(requireCommon(), exports$1);\n\t\t__exportStar(requireDeferred(), exports$1);\n\t\t__exportStar(requireErrors(), exports$1);\n\t\t__exportStar(requireFrames(), exports$1);\n\t\t__exportStar(requireRSocket(), exports$1);\n\t\t__exportStar(requireRSocketConnector(), exports$1);\n\t\t__exportStar(requireRSocketServer(), exports$1);\n\t\t__exportStar(requireTransport(), exports$1);\n\t\t\n\t} (dist));\n\treturn dist;\n}\n\nvar distExports = requireDist();\n\nvar version = \"1.48.0\";\nvar PACKAGE = {\n\tversion: version};\n\nconst DEFAULT_PRESSURE_LIMITS = {\n highWater: 10,\n lowWater: 0\n};\n/**\n * A very basic implementation of a data stream with backpressure support which does not use\n * native JS streams or async iterators.\n * This is handy for environments such as React Native which need polyfills for the above.\n */\nclass DataStream extends BaseObserver {\n options;\n dataQueue;\n isClosed;\n processingPromise;\n notifyDataAdded;\n logger;\n mapLine;\n constructor(options) {\n super();\n this.options = options;\n this.processingPromise = null;\n this.isClosed = false;\n this.dataQueue = [];\n this.mapLine = options?.mapLine ?? ((line) => line);\n this.logger = options?.logger ?? Logger.get('DataStream');\n if (options?.closeOnError) {\n const l = this.registerListener({\n error: (ex) => {\n l?.();\n this.close();\n }\n });\n }\n }\n get highWatermark() {\n return this.options?.pressure?.highWaterMark ?? DEFAULT_PRESSURE_LIMITS.highWater;\n }\n get lowWatermark() {\n return this.options?.pressure?.lowWaterMark ?? DEFAULT_PRESSURE_LIMITS.lowWater;\n }\n get closed() {\n return this.isClosed;\n }\n async close() {\n this.isClosed = true;\n await this.processingPromise;\n this.iterateListeners((l) => l.closed?.());\n // Discard any data in the queue\n this.dataQueue = [];\n this.listeners.clear();\n }\n /**\n * Enqueues data for the consumers to read\n */\n enqueueData(data) {\n if (this.isClosed) {\n throw new Error('Cannot enqueue data into closed stream.');\n }\n this.dataQueue.push(data);\n this.notifyDataAdded?.();\n this.processQueue();\n }\n /**\n * Reads data once from the data stream\n * @returns a Data payload or Null if the stream closed.\n */\n async read() {\n if (this.closed) {\n return null;\n }\n // Wait for any pending processing to complete first.\n // This ensures we register our listener before calling processQueue(),\n // avoiding a race where processQueue() sees no reader and returns early.\n if (this.processingPromise) {\n await this.processingPromise;\n }\n // Re-check after await - stream may have closed while we were waiting\n if (this.closed) {\n return null;\n }\n return new Promise((resolve, reject) => {\n const l = this.registerListener({\n data: async (data) => {\n resolve(data);\n // Remove the listener\n l?.();\n },\n closed: () => {\n resolve(null);\n l?.();\n },\n error: (ex) => {\n reject(ex);\n l?.();\n }\n });\n this.processQueue();\n });\n }\n /**\n * Executes a callback for each data item in the stream\n */\n forEach(callback) {\n if (this.dataQueue.length <= this.lowWatermark) {\n this.iterateAsyncErrored(async (l) => l.lowWater?.());\n }\n return this.registerListener({\n data: callback\n });\n }\n processQueue() {\n if (this.processingPromise) {\n return;\n }\n const promise = (this.processingPromise = this._processQueue());\n promise.finally(() => {\n this.processingPromise = null;\n });\n return promise;\n }\n hasDataReader() {\n return Array.from(this.listeners.values()).some((l) => !!l.data);\n }\n async _processQueue() {\n /**\n * Allow listeners to mutate the queue before processing.\n * This allows for operations such as dropping or compressing data\n * on high water or requesting more data on low water.\n */\n if (this.dataQueue.length >= this.highWatermark) {\n await this.iterateAsyncErrored(async (l) => l.highWater?.());\n }\n if (this.isClosed || !this.hasDataReader()) {\n return;\n }\n if (this.dataQueue.length) {\n const data = this.dataQueue.shift();\n const mapped = this.mapLine(data);\n await this.iterateAsyncErrored(async (l) => l.data?.(mapped));\n }\n if (this.dataQueue.length <= this.lowWatermark) {\n const dataAdded = new Promise((resolve) => {\n this.notifyDataAdded = resolve;\n });\n await Promise.race([this.iterateAsyncErrored(async (l) => l.lowWater?.()), dataAdded]);\n this.notifyDataAdded = null;\n }\n if (this.dataQueue.length > 0) {\n setTimeout(() => this.processQueue());\n }\n }\n async iterateAsyncErrored(cb) {\n // Important: We need to copy the listeners, as calling a listener could result in adding another\n // listener, resulting in infinite loops.\n const listeners = Array.from(this.listeners.values());\n for (let i of listeners) {\n try {\n await cb(i);\n }\n catch (ex) {\n this.logger.error(ex);\n this.iterateListeners((l) => l.error?.(ex));\n }\n }\n }\n}\n\nvar WebsocketDuplexConnection = {};\n\nvar hasRequiredWebsocketDuplexConnection;\n\nfunction requireWebsocketDuplexConnection () {\n\tif (hasRequiredWebsocketDuplexConnection) return WebsocketDuplexConnection;\n\thasRequiredWebsocketDuplexConnection = 1;\n\t/*\n\t * Copyright 2021-2022 the original author or authors.\n\t *\n\t * Licensed under the Apache License, Version 2.0 (the \"License\");\n\t * you may not use this file except in compliance with the License.\n\t * You may obtain a copy of the License at\n\t *\n\t * http://www.apache.org/licenses/LICENSE-2.0\n\t *\n\t * Unless required by applicable law or agreed to in writing, software\n\t * distributed under the License is distributed on an \"AS IS\" BASIS,\n\t * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\t * See the License for the specific language governing permissions and\n\t * limitations under the License.\n\t */\n\tvar __extends = (WebsocketDuplexConnection && WebsocketDuplexConnection.__extends) || (function () {\n\t var extendStatics = function (d, b) {\n\t extendStatics = Object.setPrototypeOf ||\n\t ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n\t function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n\t return extendStatics(d, b);\n\t };\n\t return function (d, b) {\n\t if (typeof b !== \"function\" && b !== null)\n\t throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n\t extendStatics(d, b);\n\t function __() { this.constructor = d; }\n\t d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n\t };\n\t})();\n\tObject.defineProperty(WebsocketDuplexConnection, \"__esModule\", { value: true });\n\tWebsocketDuplexConnection.WebsocketDuplexConnection = void 0;\n\tvar rsocket_core_1 = requireDist();\n\tvar WebsocketDuplexConnection$1 = /** @class */ (function (_super) {\n\t __extends(WebsocketDuplexConnection, _super);\n\t function WebsocketDuplexConnection(websocket, deserializer, multiplexerDemultiplexerFactory) {\n\t var _this = _super.call(this) || this;\n\t _this.websocket = websocket;\n\t _this.deserializer = deserializer;\n\t _this.handleClosed = function (e) {\n\t _this.close(new Error(e.reason || \"WebsocketDuplexConnection: Socket closed unexpectedly.\"));\n\t };\n\t _this.handleError = function (e) {\n\t _this.close(e.error);\n\t };\n\t _this.handleMessage = function (message) {\n\t try {\n\t var buffer = bufferExports.Buffer.from(message.data);\n\t var frame = _this.deserializer.deserializeFrame(buffer);\n\t _this.multiplexerDemultiplexer.handle(frame);\n\t }\n\t catch (error) {\n\t _this.close(error);\n\t }\n\t };\n\t websocket.addEventListener(\"close\", _this.handleClosed);\n\t websocket.addEventListener(\"error\", _this.handleError);\n\t websocket.addEventListener(\"message\", _this.handleMessage);\n\t _this.multiplexerDemultiplexer = multiplexerDemultiplexerFactory(_this);\n\t return _this;\n\t }\n\t Object.defineProperty(WebsocketDuplexConnection.prototype, \"availability\", {\n\t get: function () {\n\t return this.done ? 0 : 1;\n\t },\n\t enumerable: false,\n\t configurable: true\n\t });\n\t WebsocketDuplexConnection.prototype.close = function (error) {\n\t if (this.done) {\n\t _super.prototype.close.call(this, error);\n\t return;\n\t }\n\t this.websocket.removeEventListener(\"close\", this.handleClosed);\n\t this.websocket.removeEventListener(\"error\", this.handleError);\n\t this.websocket.removeEventListener(\"message\", this.handleMessage);\n\t this.websocket.close();\n\t delete this.websocket;\n\t _super.prototype.close.call(this, error);\n\t };\n\t WebsocketDuplexConnection.prototype.send = function (frame) {\n\t if (this.done) {\n\t return;\n\t }\n\t var buffer = (0, rsocket_core_1.serializeFrame)(frame);\n\t this.websocket.send(buffer);\n\t };\n\t return WebsocketDuplexConnection;\n\t}(rsocket_core_1.Deferred));\n\tWebsocketDuplexConnection.WebsocketDuplexConnection = WebsocketDuplexConnection$1;\n\t\n\treturn WebsocketDuplexConnection;\n}\n\nvar WebsocketDuplexConnectionExports = requireWebsocketDuplexConnection();\n\n/**\n * Adapted from rsocket-websocket-client\n * https://github.com/rsocket/rsocket-js/blob/e224cf379e747c4f1ddc4f2fa111854626cc8575/packages/rsocket-websocket-client/src/WebsocketClientTransport.ts#L17\n * This adds additional error handling for React Native iOS.\n * This particularly adds a close listener to handle cases where the WebSocket\n * connection closes immediately after opening without emitting an error.\n */\nclass WebsocketClientTransport {\n url;\n factory;\n constructor(options) {\n this.url = options.url;\n this.factory = options.wsCreator ?? ((url) => new WebSocket(url));\n }\n connect(multiplexerDemultiplexerFactory) {\n return new Promise((resolve, reject) => {\n const websocket = this.factory(this.url);\n websocket.binaryType = 'arraybuffer';\n let removeListeners;\n const openListener = () => {\n removeListeners();\n resolve(new WebsocketDuplexConnectionExports.WebsocketDuplexConnection(websocket, new distExports.Deserializer(), multiplexerDemultiplexerFactory));\n };\n const errorListener = (ev) => {\n removeListeners();\n // We add a default error in that case.\n if (ev.error != null) {\n // undici typically provides an error object\n reject(ev.error);\n }\n else if (ev.message != null) {\n // React Native typically does not provide an error object, but does provide a message\n reject(new Error(`Failed to create websocket connection: ${ev.message}`));\n }\n else {\n // Browsers often provide no details at all\n reject(new Error(`Failed to create websocket connection to ${this.url}`));\n }\n };\n /**\n * In some cases, such as React Native iOS, the WebSocket connection may close immediately after opening\n * without and error. In such cases, we need to handle the close event to reject the promise.\n */\n const closeListener = () => {\n removeListeners();\n reject(new Error('WebSocket connection closed while opening'));\n };\n removeListeners = () => {\n websocket.removeEventListener('open', openListener);\n websocket.removeEventListener('error', errorListener);\n websocket.removeEventListener('close', closeListener);\n };\n websocket.addEventListener('open', openListener);\n websocket.addEventListener('error', errorListener);\n websocket.addEventListener('close', closeListener);\n });\n }\n}\n\nconst POWERSYNC_TRAILING_SLASH_MATCH = /\\/+$/;\nconst POWERSYNC_JS_VERSION = PACKAGE.version;\nconst SYNC_QUEUE_REQUEST_LOW_WATER = 5;\n// Keep alive message is sent every period\nconst KEEP_ALIVE_MS = 20_000;\n// One message of any type must be received in this period.\nconst SOCKET_TIMEOUT_MS = 30_000;\n// One keepalive message must be received in this period.\n// If there is a backlog of messages (for example on slow connections), keepalive messages could be delayed\n// significantly. Therefore this is longer than the socket timeout.\nconst KEEP_ALIVE_LIFETIME_MS = 90_000;\nconst DEFAULT_REMOTE_LOGGER = Logger.get('PowerSyncRemote');\nvar FetchStrategy;\n(function (FetchStrategy) {\n /**\n * Queues multiple sync events before processing, reducing round-trips.\n * This comes at the cost of more processing overhead, which may cause ACK timeouts on older/weaker devices for big enough datasets.\n */\n FetchStrategy[\"Buffered\"] = \"buffered\";\n /**\n * Processes each sync event immediately before requesting the next.\n * This reduces processing overhead and improves real-time responsiveness.\n */\n FetchStrategy[\"Sequential\"] = \"sequential\";\n})(FetchStrategy || (FetchStrategy = {}));\n/**\n * Class wrapper for providing a fetch implementation.\n * The class wrapper is used to distinguish the fetchImplementation\n * option in [AbstractRemoteOptions] from the general fetch method\n * which is typeof \"function\"\n */\nclass FetchImplementationProvider {\n getFetch() {\n throw new Error('Unspecified fetch implementation');\n }\n}\nconst DEFAULT_REMOTE_OPTIONS = {\n socketUrlTransformer: (url) => url.replace(/^https?:\\/\\//, function (match) {\n return match === 'https://' ? 'wss://' : 'ws://';\n }),\n fetchImplementation: new FetchImplementationProvider(),\n fetchOptions: {}\n};\nclass AbstractRemote {\n connector;\n logger;\n credentials = null;\n options;\n constructor(connector, logger = DEFAULT_REMOTE_LOGGER, options) {\n this.connector = connector;\n this.logger = logger;\n this.options = {\n ...DEFAULT_REMOTE_OPTIONS,\n ...(options ?? {})\n };\n }\n /**\n * @returns a fetch implementation (function)\n * which can be called to perform fetch requests\n */\n get fetch() {\n const { fetchImplementation } = this.options;\n return fetchImplementation instanceof FetchImplementationProvider\n ? fetchImplementation.getFetch()\n : fetchImplementation;\n }\n /**\n * Get credentials currently cached, or fetch new credentials if none are\n * available.\n *\n * These credentials may have expired already.\n */\n async getCredentials() {\n if (this.credentials) {\n return this.credentials;\n }\n return this.prefetchCredentials();\n }\n /**\n * Fetch a new set of credentials and cache it.\n *\n * Until this call succeeds, `getCredentials` will still return the\n * old credentials.\n *\n * This may be called before the current credentials have expired.\n */\n async prefetchCredentials() {\n this.credentials = await this.fetchCredentials();\n return this.credentials;\n }\n /**\n * Get credentials for PowerSync.\n *\n * This should always fetch a fresh set of credentials - don't use cached\n * values.\n */\n async fetchCredentials() {\n const credentials = await this.connector.fetchCredentials();\n if (credentials?.endpoint.match(POWERSYNC_TRAILING_SLASH_MATCH)) {\n throw new Error(`A trailing forward slash \"/\" was found in the fetchCredentials endpoint: \"${credentials.endpoint}\". Remove the trailing forward slash \"/\" to fix this error.`);\n }\n return credentials;\n }\n /***\n * Immediately invalidate credentials.\n *\n * This may be called when the current credentials have expired.\n */\n invalidateCredentials() {\n this.credentials = null;\n this.connector.invalidateCredentials?.();\n }\n getUserAgent() {\n return `powersync-js/${POWERSYNC_JS_VERSION}`;\n }\n async buildRequest(path) {\n const credentials = await this.getCredentials();\n if (credentials != null && (credentials.endpoint == null || credentials.endpoint == '')) {\n throw new Error('PowerSync endpoint not configured');\n }\n else if (credentials?.token == null || credentials?.token == '') {\n const error = new Error(`Not signed in`);\n error.status = 401;\n throw error;\n }\n const userAgent = this.getUserAgent();\n return {\n url: credentials.endpoint + path,\n headers: {\n 'content-type': 'application/json',\n Authorization: `Token ${credentials.token}`,\n 'x-user-agent': userAgent\n }\n };\n }\n async post(path, data, headers = {}) {\n const request = await this.buildRequest(path);\n const res = await this.fetch(request.url, {\n method: 'POST',\n headers: {\n ...headers,\n ...request.headers\n },\n body: JSON.stringify(data)\n });\n if (res.status === 401) {\n this.invalidateCredentials();\n }\n if (!res.ok) {\n throw new Error(`Received ${res.status} - ${res.statusText} when posting to ${path}: ${await res.text()}}`);\n }\n return res.json();\n }\n async get(path, headers) {\n const request = await this.buildRequest(path);\n const res = await this.fetch(request.url, {\n method: 'GET',\n headers: {\n ...headers,\n ...request.headers\n }\n });\n if (res.status === 401) {\n this.invalidateCredentials();\n }\n if (!res.ok) {\n throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);\n }\n return res.json();\n }\n /**\n * @returns A text decoder decoding UTF-8. This is a method to allow patching it for Hermes which doesn't support the\n * builtin, without forcing us to bundle a polyfill with `@powersync/common`.\n */\n createTextDecoder() {\n return new TextDecoder();\n }\n createSocket(url) {\n return new WebSocket(url);\n }\n /**\n * Returns a data stream of sync line data.\n *\n * @param map Maps received payload frames to the typed event value.\n * @param bson A BSON encoder and decoder. When set, the data stream will be requested with a BSON payload\n * (required for compatibility with older sync services).\n */\n async socketStreamRaw(options, map, bson) {\n const { path, fetchStrategy = FetchStrategy.Buffered } = options;\n const mimeType = bson == null ? 'application/json' : 'application/bson';\n function toBuffer(js) {\n let contents;\n if (bson != null) {\n contents = bson.serialize(js);\n }\n else {\n contents = JSON.stringify(js);\n }\n return bufferExports.Buffer.from(contents);\n }\n const syncQueueRequestSize = fetchStrategy == FetchStrategy.Buffered ? 10 : 1;\n const request = await this.buildRequest(path);\n // Add the user agent in the setup payload - we can't set custom\n // headers with websockets on web. The browser userAgent is however added\n // automatically as a header.\n const userAgent = this.getUserAgent();\n const stream = new DataStream({\n logger: this.logger,\n pressure: {\n lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER\n },\n mapLine: map\n });\n // Handle upstream abort\n if (options.abortSignal?.aborted) {\n throw new AbortOperation('Connection request aborted');\n }\n else {\n options.abortSignal?.addEventListener('abort', () => {\n stream.close();\n }, { once: true });\n }\n let keepAliveTimeout;\n const resetTimeout = () => {\n clearTimeout(keepAliveTimeout);\n keepAliveTimeout = setTimeout(() => {\n this.logger.error(`No data received on WebSocket in ${SOCKET_TIMEOUT_MS}ms, closing connection.`);\n stream.close();\n }, SOCKET_TIMEOUT_MS);\n };\n resetTimeout();\n // Typescript complains about this being `never` if it's not assigned here.\n // This is assigned in `wsCreator`.\n let disposeSocketConnectionTimeout = () => { };\n const url = this.options.socketUrlTransformer(request.url);\n const connector = new distExports.RSocketConnector({\n transport: new WebsocketClientTransport({\n url,\n wsCreator: (url) => {\n const socket = this.createSocket(url);\n disposeSocketConnectionTimeout = stream.registerListener({\n closed: () => {\n // Allow closing the underlying WebSocket if the stream was closed before the\n // RSocket connect completed. This should effectively abort the request.\n socket.close();\n }\n });\n socket.addEventListener('message', (event) => {\n resetTimeout();\n });\n return socket;\n }\n }),\n setup: {\n keepAlive: KEEP_ALIVE_MS,\n lifetime: KEEP_ALIVE_LIFETIME_MS,\n dataMimeType: mimeType,\n metadataMimeType: mimeType,\n payload: {\n data: null,\n metadata: toBuffer({\n token: request.headers.Authorization,\n user_agent: userAgent\n })\n }\n }\n });\n let rsocket;\n try {\n rsocket = await connector.connect();\n // The connection is established, we no longer need to monitor the initial timeout\n disposeSocketConnectionTimeout();\n }\n catch (ex) {\n this.logger.error(`Failed to connect WebSocket`, ex);\n clearTimeout(keepAliveTimeout);\n if (!stream.closed) {\n await stream.close();\n }\n throw ex;\n }\n resetTimeout();\n let socketIsClosed = false;\n const closeSocket = () => {\n clearTimeout(keepAliveTimeout);\n if (socketIsClosed) {\n return;\n }\n socketIsClosed = true;\n rsocket.close();\n };\n // Helps to prevent double close scenarios\n rsocket.onClose(() => (socketIsClosed = true));\n // We initially request this amount and expect these to arrive eventually\n let pendingEventsCount = syncQueueRequestSize;\n const disposeClosedListener = stream.registerListener({\n closed: () => {\n closeSocket();\n disposeClosedListener();\n }\n });\n const socket = await new Promise((resolve, reject) => {\n let connectionEstablished = false;\n const res = rsocket.requestStream({\n data: toBuffer(options.data),\n metadata: toBuffer({\n path\n })\n }, syncQueueRequestSize, // The initial N amount\n {\n onError: (e) => {\n if (e.message.includes('PSYNC_')) {\n if (e.message.includes('PSYNC_S21')) {\n this.invalidateCredentials();\n }\n }\n else {\n // Possible that connection is with an older service, always invalidate to be safe\n if (e.message !== 'Closed. ') {\n this.invalidateCredentials();\n }\n }\n // Don't log closed as an error\n if (e.message !== 'Closed. ') {\n this.logger.error(e);\n }\n // RSocket will close the RSocket stream automatically\n // Close the downstream stream as well - this will close the RSocket connection and WebSocket\n stream.close();\n // Handles cases where the connection failed e.g. auth error or connection error\n if (!connectionEstablished) {\n reject(e);\n }\n },\n onNext: (payload) => {\n // The connection is active\n if (!connectionEstablished) {\n connectionEstablished = true;\n resolve(res);\n }\n const { data } = payload;\n // Less events are now pending\n pendingEventsCount--;\n if (!data) {\n return;\n }\n stream.enqueueData(data);\n },\n onComplete: () => {\n stream.close();\n },\n onExtension: () => { }\n });\n });\n const l = stream.registerListener({\n lowWater: async () => {\n // Request to fill up the queue\n const required = syncQueueRequestSize - pendingEventsCount;\n if (required > 0) {\n socket.request(syncQueueRequestSize - pendingEventsCount);\n pendingEventsCount = syncQueueRequestSize;\n }\n },\n closed: () => {\n l();\n }\n });\n return stream;\n }\n /**\n * Connects to the sync/stream http endpoint, mapping and emitting each received string line.\n */\n async postStreamRaw(options, mapLine) {\n const { data, path, headers, abortSignal } = options;\n const request = await this.buildRequest(path);\n /**\n * This abort controller will abort pending fetch requests.\n * If the request has resolved, it will be used to close the readable stream.\n * Which will cancel the network request.\n *\n * This nested controller is required since:\n * Aborting the active fetch request while it is being consumed seems to throw\n * an unhandled exception on the window level.\n */\n if (abortSignal?.aborted) {\n throw new AbortOperation('Abort request received before making postStreamRaw request');\n }\n const controller = new AbortController();\n let requestResolved = false;\n abortSignal?.addEventListener('abort', () => {\n if (!requestResolved) {\n // Only abort via the abort controller if the request has not resolved yet\n controller.abort(abortSignal.reason ??\n new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.'));\n }\n });\n const res = await this.fetch(request.url, {\n method: 'POST',\n headers: { ...headers, ...request.headers },\n body: JSON.stringify(data),\n signal: controller.signal,\n cache: 'no-store',\n ...(this.options.fetchOptions ?? {}),\n ...options.fetchOptions\n }).catch((ex) => {\n if (ex.name == 'AbortError') {\n throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);\n }\n throw ex;\n });\n if (!res) {\n throw new Error('Fetch request was aborted');\n }\n requestResolved = true;\n if (!res.ok || !res.body) {\n const text = await res.text();\n this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);\n const error = new Error(`HTTP ${res.statusText}: ${text}`);\n error.status = res.status;\n throw error;\n }\n // Create a new stream splitting the response at line endings while also handling cancellations\n // by closing the reader.\n const reader = res.body.getReader();\n let readerReleased = false;\n // This will close the network request and read stream\n const closeReader = async () => {\n try {\n readerReleased = true;\n await reader.cancel();\n }\n catch (ex) {\n // an error will throw if the reader hasn't been used yet\n }\n reader.releaseLock();\n };\n const stream = new DataStream({\n logger: this.logger,\n mapLine: mapLine,\n pressure: {\n highWaterMark: 20,\n lowWaterMark: 10\n }\n });\n abortSignal?.addEventListener('abort', () => {\n closeReader();\n stream.close();\n });\n const decoder = this.createTextDecoder();\n let buffer = '';\n const consumeStream = async () => {\n while (!stream.closed && !abortSignal?.aborted && !readerReleased) {\n const { done, value } = await reader.read();\n if (done) {\n const remaining = buffer.trim();\n if (remaining.length != 0) {\n stream.enqueueData(remaining);\n }\n stream.close();\n await closeReader();\n return;\n }\n const data = decoder.decode(value, { stream: true });\n buffer += data;\n const lines = buffer.split('\\n');\n for (var i = 0; i < lines.length - 1; i++) {\n var l = lines[i].trim();\n if (l.length > 0) {\n stream.enqueueData(l);\n }\n }\n buffer = lines[lines.length - 1];\n // Implement backpressure by waiting for the low water mark to be reached\n if (stream.dataQueue.length > stream.highWatermark) {\n await new Promise((resolve) => {\n const dispose = stream.registerListener({\n lowWater: async () => {\n resolve();\n dispose();\n },\n closed: () => {\n resolve();\n dispose();\n }\n });\n });\n }\n }\n };\n consumeStream().catch(ex => this.logger.error('Error consuming stream', ex));\n const l = stream.registerListener({\n closed: () => {\n closeReader();\n l?.();\n }\n });\n return stream;\n }\n}\n\nfunction priorityToJs(status) {\n return {\n priority: status.priority,\n hasSynced: status.has_synced ?? undefined,\n lastSyncedAt: status.last_synced_at != null ? new Date(status.last_synced_at * 1000) : undefined\n };\n}\nfunction coreStatusToJs(status) {\n const coreCompleteSync = status.priority_status.find((s) => s.priority == FULL_SYNC_PRIORITY);\n const completeSync = coreCompleteSync != null ? priorityToJs(coreCompleteSync) : null;\n return {\n connected: status.connected,\n connecting: status.connecting,\n dataFlow: {\n // We expose downloading as a boolean field, the core extension reports download information as a nullable\n // download status. When that status is non-null, a download is in progress.\n downloading: status.downloading != null,\n downloadProgress: status.downloading?.buckets,\n internalStreamSubscriptions: status.streams\n },\n lastSyncedAt: completeSync?.lastSyncedAt,\n hasSynced: completeSync?.hasSynced,\n priorityStatusEntries: status.priority_status.map(priorityToJs)\n };\n}\n\nfunction isStreamingSyncData(line) {\n return line.data != null;\n}\nfunction isStreamingKeepalive(line) {\n return line.token_expires_in != null;\n}\nfunction isStreamingSyncCheckpoint(line) {\n return line.checkpoint != null;\n}\nfunction isStreamingSyncCheckpointComplete(line) {\n return line.checkpoint_complete != null;\n}\nfunction isStreamingSyncCheckpointPartiallyComplete(line) {\n return line.partial_checkpoint_complete != null;\n}\nfunction isStreamingSyncCheckpointDiff(line) {\n return line.checkpoint_diff != null;\n}\nfunction isContinueCheckpointRequest(request) {\n return (Array.isArray(request.buckets) &&\n typeof request.checkpoint_token == 'string');\n}\nfunction isSyncNewCheckpointRequest(request) {\n return typeof request.request_checkpoint == 'object';\n}\n\nvar LockType;\n(function (LockType) {\n LockType[\"CRUD\"] = \"crud\";\n LockType[\"SYNC\"] = \"sync\";\n})(LockType || (LockType = {}));\nvar SyncStreamConnectionMethod;\n(function (SyncStreamConnectionMethod) {\n SyncStreamConnectionMethod[\"HTTP\"] = \"http\";\n SyncStreamConnectionMethod[\"WEB_SOCKET\"] = \"web-socket\";\n})(SyncStreamConnectionMethod || (SyncStreamConnectionMethod = {}));\nvar SyncClientImplementation;\n(function (SyncClientImplementation) {\n /**\n * Decodes and handles sync lines received from the sync service in JavaScript.\n *\n * This is the default option.\n *\n * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with\n * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future\n * version of the PowerSync SDK.\n */\n SyncClientImplementation[\"JAVASCRIPT\"] = \"js\";\n /**\n * This implementation offloads the sync line decoding and handling into the PowerSync\n * core extension.\n *\n * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the\n * recommended client implementation for all apps.\n *\n * ## Compatibility warning\n *\n * The Rust sync client stores sync data in a format that is slightly different than the one used\n * by the old {@link JAVASCRIPT} implementation. When adopting the {@link RUST} client on existing\n * databases, the PowerSync SDK will migrate the format automatically.\n * Further, the {@link JAVASCRIPT} client in recent versions of the PowerSync JS SDK (starting from\n * the version introducing {@link RUST} as an option) also supports the new format, so you can switch\n * back to {@link JAVASCRIPT} later.\n *\n * __However__: Upgrading the SDK version, then adopting {@link RUST} as a sync client and later\n * downgrading the SDK to an older version (necessarily using the JavaScript-based implementation then)\n * can lead to sync issues.\n */\n SyncClientImplementation[\"RUST\"] = \"rust\";\n})(SyncClientImplementation || (SyncClientImplementation = {}));\n/**\n * The default {@link SyncClientImplementation} to use, {@link SyncClientImplementation.RUST}.\n */\nconst DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.RUST;\nconst DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;\nconst DEFAULT_RETRY_DELAY_MS = 5000;\nconst DEFAULT_STREAMING_SYNC_OPTIONS = {\n retryDelayMs: DEFAULT_RETRY_DELAY_MS,\n crudUploadThrottleMs: DEFAULT_CRUD_UPLOAD_THROTTLE_MS\n};\nconst DEFAULT_STREAM_CONNECTION_OPTIONS = {\n appMetadata: {},\n connectionMethod: SyncStreamConnectionMethod.WEB_SOCKET,\n clientImplementation: DEFAULT_SYNC_CLIENT_IMPLEMENTATION,\n fetchStrategy: FetchStrategy.Buffered,\n params: {},\n serializedSchema: undefined,\n includeDefaultStreams: true\n};\n// The priority we assume when we receive checkpoint lines where no priority is set.\n// This is the default priority used by the sync service, but can be set to an arbitrary\n// value since sync services without priorities also won't send partial sync completion\n// messages.\nconst FALLBACK_PRIORITY = 3;\nclass AbstractStreamingSyncImplementation extends BaseObserver {\n _lastSyncedAt;\n options;\n abortController;\n // In rare cases, mostly for tests, uploads can be triggered without being properly connected.\n // This allows ensuring that all upload processes can be aborted.\n uploadAbortController;\n crudUpdateListener;\n streamingSyncPromise;\n logger;\n activeStreams;\n isUploadingCrud = false;\n notifyCompletedUploads;\n handleActiveStreamsChange;\n syncStatus;\n triggerCrudUpload;\n constructor(options) {\n super();\n this.options = options;\n this.activeStreams = options.subscriptions;\n this.logger = options.logger ?? Logger.get('PowerSyncStream');\n this.syncStatus = new SyncStatus({\n connected: false,\n connecting: false,\n lastSyncedAt: undefined,\n dataFlow: {\n uploading: false,\n downloading: false\n }\n });\n this.abortController = null;\n this.triggerCrudUpload = throttleLeadingTrailing(() => {\n if (!this.syncStatus.connected || this.isUploadingCrud) {\n return;\n }\n this.isUploadingCrud = true;\n this._uploadAllCrud().finally(() => {\n this.notifyCompletedUploads?.();\n this.isUploadingCrud = false;\n });\n }, this.options.crudUploadThrottleMs);\n }\n async waitForReady() { }\n waitForStatus(status) {\n return this.waitUntilStatusMatches((currentStatus) => {\n /**\n * Match only the partial status options provided in the\n * matching status\n */\n const matchPartialObject = (compA, compB) => {\n return Object.entries(compA).every(([key, value]) => {\n const comparisonBValue = compB[key];\n if (typeof value == 'object' && typeof comparisonBValue == 'object') {\n return matchPartialObject(value, comparisonBValue);\n }\n return value == comparisonBValue;\n });\n };\n return matchPartialObject(status, currentStatus);\n });\n }\n waitUntilStatusMatches(predicate) {\n return new Promise((resolve) => {\n if (predicate(this.syncStatus)) {\n resolve();\n return;\n }\n const l = this.registerListener({\n statusChanged: (updatedStatus) => {\n if (predicate(updatedStatus)) {\n resolve();\n l?.();\n }\n }\n });\n });\n }\n get lastSyncedAt() {\n const lastSynced = this.syncStatus.lastSyncedAt;\n return lastSynced && new Date(lastSynced);\n }\n get isConnected() {\n return this.syncStatus.connected;\n }\n async dispose() {\n super.dispose();\n this.crudUpdateListener?.();\n this.crudUpdateListener = undefined;\n this.uploadAbortController?.abort();\n }\n async hasCompletedSync() {\n return this.options.adapter.hasCompletedSync();\n }\n async getWriteCheckpoint() {\n const clientId = await this.options.adapter.getClientId();\n let path = `/write-checkpoint2.json?client_id=${clientId}`;\n const response = await this.options.remote.get(path);\n const checkpoint = response['data']['write_checkpoint'];\n this.logger.debug(`Created write checkpoint: ${checkpoint}`);\n return checkpoint;\n }\n async _uploadAllCrud() {\n return this.obtainLock({\n type: LockType.CRUD,\n callback: async () => {\n /**\n * Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.\n */\n let checkedCrudItem;\n const controller = new AbortController();\n this.uploadAbortController = controller;\n this.abortController?.signal.addEventListener('abort', () => {\n controller.abort();\n }, { once: true });\n while (!controller.signal.aborted) {\n try {\n /**\n * This is the first item in the FIFO CRUD queue.\n */\n const nextCrudItem = await this.options.adapter.nextCrudItem();\n if (nextCrudItem) {\n this.updateSyncStatus({\n dataFlow: {\n uploading: true\n }\n });\n if (nextCrudItem.clientId == checkedCrudItem?.clientId) {\n // This will force a higher log level than exceptions which are caught here.\n this.logger.warn(`Potentially previously uploaded CRUD entries are still present in the upload queue.\nMake sure to handle uploads and complete CRUD transactions or batches by calling and awaiting their [.complete()] method.\nThe next upload iteration will be delayed.`);\n throw new Error('Delaying due to previously encountered CRUD item.');\n }\n checkedCrudItem = nextCrudItem;\n await this.options.uploadCrud();\n this.updateSyncStatus({\n dataFlow: {\n uploadError: undefined\n }\n });\n }\n else {\n // Uploading is completed\n const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());\n if (neededUpdate == false && checkedCrudItem != null) {\n // Only log this if there was something to upload\n this.logger.debug('Upload complete, no write checkpoint needed.');\n }\n break;\n }\n }\n catch (ex) {\n checkedCrudItem = undefined;\n this.updateSyncStatus({\n dataFlow: {\n uploading: false,\n uploadError: ex\n }\n });\n await this.delayRetry(controller.signal);\n if (!this.isConnected) {\n // Exit the upload loop if the sync stream is no longer connected\n break;\n }\n this.logger.debug(`Caught exception when uploading. Upload will retry after a delay. Exception: ${ex.message}`);\n }\n finally {\n this.updateSyncStatus({\n dataFlow: {\n uploading: false\n }\n });\n }\n }\n this.uploadAbortController = null;\n }\n });\n }\n async connect(options) {\n if (this.abortController) {\n await this.disconnect();\n }\n const controller = new AbortController();\n this.abortController = controller;\n this.streamingSyncPromise = this.streamingSync(this.abortController.signal, options);\n // Return a promise that resolves when the connection status is updated to indicate that we're connected.\n return new Promise((resolve) => {\n const disposer = this.registerListener({\n statusChanged: (status) => {\n if (status.dataFlowStatus.downloadError != null) {\n this.logger.warn('Initial connect attempt did not successfully connect to server');\n }\n else if (status.connecting) {\n // Still connecting.\n return;\n }\n disposer();\n resolve();\n }\n });\n });\n }\n async disconnect() {\n if (!this.abortController) {\n return;\n }\n // This might be called multiple times\n if (!this.abortController.signal.aborted) {\n this.abortController.abort(new AbortOperation('Disconnect has been requested'));\n }\n // Await any pending operations before completing the disconnect operation\n try {\n await this.streamingSyncPromise;\n }\n catch (ex) {\n // The operation might have failed, all we care about is if it has completed\n this.logger.warn(ex);\n }\n this.streamingSyncPromise = undefined;\n this.abortController = null;\n this.updateSyncStatus({ connected: false, connecting: false });\n }\n /**\n * @deprecated use [connect instead]\n */\n async streamingSync(signal, options) {\n if (!signal) {\n this.abortController = new AbortController();\n signal = this.abortController.signal;\n }\n /**\n * Listen for CRUD updates and trigger upstream uploads\n */\n this.crudUpdateListener = this.options.adapter.registerListener({\n crudUpdate: () => this.triggerCrudUpload()\n });\n /**\n * Create a new abort controller which aborts items downstream.\n * This is needed to close any previous connections on exception.\n */\n let nestedAbortController = new AbortController();\n signal.addEventListener('abort', () => {\n /**\n * A request for disconnect was received upstream. Relay the request\n * to the nested abort controller.\n */\n nestedAbortController.abort(signal?.reason ?? new AbortOperation('Received command to disconnect from upstream'));\n this.crudUpdateListener?.();\n this.crudUpdateListener = undefined;\n this.updateSyncStatus({\n connected: false,\n connecting: false,\n dataFlow: {\n downloading: false,\n downloadProgress: null\n }\n });\n });\n /**\n * This loops runs until [retry] is false or the abort signal is set to aborted.\n * Aborting the nestedAbortController will:\n * - Abort any pending fetch requests\n * - Close any sync stream ReadableStreams (which will also close any established network requests)\n */\n while (true) {\n this.updateSyncStatus({ connecting: true });\n let shouldDelayRetry = true;\n let result = null;\n try {\n if (signal?.aborted) {\n break;\n }\n result = await this.streamingSyncIteration(nestedAbortController.signal, options);\n // Continue immediately, streamingSyncIteration will wait before completing if necessary.\n }\n catch (ex) {\n /**\n * Either:\n * - A network request failed with a failed connection or not OKAY response code.\n * - There was a sync processing error.\n * - The connection was aborted.\n * This loop will retry after a delay if the connection was not aborted.\n * The nested abort controller will cleanup any open network requests and streams.\n * The WebRemote should only abort pending fetch requests or close active Readable streams.\n */\n if (ex instanceof AbortOperation) {\n this.logger.warn(ex);\n shouldDelayRetry = false;\n // A disconnect was requested, we should not delay since there is no explicit retry\n }\n else {\n this.logger.error(ex);\n }\n this.updateSyncStatus({\n dataFlow: {\n downloadError: ex\n }\n });\n }\n finally {\n this.notifyCompletedUploads = undefined;\n if (!signal.aborted) {\n nestedAbortController.abort(new AbortOperation('Closing sync stream network requests before retry.'));\n nestedAbortController = new AbortController();\n }\n if (result?.immediateRestart != true) {\n this.updateSyncStatus({\n connected: false,\n connecting: true // May be unnecessary\n });\n // On error, wait a little before retrying\n if (shouldDelayRetry) {\n await this.delayRetry(nestedAbortController.signal);\n }\n }\n }\n }\n // Mark as disconnected if here\n this.updateSyncStatus({ connected: false, connecting: false });\n }\n async collectLocalBucketState() {\n const bucketEntries = await this.options.adapter.getBucketStates();\n const req = bucketEntries.map((entry) => ({\n name: entry.bucket,\n after: entry.op_id\n }));\n const localDescriptions = new Map();\n for (const entry of bucketEntries) {\n localDescriptions.set(entry.bucket, null);\n }\n return [req, localDescriptions];\n }\n /**\n * Older versions of the JS SDK used to encode subkeys as JSON in {@link OplogEntry.toJSON}.\n * Because subkeys are always strings, this leads to quotes being added around them in `ps_oplog`.\n * While this is not a problem as long as it's done consistently, it causes issues when a database\n * created by the JS SDK is used with other SDKs, or (more likely) when the new Rust sync client\n * is enabled.\n *\n * So, we add a migration from the old key format (with quotes) to the new one (no quotes). The\n * migration is only triggered when necessary (for now). The function returns whether the new format\n * should be used, so that the JS SDK is able to write to updated databases.\n *\n * @param requireFixedKeyFormat Whether we require the new format or also support the old one.\n * The Rust client requires the new subkey format.\n * @returns Whether the database is now using the new, fixed subkey format.\n */\n async requireKeyFormat(requireFixedKeyFormat) {\n const hasMigrated = await this.options.adapter.hasMigratedSubkeys();\n if (requireFixedKeyFormat && !hasMigrated) {\n await this.options.adapter.migrateToFixedSubkeys();\n return true;\n }\n else {\n return hasMigrated;\n }\n }\n streamingSyncIteration(signal, options) {\n return this.obtainLock({\n type: LockType.SYNC,\n signal,\n callback: async () => {\n const resolvedOptions = {\n ...DEFAULT_STREAM_CONNECTION_OPTIONS,\n ...(options ?? {})\n };\n // Validate app metadata\n const invalidMetadata = Object.entries(resolvedOptions.appMetadata).filter(([_, value]) => typeof value != 'string');\n if (invalidMetadata.length > 0) {\n throw new Error(`Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`);\n }\n const clientImplementation = resolvedOptions.clientImplementation;\n this.updateSyncStatus({ clientImplementation });\n if (clientImplementation == SyncClientImplementation.JAVASCRIPT) {\n await this.legacyStreamingSyncIteration(signal, resolvedOptions);\n return null;\n }\n else {\n await this.requireKeyFormat(true);\n return await this.rustSyncIteration(signal, resolvedOptions);\n }\n }\n });\n }\n async legacyStreamingSyncIteration(signal, resolvedOptions) {\n const rawTables = resolvedOptions.serializedSchema?.raw_tables;\n if (rawTables != null && rawTables.length) {\n this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');\n }\n if (this.activeStreams.length) {\n this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');\n }\n this.logger.debug('Streaming sync iteration started');\n this.options.adapter.startSession();\n let [req, bucketMap] = await this.collectLocalBucketState();\n let targetCheckpoint = null;\n // A checkpoint that has been validated but not applied (e.g. due to pending local writes)\n let pendingValidatedCheckpoint = null;\n const clientId = await this.options.adapter.getClientId();\n const usingFixedKeyFormat = await this.requireKeyFormat(false);\n this.logger.debug('Requesting stream from server');\n const syncOptions = {\n path: '/sync/stream',\n abortSignal: signal,\n data: {\n buckets: req,\n include_checksum: true,\n raw_data: true,\n parameters: resolvedOptions.params,\n app_metadata: resolvedOptions.appMetadata,\n client_id: clientId\n }\n };\n let stream;\n if (resolvedOptions?.connectionMethod == SyncStreamConnectionMethod.HTTP) {\n stream = await this.options.remote.postStreamRaw(syncOptions, (line) => {\n if (typeof line == 'string') {\n return JSON.parse(line);\n }\n else {\n // Directly enqueued by us\n return line;\n }\n });\n }\n else {\n const bson = await this.options.remote.getBSON();\n stream = await this.options.remote.socketStreamRaw({\n ...syncOptions,\n ...{ fetchStrategy: resolvedOptions.fetchStrategy }\n }, (payload) => {\n if (payload instanceof Uint8Array) {\n return bson.deserialize(payload);\n }\n else {\n // Directly enqueued by us\n return payload;\n }\n }, bson);\n }\n this.logger.debug('Stream established. Processing events');\n this.notifyCompletedUploads = () => {\n if (!stream.closed) {\n stream.enqueueData({ crud_upload_completed: null });\n }\n };\n while (!stream.closed) {\n const line = await stream.read();\n if (!line) {\n // The stream has closed while waiting\n return;\n }\n if ('crud_upload_completed' in line) {\n if (pendingValidatedCheckpoint != null) {\n const { applied, endIteration } = await this.applyCheckpoint(pendingValidatedCheckpoint);\n if (applied) {\n pendingValidatedCheckpoint = null;\n }\n else if (endIteration) {\n break;\n }\n }\n continue;\n }\n // A connection is active and messages are being received\n if (!this.syncStatus.connected) {\n // There is a connection now\n Promise.resolve().then(() => this.triggerCrudUpload());\n this.updateSyncStatus({\n connected: true\n });\n }\n if (isStreamingSyncCheckpoint(line)) {\n targetCheckpoint = line.checkpoint;\n // New checkpoint - existing validated checkpoint is no longer valid\n pendingValidatedCheckpoint = null;\n const bucketsToDelete = new Set(bucketMap.keys());\n const newBuckets = new Map();\n for (const checksum of line.checkpoint.buckets) {\n newBuckets.set(checksum.bucket, {\n name: checksum.bucket,\n priority: checksum.priority ?? FALLBACK_PRIORITY\n });\n bucketsToDelete.delete(checksum.bucket);\n }\n if (bucketsToDelete.size > 0) {\n this.logger.debug('Removing buckets', [...bucketsToDelete]);\n }\n bucketMap = newBuckets;\n await this.options.adapter.removeBuckets([...bucketsToDelete]);\n await this.options.adapter.setTargetCheckpoint(targetCheckpoint);\n await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);\n }\n else if (isStreamingSyncCheckpointComplete(line)) {\n const result = await this.applyCheckpoint(targetCheckpoint);\n if (result.endIteration) {\n return;\n }\n else if (!result.applied) {\n // \"Could not apply checkpoint due to local data\". We need to retry after\n // finishing uploads.\n pendingValidatedCheckpoint = targetCheckpoint;\n }\n else {\n // Nothing to retry later. This would likely already be null from the last\n // checksum or checksum_diff operation, but we make sure.\n pendingValidatedCheckpoint = null;\n }\n }\n else if (isStreamingSyncCheckpointPartiallyComplete(line)) {\n const priority = line.partial_checkpoint_complete.priority;\n this.logger.debug('Partial checkpoint complete', priority);\n const result = await this.options.adapter.syncLocalDatabase(targetCheckpoint, priority);\n if (!result.checkpointValid) {\n // This means checksums failed. Start again with a new checkpoint.\n // TODO: better back-off\n await new Promise((resolve) => setTimeout(resolve, 50));\n return;\n }\n else if (!result.ready) ;\n else {\n // We'll keep on downloading, but can report that this priority is synced now.\n this.logger.debug('partial checkpoint validation succeeded');\n // All states with a higher priority can be deleted since this partial sync includes them.\n const priorityStates = this.syncStatus.priorityStatusEntries.filter((s) => s.priority <= priority);\n priorityStates.push({\n priority,\n lastSyncedAt: new Date(),\n hasSynced: true\n });\n this.updateSyncStatus({\n connected: true,\n priorityStatusEntries: priorityStates\n });\n }\n }\n else if (isStreamingSyncCheckpointDiff(line)) {\n // TODO: It may be faster to just keep track of the diff, instead of the entire checkpoint\n if (targetCheckpoint == null) {\n throw new Error('Checkpoint diff without previous checkpoint');\n }\n // New checkpoint - existing validated checkpoint is no longer valid\n pendingValidatedCheckpoint = null;\n const diff = line.checkpoint_diff;\n const newBuckets = new Map();\n for (const checksum of targetCheckpoint.buckets) {\n newBuckets.set(checksum.bucket, checksum);\n }\n for (const checksum of diff.updated_buckets) {\n newBuckets.set(checksum.bucket, checksum);\n }\n for (const bucket of diff.removed_buckets) {\n newBuckets.delete(bucket);\n }\n const newCheckpoint = {\n last_op_id: diff.last_op_id,\n buckets: [...newBuckets.values()],\n write_checkpoint: diff.write_checkpoint\n };\n targetCheckpoint = newCheckpoint;\n await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);\n bucketMap = new Map();\n newBuckets.forEach((checksum, name) => bucketMap.set(name, {\n name: checksum.bucket,\n priority: checksum.priority ?? FALLBACK_PRIORITY\n }));\n const bucketsToDelete = diff.removed_buckets;\n if (bucketsToDelete.length > 0) {\n this.logger.debug('Remove buckets', bucketsToDelete);\n }\n await this.options.adapter.removeBuckets(bucketsToDelete);\n await this.options.adapter.setTargetCheckpoint(targetCheckpoint);\n }\n else if (isStreamingSyncData(line)) {\n const { data } = line;\n const previousProgress = this.syncStatus.dataFlowStatus.downloadProgress;\n let updatedProgress = null;\n if (previousProgress) {\n updatedProgress = { ...previousProgress };\n const progressForBucket = updatedProgress[data.bucket];\n if (progressForBucket) {\n updatedProgress[data.bucket] = {\n ...progressForBucket,\n since_last: progressForBucket.since_last + data.data.length\n };\n }\n }\n this.updateSyncStatus({\n dataFlow: {\n downloading: true,\n downloadProgress: updatedProgress\n }\n });\n await this.options.adapter.saveSyncData({ buckets: [SyncDataBucket.fromRow(data)] }, usingFixedKeyFormat);\n }\n else if (isStreamingKeepalive(line)) {\n const remaining_seconds = line.token_expires_in;\n if (remaining_seconds == 0) {\n // Connection would be closed automatically right after this\n this.logger.debug('Token expiring; reconnect');\n /**\n * For a rare case where the backend connector does not update the token\n * (uses the same one), this should have some delay.\n */\n await this.delayRetry();\n return;\n }\n else if (remaining_seconds < 30) {\n this.logger.debug('Token will expire soon; reconnect');\n // Pre-emptively refresh the token\n this.options.remote.invalidateCredentials();\n return;\n }\n this.triggerCrudUpload();\n }\n else {\n this.logger.debug('Received unknown sync line', line);\n }\n }\n this.logger.debug('Stream input empty');\n // Connection closed. Likely due to auth issue.\n return;\n }\n async rustSyncIteration(signal, resolvedOptions) {\n const syncImplementation = this;\n const adapter = this.options.adapter;\n const remote = this.options.remote;\n let receivingLines = null;\n let hadSyncLine = false;\n let hideDisconnectOnRestart = false;\n if (signal.aborted) {\n throw new AbortOperation('Connection request has been aborted');\n }\n const abortController = new AbortController();\n signal.addEventListener('abort', () => abortController.abort());\n // Pending sync lines received from the service, as well as local events that trigger a powersync_control\n // invocation (local events include refreshed tokens and completed uploads).\n // This is a single data stream so that we can handle all control calls from a single place.\n let controlInvocations = null;\n async function connect(instr) {\n const syncOptions = {\n path: '/sync/stream',\n abortSignal: abortController.signal,\n data: instr.request\n };\n if (resolvedOptions.connectionMethod == SyncStreamConnectionMethod.HTTP) {\n controlInvocations = await remote.postStreamRaw(syncOptions, (line) => {\n if (typeof line == 'string') {\n return {\n command: PowerSyncControlCommand.PROCESS_TEXT_LINE,\n payload: line\n };\n }\n else {\n // Directly enqueued by us\n return line;\n }\n });\n }\n else {\n controlInvocations = await remote.socketStreamRaw({\n ...syncOptions,\n fetchStrategy: resolvedOptions.fetchStrategy\n }, (payload) => {\n if (payload instanceof Uint8Array) {\n return {\n command: PowerSyncControlCommand.PROCESS_BSON_LINE,\n payload: payload\n };\n }\n else {\n // Directly enqueued by us\n return payload;\n }\n });\n }\n // The rust client will set connected: true after the first sync line because that's when it gets invoked, but\n // we're already connected here and can report that.\n syncImplementation.updateSyncStatus({ connected: true });\n try {\n while (!controlInvocations.closed) {\n const line = await controlInvocations.read();\n if (line == null) {\n return;\n }\n await control(line.command, line.payload);\n if (!hadSyncLine) {\n syncImplementation.triggerCrudUpload();\n hadSyncLine = true;\n }\n }\n }\n finally {\n const activeInstructions = controlInvocations;\n // We concurrently add events to the active data stream when e.g. a CRUD upload is completed or a token is\n // refreshed. That would throw after closing (and we can't handle those events either way), so set this back\n // to null.\n controlInvocations = null;\n await activeInstructions.close();\n }\n }\n async function stop() {\n await control(PowerSyncControlCommand.STOP);\n }\n async function control(op, payload) {\n const rawResponse = await adapter.control(op, payload ?? null);\n const logger = syncImplementation.logger;\n logger.trace('powersync_control', op, payload == null || typeof payload == 'string' ? payload : '<bytes>', rawResponse);\n await handleInstructions(JSON.parse(rawResponse));\n }\n async function handleInstruction(instruction) {\n if ('LogLine' in instruction) {\n switch (instruction.LogLine.severity) {\n case 'DEBUG':\n syncImplementation.logger.debug(instruction.LogLine.line);\n break;\n case 'INFO':\n syncImplementation.logger.info(instruction.LogLine.line);\n break;\n case 'WARNING':\n syncImplementation.logger.warn(instruction.LogLine.line);\n break;\n }\n }\n else if ('UpdateSyncStatus' in instruction) {\n syncImplementation.updateSyncStatus(coreStatusToJs(instruction.UpdateSyncStatus.status));\n }\n else if ('EstablishSyncStream' in instruction) {\n if (receivingLines != null) {\n // Already connected, this shouldn't happen during a single iteration.\n throw 'Unexpected request to establish sync stream, already connected';\n }\n receivingLines = connect(instruction.EstablishSyncStream);\n }\n else if ('FetchCredentials' in instruction) {\n if (instruction.FetchCredentials.did_expire) {\n remote.invalidateCredentials();\n }\n else {\n remote.invalidateCredentials();\n // Restart iteration after the credentials have been refreshed.\n remote.fetchCredentials().then((_) => {\n controlInvocations?.enqueueData({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });\n }, (err) => {\n syncImplementation.logger.warn('Could not prefetch credentials', err);\n });\n }\n }\n else if ('CloseSyncStream' in instruction) {\n abortController.abort();\n hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;\n }\n else if ('FlushFileSystem' in instruction) ;\n else if ('DidCompleteSync' in instruction) {\n syncImplementation.updateSyncStatus({\n dataFlow: {\n downloadError: undefined\n }\n });\n }\n }\n async function handleInstructions(instructions) {\n for (const instr of instructions) {\n await handleInstruction(instr);\n }\n }\n try {\n const options = {\n parameters: resolvedOptions.params,\n app_metadata: resolvedOptions.appMetadata,\n active_streams: this.activeStreams,\n include_defaults: resolvedOptions.includeDefaultStreams\n };\n if (resolvedOptions.serializedSchema) {\n options.schema = resolvedOptions.serializedSchema;\n }\n await control(PowerSyncControlCommand.START, JSON.stringify(options));\n this.notifyCompletedUploads = () => {\n if (controlInvocations && !controlInvocations?.closed) {\n controlInvocations.enqueueData({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });\n }\n };\n this.handleActiveStreamsChange = () => {\n if (controlInvocations && !controlInvocations?.closed) {\n controlInvocations.enqueueData({\n command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,\n payload: JSON.stringify(this.activeStreams)\n });\n }\n };\n await receivingLines;\n }\n finally {\n this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;\n await stop();\n }\n return { immediateRestart: hideDisconnectOnRestart };\n }\n async updateSyncStatusForStartingCheckpoint(checkpoint) {\n const localProgress = await this.options.adapter.getBucketOperationProgress();\n const progress = {};\n let invalidated = false;\n for (const bucket of checkpoint.buckets) {\n const savedProgress = localProgress[bucket.bucket];\n const atLast = savedProgress?.atLast ?? 0;\n const sinceLast = savedProgress?.sinceLast ?? 0;\n progress[bucket.bucket] = {\n // The fallback priority doesn't matter here, but 3 is the one newer versions of the sync service\n // will use by default.\n priority: bucket.priority ?? 3,\n at_last: atLast,\n since_last: sinceLast,\n target_count: bucket.count ?? 0\n };\n if (bucket.count != null && bucket.count < atLast + sinceLast) {\n // Either due to a defrag / sync rule deploy or a compaction operation, the size\n // of the bucket shrank so much that the local ops exceed the ops in the updated\n // bucket. We can't prossibly report progress in this case (it would overshoot 100%).\n invalidated = true;\n }\n }\n if (invalidated) {\n for (const bucket in progress) {\n const bucketProgress = progress[bucket];\n bucketProgress.at_last = 0;\n bucketProgress.since_last = 0;\n }\n }\n this.updateSyncStatus({\n dataFlow: {\n downloading: true,\n downloadProgress: progress\n }\n });\n }\n async applyCheckpoint(checkpoint) {\n let result = await this.options.adapter.syncLocalDatabase(checkpoint);\n if (!result.checkpointValid) {\n this.logger.debug(`Checksum mismatch in checkpoint ${checkpoint.last_op_id}, will reconnect`);\n // This means checksums failed. Start again with a new checkpoint.\n // TODO: better back-off\n await new Promise((resolve) => setTimeout(resolve, 50));\n return { applied: false, endIteration: true };\n }\n else if (!result.ready) {\n this.logger.debug(`Could not apply checkpoint ${checkpoint.last_op_id} due to local data. We will retry applying the checkpoint after that upload is completed.`);\n return { applied: false, endIteration: false };\n }\n this.logger.debug(`Applied checkpoint ${checkpoint.last_op_id}`, checkpoint);\n this.updateSyncStatus({\n connected: true,\n lastSyncedAt: new Date(),\n dataFlow: {\n downloading: false,\n downloadProgress: null,\n downloadError: undefined\n }\n });\n return { applied: true, endIteration: false };\n }\n updateSyncStatus(options) {\n const updatedStatus = new SyncStatus({\n connected: options.connected ?? this.syncStatus.connected,\n connecting: !options.connected && (options.connecting ?? this.syncStatus.connecting),\n lastSyncedAt: options.lastSyncedAt ?? this.syncStatus.lastSyncedAt,\n dataFlow: {\n ...this.syncStatus.dataFlowStatus,\n ...options.dataFlow\n },\n priorityStatusEntries: options.priorityStatusEntries ?? this.syncStatus.priorityStatusEntries,\n clientImplementation: options.clientImplementation ?? this.syncStatus.clientImplementation\n });\n if (!this.syncStatus.isEqual(updatedStatus)) {\n this.syncStatus = updatedStatus;\n // Only trigger this is there was a change\n this.iterateListeners((cb) => cb.statusChanged?.(updatedStatus));\n }\n // trigger this for all updates\n this.iterateListeners((cb) => cb.statusUpdated?.(options));\n }\n async delayRetry(signal) {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n // If the signal is already aborted, resolve immediately\n resolve();\n return;\n }\n const { retryDelayMs } = this.options;\n let timeoutId;\n const endDelay = () => {\n resolve();\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n }\n signal?.removeEventListener('abort', endDelay);\n };\n signal?.addEventListener('abort', endDelay, { once: true });\n timeoutId = setTimeout(endDelay, retryDelayMs);\n });\n }\n updateSubscriptions(subscriptions) {\n this.activeStreams = subscriptions;\n this.handleActiveStreamsChange?.();\n }\n}\n\nconst CLAIM_STORE = new Map();\n/**\n * @internal\n * @experimental\n */\nconst MEMORY_TRIGGER_CLAIM_MANAGER = {\n async obtainClaim(identifier) {\n if (CLAIM_STORE.has(identifier)) {\n throw new Error(`A claim is already present for ${identifier}`);\n }\n const release = async () => {\n CLAIM_STORE.delete(identifier);\n };\n CLAIM_STORE.set(identifier, release);\n return release;\n },\n async checkClaim(identifier) {\n return CLAIM_STORE.has(identifier);\n }\n};\n\n/**\n * SQLite operations to track changes for with {@link TriggerManager}\n * @experimental\n */\nvar DiffTriggerOperation;\n(function (DiffTriggerOperation) {\n DiffTriggerOperation[\"INSERT\"] = \"INSERT\";\n DiffTriggerOperation[\"UPDATE\"] = \"UPDATE\";\n DiffTriggerOperation[\"DELETE\"] = \"DELETE\";\n})(DiffTriggerOperation || (DiffTriggerOperation = {}));\n\nconst DEFAULT_TRIGGER_MANAGER_CONFIGURATION = {\n useStorageByDefault: false\n};\nconst TRIGGER_CLEANUP_INTERVAL_MS = 120_000; // 2 minutes\n/**\n * @internal\n * @experimental\n */\nclass TriggerManagerImpl {\n options;\n schema;\n defaultConfig;\n cleanupTimeout;\n isDisposed;\n constructor(options) {\n this.options = options;\n this.schema = options.schema;\n options.db.registerListener({\n schemaChanged: (schema) => {\n this.schema = schema;\n }\n });\n this.isDisposed = false;\n /**\n * Configure a cleanup to run on an interval.\n * The interval is configured using setTimeout to take the async\n * execution time of the callback into account.\n */\n this.defaultConfig = DEFAULT_TRIGGER_MANAGER_CONFIGURATION;\n const cleanupCallback = async () => {\n this.cleanupTimeout = null;\n if (this.isDisposed) {\n return;\n }\n try {\n await this.cleanupResources();\n }\n catch (ex) {\n this.db.logger.error(`Caught error while attempting to cleanup triggers`, ex);\n }\n finally {\n // if not closed, set another timeout\n if (this.isDisposed) {\n return;\n }\n this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);\n }\n };\n this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);\n }\n get db() {\n return this.options.db;\n }\n async getUUID() {\n const { id: uuid } = await this.db.get(/* sql */ `\n SELECT\n uuid () as id\n `);\n // Replace dashes with underscores for SQLite table/trigger name compatibility\n return uuid.replace(/-/g, '_');\n }\n async removeTriggers(tx, triggerIds) {\n for (const triggerId of triggerIds) {\n await tx.execute(/* sql */ `DROP TRIGGER IF EXISTS ${triggerId}; `);\n }\n }\n dispose() {\n this.isDisposed = true;\n if (this.cleanupTimeout) {\n clearTimeout(this.cleanupTimeout);\n }\n }\n /**\n * Updates default config settings for platform specific use-cases.\n */\n updateDefaults(config) {\n this.defaultConfig = {\n ...this.defaultConfig,\n ...config\n };\n }\n generateTriggerName(operation, destinationTable, triggerId) {\n return `__ps_temp_trigger_${operation.toLowerCase()}__${destinationTable}__${triggerId}`;\n }\n /**\n * Cleanup any SQLite triggers or tables that are no longer in use.\n */\n async cleanupResources() {\n // we use the database here since cleanupResources is called during the PowerSyncDatabase initialization\n await this.db.database.writeLock(async (ctx) => {\n /**\n * Note: We only cleanup persisted triggers. These are tracked in the sqlite_master table.\n * temporary triggers will not be affected by this.\n * Query all triggers that match our naming pattern\n */\n const triggers = await ctx.getAll(/* sql */ `\n SELECT\n name\n FROM\n sqlite_master\n WHERE\n type = 'trigger'\n AND name LIKE '__ps_temp_trigger_%'\n `);\n /** Use regex to extract table names and IDs from trigger names\n * Trigger naming convention: __ps_temp_trigger_<operation>__<destination_table>__<id>\n */\n const triggerPattern = /^__ps_temp_trigger_(?:insert|update|delete)__(.+)__([a-f0-9_]{36})$/i;\n const trackedItems = new Map();\n for (const trigger of triggers) {\n const match = trigger.name.match(triggerPattern);\n if (match) {\n const [, table, id] = match;\n // Collect all trigger names for each id combo\n const existing = trackedItems.get(id);\n if (existing) {\n existing.triggerNames.push(trigger.name);\n }\n else {\n trackedItems.set(id, { table, id, triggerNames: [trigger.name] });\n }\n }\n }\n for (const trackedItem of trackedItems.values()) {\n // check if there is anything holding on to this item\n const hasClaim = await this.options.claimManager.checkClaim(trackedItem.id);\n if (hasClaim) {\n // This does not require cleanup\n continue;\n }\n this.db.logger.debug(`Clearing resources for trigger ${trackedItem.id} with table ${trackedItem.table}`);\n // We need to delete the triggers and table\n for (const triggerName of trackedItem.triggerNames) {\n await ctx.execute(`DROP TRIGGER IF EXISTS ${triggerName}`);\n }\n await ctx.execute(`DROP TABLE IF EXISTS ${trackedItem.table}`);\n }\n });\n }\n async createDiffTrigger(options) {\n await this.db.waitForReady();\n const { source, destination, columns, when, hooks, \n // Fall back to the provided default if not given on this level\n useStorage = this.defaultConfig.useStorageByDefault } = options;\n const operations = Object.keys(when);\n if (operations.length == 0) {\n throw new Error('At least one WHEN operation must be specified for the trigger.');\n }\n /**\n * The clause to use when executing\n * CREATE ${tableTriggerTypeClause} TABLE\n * OR\n * CREATE ${tableTriggerTypeClause} TRIGGER\n */\n const tableTriggerTypeClause = !useStorage ? 'TEMP' : '';\n const whenClauses = Object.fromEntries(Object.entries(when).map(([operation, filter]) => [operation, `WHEN ${filter}`]));\n /**\n * Allow specifying the View name as the source.\n * We can lookup the internal table name from the schema.\n */\n const sourceDefinition = this.schema.tables.find((table) => table.viewName == source);\n if (!sourceDefinition) {\n throw new Error(`Source table or view \"${source}\" not found in the schema.`);\n }\n const replicatedColumns = columns ?? sourceDefinition.columns.map((col) => col.name);\n const internalSource = sourceDefinition.internalName;\n const triggerIds = [];\n const id = await this.getUUID();\n const releaseStorageClaim = useStorage ? await this.options.claimManager.obtainClaim(id) : null;\n /**\n * We default to replicating all columns if no columns array is provided.\n */\n const jsonFragment = (source = 'NEW') => {\n if (columns == null) {\n // Track all columns\n return `${source}.data`;\n }\n else if (columns.length == 0) {\n // Don't track any columns except for the id\n return `'{}'`;\n }\n else {\n // Filter the data by the replicated columns\n return `json_object(${replicatedColumns.map((col) => `'${col}', json_extract(${source}.data, '$.${col}')`).join(', ')})`;\n }\n };\n const disposeWarningListener = this.db.registerListener({\n schemaChanged: () => {\n this.db.logger.warn(`The PowerSync schema has changed while previously configured triggers are still operational. This might cause unexpected results.`);\n }\n });\n /**\n * Declare the cleanup function early since if any of the init steps fail,\n * we need to ensure we can cleanup the created resources.\n * We unfortunately cannot rely on transaction rollback.\n */\n const cleanup = async () => {\n disposeWarningListener();\n return this.db.writeLock(async (tx) => {\n await this.removeTriggers(tx, triggerIds);\n await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);\n await releaseStorageClaim?.();\n });\n };\n const setup = async (tx) => {\n // Allow user code to execute in this lock context before the trigger is created.\n await hooks?.beforeCreate?.(tx);\n await tx.execute(/* sql */ `\n CREATE ${tableTriggerTypeClause} TABLE ${destination} (\n operation_id INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT,\n operation TEXT,\n timestamp TEXT,\n value TEXT,\n previous_value TEXT\n )\n `);\n if (operations.includes(DiffTriggerOperation.INSERT)) {\n const insertTriggerId = this.generateTriggerName(DiffTriggerOperation.INSERT, destination, id);\n triggerIds.push(insertTriggerId);\n await tx.execute(/* sql */ `\n CREATE ${tableTriggerTypeClause} TRIGGER ${insertTriggerId} AFTER INSERT ON ${internalSource} ${whenClauses[DiffTriggerOperation.INSERT]} BEGIN\n INSERT INTO\n ${destination} (id, operation, timestamp, value)\n VALUES\n (\n NEW.id,\n 'INSERT',\n strftime ('%Y-%m-%dT%H:%M:%fZ', 'now'),\n ${jsonFragment('NEW')}\n );\n\n END\n `);\n }\n if (operations.includes(DiffTriggerOperation.UPDATE)) {\n const updateTriggerId = this.generateTriggerName(DiffTriggerOperation.UPDATE, destination, id);\n triggerIds.push(updateTriggerId);\n await tx.execute(/* sql */ `\n CREATE ${tableTriggerTypeClause} TRIGGER ${updateTriggerId} AFTER\n UPDATE ON ${internalSource} ${whenClauses[DiffTriggerOperation.UPDATE]} BEGIN\n INSERT INTO\n ${destination} (id, operation, timestamp, value, previous_value)\n VALUES\n (\n NEW.id,\n 'UPDATE',\n strftime ('%Y-%m-%dT%H:%M:%fZ', 'now'),\n ${jsonFragment('NEW')},\n ${jsonFragment('OLD')}\n );\n\n END;\n `);\n }\n if (operations.includes(DiffTriggerOperation.DELETE)) {\n const deleteTriggerId = this.generateTriggerName(DiffTriggerOperation.DELETE, destination, id);\n triggerIds.push(deleteTriggerId);\n // Create delete trigger for basic JSON\n await tx.execute(/* sql */ `\n CREATE ${tableTriggerTypeClause} TRIGGER ${deleteTriggerId} AFTER DELETE ON ${internalSource} ${whenClauses[DiffTriggerOperation.DELETE]} BEGIN\n INSERT INTO\n ${destination} (id, operation, timestamp, value)\n VALUES\n (\n OLD.id,\n 'DELETE',\n strftime ('%Y-%m-%dT%H:%M:%fZ', 'now'),\n ${jsonFragment('OLD')}\n );\n\n END;\n `);\n }\n };\n try {\n await this.db.writeLock(setup);\n return cleanup;\n }\n catch (error) {\n try {\n await cleanup();\n }\n catch (cleanupError) {\n throw new AggregateError([error, cleanupError], 'Error during operation and cleanup');\n }\n throw error;\n }\n }\n async trackTableDiff(options) {\n const { source, when, columns, hooks, throttleMs = DEFAULT_WATCH_THROTTLE_MS } = options;\n await this.db.waitForReady();\n /**\n * Allow specifying the View name as the source.\n * We can lookup the internal table name from the schema.\n */\n const sourceDefinition = this.schema.tables.find((table) => table.viewName == source);\n if (!sourceDefinition) {\n throw new Error(`Source table or view \"${source}\" not found in the schema.`);\n }\n // The columns to present in the onChange context methods.\n // If no array is provided, we use all columns from the source table.\n const contextColumns = columns ?? sourceDefinition.columns.map((col) => col.name);\n const id = await this.getUUID();\n const destination = `__ps_temp_track_${source}_${id}`;\n // register an onChange before the trigger is created\n const abortController = new AbortController();\n const abortOnChange = () => abortController.abort();\n this.db.onChange({\n // Note that the onChange events here have their execution scheduled.\n // Callbacks are throttled and are sequential.\n onChange: async () => {\n if (abortController.signal.aborted)\n return;\n // Run the handler in a write lock to keep the state of the\n // destination table consistent.\n await this.db.writeTransaction(async (tx) => {\n const callbackResult = await options.onChange({\n ...tx,\n destinationTable: destination,\n withDiff: async (query, params, options) => {\n // Wrap the query to expose the destination table\n const operationIdSelect = options?.castOperationIdAsText\n ? 'id, operation, CAST(operation_id AS TEXT) as operation_id, timestamp, value, previous_value'\n : '*';\n const wrappedQuery = /* sql */ `\n WITH\n DIFF AS (\n SELECT\n ${operationIdSelect}\n FROM\n ${destination}\n ORDER BY\n operation_id ASC\n ) ${query}\n `;\n return tx.getAll(wrappedQuery, params);\n },\n withExtractedDiff: async (query, params) => {\n // Wrap the query to expose the destination table\n const wrappedQuery = /* sql */ `\n WITH\n DIFF AS (\n SELECT\n id,\n ${contextColumns.length > 0\n ? `${contextColumns.map((col) => `json_extract(value, '$.${col}') as ${col}`).join(', ')},`\n : ''} operation_id as __operation_id,\n operation as __operation,\n timestamp as __timestamp,\n previous_value as __previous_value\n FROM\n ${destination}\n ORDER BY\n __operation_id ASC\n ) ${query}\n `;\n return tx.getAll(wrappedQuery, params);\n }\n });\n // Clear the destination table after processing\n await tx.execute(/* sql */ `DELETE FROM ${destination};`);\n return callbackResult;\n });\n }\n }, { tables: [destination], signal: abortController.signal, throttleMs });\n try {\n const removeTrigger = await this.createDiffTrigger({\n source,\n destination,\n columns: contextColumns,\n when,\n hooks\n });\n return async () => {\n abortOnChange();\n await removeTrigger();\n };\n }\n catch (error) {\n try {\n abortOnChange();\n }\n catch (cleanupError) {\n throw new AggregateError([error, cleanupError], 'Error during operation and cleanup');\n }\n throw error;\n }\n }\n}\n\nconst POWERSYNC_TABLE_MATCH = /(^ps_data__|^ps_data_local__)/;\nconst DEFAULT_DISCONNECT_CLEAR_OPTIONS = {\n clearLocal: true\n};\nconst DEFAULT_POWERSYNC_CLOSE_OPTIONS = {\n disconnect: true\n};\nconst DEFAULT_POWERSYNC_DB_OPTIONS = {\n retryDelayMs: 5000,\n crudUploadThrottleMs: DEFAULT_CRUD_UPLOAD_THROTTLE_MS\n};\nconst DEFAULT_CRUD_BATCH_LIMIT = 100;\n/**\n * Requesting nested or recursive locks can block the application in some circumstances.\n * This default lock timeout will act as a failsafe to throw an error if a lock cannot\n * be obtained.\n */\nconst DEFAULT_LOCK_TIMEOUT_MS = 120_000; // 2 mins\n/**\n * Tests if the input is a {@link PowerSyncDatabaseOptionsWithSettings}\n * @internal\n */\nconst isPowerSyncDatabaseOptionsWithSettings = (test) => {\n return typeof test == 'object' && isSQLOpenOptions(test.database);\n};\nclass AbstractPowerSyncDatabase extends BaseObserver {\n options;\n /**\n * Returns true if the connection is closed.\n */\n closed;\n ready;\n /**\n * Current connection status.\n */\n currentStatus;\n sdkVersion;\n bucketStorageAdapter;\n _isReadyPromise;\n connectionManager;\n subscriptions;\n get syncStreamImplementation() {\n return this.connectionManager.syncStreamImplementation;\n }\n /**\n * The connector used to connect to the PowerSync service.\n *\n * @returns The connector used to connect to the PowerSync service or null if `connect()` has not been called.\n */\n get connector() {\n return this.connectionManager.connector;\n }\n /**\n * The resolved connection options used to connect to the PowerSync service.\n *\n * @returns The resolved connection options used to connect to the PowerSync service or null if `connect()` has not been called.\n */\n get connectionOptions() {\n return this.connectionManager.connectionOptions;\n }\n _schema;\n _database;\n runExclusiveMutex;\n /**\n * @experimental\n * Allows creating SQLite triggers which can be used to track various operations on SQLite tables.\n */\n triggers;\n triggersImpl;\n logger;\n constructor(options) {\n super();\n this.options = options;\n const { database, schema } = options;\n if (typeof schema?.toJSON != 'function') {\n throw new Error('The `schema` option should be provided and should be an instance of `Schema`.');\n }\n if (isDBAdapter(database)) {\n this._database = database;\n }\n else if (isSQLOpenFactory(database)) {\n this._database = database.openDB();\n }\n else if (isPowerSyncDatabaseOptionsWithSettings(options)) {\n this._database = this.openDBAdapter(options);\n }\n else {\n throw new Error('The provided `database` option is invalid.');\n }\n this.logger = options.logger ?? Logger.get(`PowerSyncDatabase[${this._database.name}]`);\n this.bucketStorageAdapter = this.generateBucketStorageAdapter();\n this.closed = false;\n this.currentStatus = new SyncStatus({});\n this.options = { ...DEFAULT_POWERSYNC_DB_OPTIONS, ...options };\n this._schema = schema;\n this.ready = false;\n this.sdkVersion = '';\n this.runExclusiveMutex = new Mutex();\n // Start async init\n this.subscriptions = {\n firstStatusMatching: (predicate, abort) => this.waitForStatus(predicate, abort),\n resolveOfflineSyncStatus: () => this.resolveOfflineSyncStatus(),\n rustSubscriptionsCommand: async (payload) => {\n await this.writeTransaction((tx) => {\n return tx.execute('select powersync_control(?,?)', ['subscriptions', JSON.stringify(payload)]);\n });\n }\n };\n this.connectionManager = new ConnectionManager({\n createSyncImplementation: async (connector, options) => {\n await this.waitForReady();\n return this.runExclusive(async () => {\n const sync = this.generateSyncStreamImplementation(connector, this.resolvedConnectionOptions(options));\n const onDispose = sync.registerListener({\n statusChanged: (status) => {\n this.currentStatus = new SyncStatus({\n ...status.toJSON(),\n hasSynced: this.currentStatus?.hasSynced || !!status.lastSyncedAt\n });\n this.iterateListeners((cb) => cb.statusChanged?.(this.currentStatus));\n }\n });\n await sync.waitForReady();\n return {\n sync,\n onDispose\n };\n });\n },\n logger: this.logger\n });\n this._isReadyPromise = this.initialize();\n this.triggers = this.triggersImpl = new TriggerManagerImpl({\n db: this,\n schema: this.schema,\n ...this.generateTriggerManagerConfig()\n });\n }\n /**\n * Schema used for the local database.\n */\n get schema() {\n return this._schema;\n }\n /**\n * The underlying database.\n *\n * For the most part, behavior is the same whether querying on the underlying database, or on {@link AbstractPowerSyncDatabase}.\n */\n get database() {\n return this._database;\n }\n /**\n * Whether a connection to the PowerSync service is currently open.\n */\n get connected() {\n return this.currentStatus?.connected || false;\n }\n get connecting() {\n return this.currentStatus?.connecting || false;\n }\n /**\n * Generates a base configuration for {@link TriggerManagerImpl}.\n * Implementations should override this if necessary.\n */\n generateTriggerManagerConfig() {\n return {\n claimManager: MEMORY_TRIGGER_CLAIM_MANAGER\n };\n }\n /**\n * @returns A promise which will resolve once initialization is completed.\n */\n async waitForReady() {\n if (this.ready) {\n return;\n }\n await this._isReadyPromise;\n }\n /**\n * Wait for the first sync operation to complete.\n *\n * @param request Either an abort signal (after which the promise will complete regardless of\n * whether a full sync was completed) or an object providing an abort signal and a priority target.\n * When a priority target is set, the promise may complete when all buckets with the given (or higher)\n * priorities have been synchronized. This can be earlier than a complete sync.\n * @returns A promise which will resolve once the first full sync has completed.\n */\n async waitForFirstSync(request) {\n const signal = request instanceof AbortSignal ? request : request?.signal;\n const priority = request && 'priority' in request ? request.priority : undefined;\n const statusMatches = priority === undefined\n ? (status) => status.hasSynced\n : (status) => status.statusForPriority(priority).hasSynced;\n return this.waitForStatus(statusMatches, signal);\n }\n /**\n * Waits for the first sync status for which the `status` callback returns a truthy value.\n */\n async waitForStatus(predicate, signal) {\n if (predicate(this.currentStatus)) {\n return;\n }\n return new Promise((resolve) => {\n const dispose = this.registerListener({\n statusChanged: (status) => {\n if (predicate(status)) {\n abort();\n }\n }\n });\n function abort() {\n dispose();\n resolve();\n }\n if (signal?.aborted) {\n abort();\n }\n else {\n signal?.addEventListener('abort', abort);\n }\n });\n }\n /**\n * Entry point for executing initialization logic.\n * This is to be automatically executed in the constructor.\n */\n async initialize() {\n await this._initialize();\n await this.bucketStorageAdapter.init();\n await this.loadVersion();\n await this.updateSchema(this.options.schema);\n await this.resolveOfflineSyncStatus();\n await this.database.execute('PRAGMA RECURSIVE_TRIGGERS=TRUE');\n await this.triggersImpl.cleanupResources();\n this.ready = true;\n this.iterateListeners((cb) => cb.initialized?.());\n }\n async loadVersion() {\n try {\n const { version } = await this.database.get('SELECT powersync_rs_version() as version');\n this.sdkVersion = version;\n }\n catch (e) {\n throw new Error(`The powersync extension is not loaded correctly. Details: ${e.message}`);\n }\n let versionInts;\n try {\n versionInts = this.sdkVersion.split(/[.\\/]/)\n .slice(0, 3)\n .map((n) => parseInt(n));\n }\n catch (e) {\n throw new Error(`Unsupported powersync extension version. Need >=0.4.10 <1.0.0, got: ${this.sdkVersion}. Details: ${e.message}`);\n }\n // Validate >=0.4.10 <1.0.0\n if (versionInts[0] != 0 || versionInts[1] < 4 || (versionInts[1] == 4 && versionInts[2] < 10)) {\n throw new Error(`Unsupported powersync extension version. Need >=0.4.10 <1.0.0, got: ${this.sdkVersion}`);\n }\n }\n async resolveOfflineSyncStatus() {\n const result = await this.database.get('SELECT powersync_offline_sync_status() as r');\n const parsed = JSON.parse(result.r);\n const updatedStatus = new SyncStatus({\n ...this.currentStatus.toJSON(),\n ...coreStatusToJs(parsed)\n });\n if (!updatedStatus.isEqual(this.currentStatus)) {\n this.currentStatus = updatedStatus;\n this.iterateListeners((l) => l.statusChanged?.(this.currentStatus));\n }\n }\n /**\n * Replace the schema with a new version. This is for advanced use cases - typically the schema should just be specified once in the constructor.\n *\n * Cannot be used while connected - this should only be called before {@link AbstractPowerSyncDatabase.connect}.\n */\n async updateSchema(schema) {\n if (this.syncStreamImplementation) {\n throw new Error('Cannot update schema while connected');\n }\n /**\n * TODO\n * Validations only show a warning for now.\n * The next major release should throw an exception.\n */\n try {\n schema.validate();\n }\n catch (ex) {\n this.logger.warn('Schema validation failed. Unexpected behaviour could occur', ex);\n }\n this._schema = schema;\n await this.database.execute('SELECT powersync_replace_schema(?)', [JSON.stringify(this.schema.toJSON())]);\n await this.database.refreshSchema();\n this.iterateListeners(async (cb) => cb.schemaChanged?.(schema));\n }\n /**\n * Wait for initialization to complete.\n * While initializing is automatic, this helps to catch and report initialization errors.\n */\n async init() {\n return this.waitForReady();\n }\n // Use the options passed in during connect, or fallback to the options set during database creation or fallback to the default options\n resolvedConnectionOptions(options) {\n return {\n ...options,\n retryDelayMs: options?.retryDelayMs ?? this.options.retryDelayMs ?? this.options.retryDelay ?? DEFAULT_RETRY_DELAY_MS,\n crudUploadThrottleMs: options?.crudUploadThrottleMs ?? this.options.crudUploadThrottleMs ?? DEFAULT_CRUD_UPLOAD_THROTTLE_MS\n };\n }\n /**\n * @deprecated Use {@link AbstractPowerSyncDatabase#close} instead.\n * Clears all listeners registered by {@link AbstractPowerSyncDatabase#registerListener}.\n */\n dispose() {\n return super.dispose();\n }\n /**\n * Locking mechanism for exclusively running critical portions of connect/disconnect operations.\n * Locking here is mostly only important on web for multiple tab scenarios.\n */\n runExclusive(callback) {\n return this.runExclusiveMutex.runExclusive(callback);\n }\n /**\n * Connects to stream of events from the PowerSync instance.\n */\n async connect(connector, options) {\n const resolvedOptions = options ?? {};\n resolvedOptions.serializedSchema = this.schema.toJSON();\n return this.connectionManager.connect(connector, resolvedOptions);\n }\n /**\n * Close the sync connection.\n *\n * Use {@link connect} to connect again.\n */\n async disconnect() {\n return this.connectionManager.disconnect();\n }\n /**\n * Disconnect and clear the database.\n * Use this when logging out.\n * The database can still be queried after this is called, but the tables\n * would be empty.\n *\n * To preserve data in local-only tables, set clearLocal to false.\n */\n async disconnectAndClear(options = DEFAULT_DISCONNECT_CLEAR_OPTIONS) {\n await this.disconnect();\n await this.waitForReady();\n const { clearLocal } = options;\n await this.database.writeTransaction(async (tx) => {\n await tx.execute('SELECT powersync_clear(?)', [clearLocal ? 1 : 0]);\n });\n // The data has been deleted - reset the sync status\n this.currentStatus = new SyncStatus({});\n this.iterateListeners((l) => l.statusChanged?.(this.currentStatus));\n }\n /**\n * Create a sync stream to query its status or to subscribe to it.\n *\n * @param name The name of the stream to subscribe to.\n * @param params Optional parameters for the stream subscription.\n * @returns A {@link SyncStream} instance that can be subscribed to.\n * @experimental Sync streams are currently in alpha.\n */\n syncStream(name, params) {\n return this.connectionManager.stream(this.subscriptions, name, params ?? null);\n }\n /**\n * Close the database, releasing resources.\n *\n * Also disconnects any active connection.\n *\n * Once close is called, this connection cannot be used again - a new one\n * must be constructed.\n */\n async close(options = DEFAULT_POWERSYNC_CLOSE_OPTIONS) {\n await this.waitForReady();\n if (this.closed) {\n return;\n }\n this.triggersImpl.dispose();\n await this.iterateAsyncListeners(async (cb) => cb.closing?.());\n const { disconnect } = options;\n if (disconnect) {\n await this.disconnect();\n }\n await this.connectionManager.close();\n await this.database.close();\n this.closed = true;\n await this.iterateAsyncListeners(async (cb) => cb.closed?.());\n }\n /**\n * Get upload queue size estimate and count.\n */\n async getUploadQueueStats(includeSize) {\n return this.readTransaction(async (tx) => {\n if (includeSize) {\n const result = await tx.execute(`SELECT SUM(cast(data as blob) + 20) as size, count(*) as count FROM ${PSInternalTable.CRUD}`);\n const row = result.rows.item(0);\n return new UploadQueueStats(row?.count ?? 0, row?.size ?? 0);\n }\n else {\n const result = await tx.execute(`SELECT count(*) as count FROM ${PSInternalTable.CRUD}`);\n const row = result.rows.item(0);\n return new UploadQueueStats(row?.count ?? 0);\n }\n });\n }\n /**\n * Get a batch of CRUD data to upload.\n *\n * Returns null if there is no data to upload.\n *\n * Use this from the {@link PowerSyncBackendConnector.uploadData} callback.\n *\n * Once the data have been successfully uploaded, call {@link CrudBatch.complete} before\n * requesting the next batch.\n *\n * Use {@link limit} to specify the maximum number of updates to return in a single\n * batch.\n *\n * This method does include transaction ids in the result, but does not group\n * data by transaction. One batch may contain data from multiple transactions,\n * and a single transaction may be split over multiple batches.\n *\n * @param limit Maximum number of CRUD entries to include in the batch\n * @returns A batch of CRUD operations to upload, or null if there are none\n */\n async getCrudBatch(limit = DEFAULT_CRUD_BATCH_LIMIT) {\n const result = await this.getAll(`SELECT id, tx_id, data FROM ${PSInternalTable.CRUD} ORDER BY id ASC LIMIT ?`, [limit + 1]);\n const all = result.map((row) => CrudEntry.fromRow(row)) ?? [];\n let haveMore = false;\n if (all.length > limit) {\n all.pop();\n haveMore = true;\n }\n if (all.length == 0) {\n return null;\n }\n const last = all[all.length - 1];\n return new CrudBatch(all, haveMore, async (writeCheckpoint) => this.handleCrudCheckpoint(last.clientId, writeCheckpoint));\n }\n /**\n * Get the next recorded transaction to upload.\n *\n * Returns null if there is no data to upload.\n *\n * Use this from the {@link PowerSyncBackendConnector.uploadData} callback.\n *\n * Once the data have been successfully uploaded, call {@link CrudTransaction.complete} before\n * requesting the next transaction.\n *\n * Unlike {@link getCrudBatch}, this only returns data from a single transaction at a time.\n * All data for the transaction is loaded into memory.\n *\n * @returns A transaction of CRUD operations to upload, or null if there are none\n */\n async getNextCrudTransaction() {\n const iterator = this.getCrudTransactions()[symbolAsyncIterator]();\n return (await iterator.next()).value;\n }\n /**\n * Returns an async iterator of completed transactions with local writes against the database.\n *\n * This is typically used from the {@link PowerSyncBackendConnector.uploadData} callback. Each entry emitted by the\n * returned iterator is a full transaction containing all local writes made while that transaction was active.\n *\n * Unlike {@link getNextCrudTransaction}, which always returns the oldest transaction that hasn't been\n * {@link CrudTransaction.complete}d yet, this iterator can be used to receive multiple transactions. Calling\n * {@link CrudTransaction.complete} will mark that and all prior transactions emitted by the iterator as completed.\n *\n * This can be used to upload multiple transactions in a single batch, e.g with:\n *\n * ```JavaScript\n * let lastTransaction = null;\n * let batch = [];\n *\n * for await (const transaction of database.getCrudTransactions()) {\n * batch.push(...transaction.crud);\n * lastTransaction = transaction;\n *\n * if (batch.length > 10) {\n * break;\n * }\n * }\n * ```\n *\n * If there is no local data to upload, the async iterator complete without emitting any items.\n *\n * Note that iterating over async iterables requires a [polyfill](https://github.com/powersync-ja/powersync-js/tree/main/packages/react-native#babel-plugins-watched-queries)\n * for React Native.\n */\n getCrudTransactions() {\n return {\n [symbolAsyncIterator]: () => {\n let lastCrudItemId = -1;\n const sql = `\nWITH RECURSIVE crud_entries AS (\n SELECT id, tx_id, data FROM ps_crud WHERE id = (SELECT min(id) FROM ps_crud WHERE id > ?)\n UNION ALL\n SELECT ps_crud.id, ps_crud.tx_id, ps_crud.data FROM ps_crud\n INNER JOIN crud_entries ON crud_entries.id + 1 = rowid\n WHERE crud_entries.tx_id = ps_crud.tx_id\n)\nSELECT * FROM crud_entries;\n `;\n return {\n next: async () => {\n const nextTransaction = await this.database.getAll(sql, [lastCrudItemId]);\n if (nextTransaction.length == 0) {\n return { done: true, value: null };\n }\n const items = nextTransaction.map((row) => CrudEntry.fromRow(row));\n const last = items[items.length - 1];\n const txId = last.transactionId;\n lastCrudItemId = last.clientId;\n return {\n done: false,\n value: new CrudTransaction(items, async (writeCheckpoint) => this.handleCrudCheckpoint(last.clientId, writeCheckpoint), txId)\n };\n }\n };\n }\n };\n }\n /**\n * Get an unique client id for this database.\n *\n * The id is not reset when the database is cleared, only when the database is deleted.\n *\n * @returns A unique identifier for the database instance\n */\n async getClientId() {\n return this.bucketStorageAdapter.getClientId();\n }\n async handleCrudCheckpoint(lastClientId, writeCheckpoint) {\n return this.writeTransaction(async (tx) => {\n await tx.execute(`DELETE FROM ${PSInternalTable.CRUD} WHERE id <= ?`, [lastClientId]);\n if (writeCheckpoint) {\n const check = await tx.execute(`SELECT 1 FROM ${PSInternalTable.CRUD} LIMIT 1`);\n if (!check.rows?.length) {\n await tx.execute(`UPDATE ${PSInternalTable.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`, [\n writeCheckpoint\n ]);\n }\n }\n else {\n await tx.execute(`UPDATE ${PSInternalTable.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`, [\n this.bucketStorageAdapter.getMaxOpId()\n ]);\n }\n });\n }\n /**\n * Execute a SQL write (INSERT/UPDATE/DELETE) query\n * and optionally return results.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @returns The query result as an object with structured key-value pairs\n */\n async execute(sql, parameters) {\n return this.writeLock((tx) => tx.execute(sql, parameters));\n }\n /**\n * Execute a SQL write (INSERT/UPDATE/DELETE) query directly on the database without any PowerSync processing.\n * This bypasses certain PowerSync abstractions and is useful for accessing the raw database results.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @returns The raw query result from the underlying database as a nested array of raw values, where each row is\n * represented as an array of column values without field names.\n */\n async executeRaw(sql, parameters) {\n await this.waitForReady();\n return this.database.executeRaw(sql, parameters);\n }\n /**\n * Execute a write query (INSERT/UPDATE/DELETE) multiple times with each parameter set\n * and optionally return results.\n * This is faster than executing separately with each parameter set.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional 2D array of parameter sets, where each inner array is a set of parameters for one execution\n * @returns The query result\n */\n async executeBatch(sql, parameters) {\n await this.waitForReady();\n return this.database.executeBatch(sql, parameters);\n }\n /**\n * Execute a read-only query and return results.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @returns An array of results\n */\n async getAll(sql, parameters) {\n await this.waitForReady();\n return this.database.getAll(sql, parameters);\n }\n /**\n * Execute a read-only query and return the first result, or null if the ResultSet is empty.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @returns The first result if found, or null if no results are returned\n */\n async getOptional(sql, parameters) {\n await this.waitForReady();\n return this.database.getOptional(sql, parameters);\n }\n /**\n * Execute a read-only query and return the first result, error if the ResultSet is empty.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @returns The first result matching the query\n * @throws Error if no rows are returned\n */\n async get(sql, parameters) {\n await this.waitForReady();\n return this.database.get(sql, parameters);\n }\n /**\n * Takes a read lock, without starting a transaction.\n * In most cases, {@link readTransaction} should be used instead.\n */\n async readLock(callback) {\n await this.waitForReady();\n return this.database.readLock(callback);\n }\n /**\n * Takes a global lock, without starting a transaction.\n * In most cases, {@link writeTransaction} should be used instead.\n */\n async writeLock(callback) {\n await this.waitForReady();\n return this.database.writeLock(callback);\n }\n /**\n * Open a read-only transaction.\n * Read transactions can run concurrently to a write transaction.\n * Changes from any write transaction are not visible to read transactions started before it.\n *\n * @param callback Function to execute within the transaction\n * @param lockTimeout Time in milliseconds to wait for a lock before throwing an error\n * @returns The result of the callback\n * @throws Error if the lock cannot be obtained within the timeout period\n */\n async readTransaction(callback, lockTimeout = DEFAULT_LOCK_TIMEOUT_MS) {\n await this.waitForReady();\n return this.database.readTransaction(async (tx) => {\n const res = await callback({ ...tx });\n await tx.rollback();\n return res;\n }, { timeoutMs: lockTimeout });\n }\n /**\n * Open a read-write transaction.\n * This takes a global lock - only one write transaction can execute against the database at a time.\n * Statements within the transaction must be done on the provided {@link Transaction} interface.\n *\n * @param callback Function to execute within the transaction\n * @param lockTimeout Time in milliseconds to wait for a lock before throwing an error\n * @returns The result of the callback\n * @throws Error if the lock cannot be obtained within the timeout period\n */\n async writeTransaction(callback, lockTimeout = DEFAULT_LOCK_TIMEOUT_MS) {\n await this.waitForReady();\n return this.database.writeTransaction(async (tx) => {\n const res = await callback(tx);\n await tx.commit();\n return res;\n }, { timeoutMs: lockTimeout });\n }\n watch(sql, parameters, handlerOrOptions, maybeOptions) {\n if (handlerOrOptions && typeof handlerOrOptions === 'object' && 'onResult' in handlerOrOptions) {\n const handler = handlerOrOptions;\n const options = maybeOptions;\n return this.watchWithCallback(sql, parameters, handler, options);\n }\n const options = handlerOrOptions;\n return this.watchWithAsyncGenerator(sql, parameters, options);\n }\n /**\n * Allows defining a query which can be used to build a {@link WatchedQuery}.\n * The defined query will be executed with {@link AbstractPowerSyncDatabase#getAll}.\n * An optional mapper function can be provided to transform the results.\n *\n * @example\n * ```javascript\n * const watchedTodos = powersync.query({\n * sql: `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,\n * parameters: [],\n * mapper: (row) => ({\n * ...row,\n * created_at: new Date(row.created_at as string)\n * })\n * })\n * .watch()\n * // OR use .differentialWatch() for fine-grained watches.\n * ```\n */\n query(query) {\n const { sql, parameters = [], mapper } = query;\n const compatibleQuery = {\n compile: () => ({\n sql,\n parameters\n }),\n execute: async ({ sql, parameters }) => {\n const result = await this.getAll(sql, parameters);\n return mapper ? result.map(mapper) : result;\n }\n };\n return this.customQuery(compatibleQuery);\n }\n /**\n * Allows building a {@link WatchedQuery} using an existing {@link WatchCompatibleQuery}.\n * The watched query will use the provided {@link WatchCompatibleQuery.execute} method to query results.\n *\n * @example\n * ```javascript\n *\n * // Potentially a query from an ORM like Drizzle\n * const query = db.select().from(lists);\n *\n * const watchedTodos = powersync.customQuery(query)\n * .watch()\n * // OR use .differentialWatch() for fine-grained watches.\n * ```\n */\n customQuery(query) {\n return new CustomQuery({\n db: this,\n query\n });\n }\n /**\n * Execute a read query every time the source tables are modified.\n * Use {@link SQLWatchOptions.throttleMs} to specify the minimum interval between queries.\n * Source tables are automatically detected using `EXPLAIN QUERY PLAN`.\n *\n * Note that the `onChange` callback member of the handler is required.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @param handler Callbacks for handling results and errors\n * @param options Options for configuring watch behavior\n */\n watchWithCallback(sql, parameters, handler, options) {\n const { onResult, onError = (e) => this.logger.error(e) } = handler ?? {};\n if (!onResult) {\n throw new Error('onResult is required');\n }\n const { comparator } = options ?? {};\n // This API yields a QueryResult type.\n // This is not a standard Array result, which makes it incompatible with the .query API.\n const watchedQuery = new OnChangeQueryProcessor({\n db: this,\n comparator,\n placeholderData: null,\n watchOptions: {\n query: {\n compile: () => ({\n sql: sql,\n parameters: parameters ?? []\n }),\n execute: () => this.executeReadOnly(sql, parameters)\n },\n reportFetching: false,\n throttleMs: options?.throttleMs ?? DEFAULT_WATCH_THROTTLE_MS,\n triggerOnTables: options?.tables\n }\n });\n const dispose = watchedQuery.registerListener({\n onData: (data) => {\n if (!data) {\n // This should not happen. We only use null for the initial data.\n return;\n }\n onResult(data);\n },\n onError: (error) => {\n onError(error);\n }\n });\n options?.signal?.addEventListener('abort', () => {\n dispose();\n watchedQuery.close();\n });\n }\n /**\n * Execute a read query every time the source tables are modified.\n * Use {@link SQLWatchOptions.throttleMs} to specify the minimum interval between queries.\n * Source tables are automatically detected using `EXPLAIN QUERY PLAN`.\n *\n * @param sql The SQL query to execute\n * @param parameters Optional array of parameters to bind to the query\n * @param options Options for configuring watch behavior\n * @returns An AsyncIterable that yields QueryResults whenever the data changes\n */\n watchWithAsyncGenerator(sql, parameters, options) {\n return new domExports.EventIterator((eventOptions) => {\n const handler = {\n onResult: (result) => {\n eventOptions.push(result);\n },\n onError: (error) => {\n eventOptions.fail(error);\n }\n };\n this.watchWithCallback(sql, parameters, handler, options);\n options?.signal?.addEventListener('abort', () => {\n eventOptions.stop();\n });\n });\n }\n /**\n * Resolves the list of tables that are used in a SQL query.\n * If tables are specified in the options, those are used directly.\n * Otherwise, analyzes the query using EXPLAIN to determine which tables are accessed.\n *\n * @param sql The SQL query to analyze\n * @param parameters Optional parameters for the SQL query\n * @param options Optional watch options that may contain explicit table list\n * @returns Array of table names that the query depends on\n */\n async resolveTables(sql, parameters, options) {\n const resolvedTables = options?.tables ? [...options.tables] : [];\n if (!options?.tables) {\n const explained = await this.getAll(`EXPLAIN ${sql}`, parameters);\n const rootPages = explained\n .filter((row) => row.opcode == 'OpenRead' && row.p3 == 0 && typeof row.p2 == 'number')\n .map((row) => row.p2);\n const tables = await this.getAll(`SELECT DISTINCT tbl_name FROM sqlite_master WHERE rootpage IN (SELECT json_each.value FROM json_each(?))`, [JSON.stringify(rootPages)]);\n for (const table of tables) {\n resolvedTables.push(table.tbl_name.replace(POWERSYNC_TABLE_MATCH, ''));\n }\n }\n return resolvedTables;\n }\n onChange(handlerOrOptions, maybeOptions) {\n if (handlerOrOptions && typeof handlerOrOptions === 'object' && 'onChange' in handlerOrOptions) {\n const handler = handlerOrOptions;\n const options = maybeOptions;\n return this.onChangeWithCallback(handler, options);\n }\n const options = handlerOrOptions;\n return this.onChangeWithAsyncGenerator(options);\n }\n /**\n * Invoke the provided callback on any changes to any of the specified tables.\n *\n * This is preferred over {@link watchWithCallback} when multiple queries need to be performed\n * together when data is changed.\n *\n * Note that the `onChange` callback member of the handler is required.\n *\n * @param handler Callbacks for handling change events and errors\n * @param options Options for configuring watch behavior\n * @returns A dispose function to stop watching for changes\n */\n onChangeWithCallback(handler, options) {\n const { onChange, onError = (e) => this.logger.error(e) } = handler ?? {};\n if (!onChange) {\n throw new Error('onChange is required');\n }\n const resolvedOptions = options ?? {};\n const watchedTables = new Set((resolvedOptions?.tables ?? []).flatMap((table) => [table, `ps_data__${table}`, `ps_data_local__${table}`]));\n const changedTables = new Set();\n const throttleMs = resolvedOptions.throttleMs ?? DEFAULT_WATCH_THROTTLE_MS;\n const executor = new ControlledExecutor(async (e) => {\n await onChange(e);\n });\n const flushTableUpdates = throttleTrailing(() => this.handleTableChanges(changedTables, watchedTables, (intersection) => {\n if (resolvedOptions?.signal?.aborted)\n return;\n executor.schedule({ changedTables: intersection });\n }), throttleMs);\n if (options?.triggerImmediate) {\n executor.schedule({ changedTables: [] });\n }\n const dispose = this.database.registerListener({\n tablesUpdated: async (update) => {\n try {\n this.processTableUpdates(update, changedTables);\n flushTableUpdates();\n }\n catch (error) {\n onError?.(error);\n }\n }\n });\n resolvedOptions.signal?.addEventListener('abort', () => {\n executor.dispose();\n dispose();\n });\n return () => dispose();\n }\n /**\n * Create a Stream of changes to any of the specified tables.\n *\n * This is preferred over {@link watchWithAsyncGenerator} when multiple queries need to be performed\n * together when data is changed.\n *\n * Note: do not declare this as `async *onChange` as it will not work in React Native.\n *\n * @param options Options for configuring watch behavior\n * @returns An AsyncIterable that yields change events whenever the specified tables change\n */\n onChangeWithAsyncGenerator(options) {\n const resolvedOptions = options ?? {};\n return new domExports.EventIterator((eventOptions) => {\n const dispose = this.onChangeWithCallback({\n onChange: (event) => {\n eventOptions.push(event);\n },\n onError: (error) => {\n eventOptions.fail(error);\n }\n }, options);\n resolvedOptions.signal?.addEventListener('abort', () => {\n eventOptions.stop();\n // Maybe fail?\n });\n return () => dispose();\n });\n }\n handleTableChanges(changedTables, watchedTables, onDetectedChanges) {\n if (changedTables.size > 0) {\n const intersection = Array.from(changedTables.values()).filter((change) => watchedTables.has(change));\n if (intersection.length) {\n onDetectedChanges(intersection);\n }\n }\n changedTables.clear();\n }\n processTableUpdates(updateNotification, changedTables) {\n const tables = isBatchedUpdateNotification(updateNotification)\n ? updateNotification.tables\n : [updateNotification.table];\n for (const table of tables) {\n changedTables.add(table);\n }\n }\n /**\n * @ignore\n */\n async executeReadOnly(sql, params) {\n await this.waitForReady();\n return this.database.readLock((tx) => tx.execute(sql, params));\n }\n}\n\nclass AbstractPowerSyncDatabaseOpenFactory {\n options;\n constructor(options) {\n this.options = options;\n options.logger = options.logger ?? Logger.get(`PowerSync ${this.options.dbFilename}`);\n }\n /**\n * Schema used for the local database.\n */\n get schema() {\n return this.options.schema;\n }\n generateOptions() {\n return {\n database: this.openDB(),\n ...this.options\n };\n }\n getInstance() {\n const options = this.generateOptions();\n return this.generateInstance(options);\n }\n}\n\nfunction runOnSchemaChange(callback, db, options) {\n const triggerWatchedQuery = () => {\n const abortController = new AbortController();\n let disposeSchemaListener = null;\n const stopWatching = () => {\n abortController.abort('Abort triggered');\n disposeSchemaListener?.();\n disposeSchemaListener = null;\n // Stop listening to upstream abort for this watch\n options?.signal?.removeEventListener('abort', stopWatching);\n };\n options?.signal?.addEventListener('abort', stopWatching);\n disposeSchemaListener = db.registerListener({\n schemaChanged: async () => {\n stopWatching();\n // Re trigger the watched query (recursively), setTimeout ensures that we don't modify the list of listeners while iterating through them\n setTimeout(() => triggerWatchedQuery(), 0);\n }\n });\n callback(abortController.signal);\n };\n triggerWatchedQuery();\n}\n\nfunction compilableQueryWatch(db, query, handler, options) {\n const { onResult, onError = (e) => { } } = handler ?? {};\n if (!onResult) {\n throw new Error('onResult is required');\n }\n const watchQuery = async (abortSignal) => {\n try {\n const toSql = query.compile();\n const resolvedTables = await db.resolveTables(toSql.sql, toSql.parameters, options);\n // Fetch initial data\n const result = await query.execute();\n onResult(result);\n db.onChangeWithCallback({\n onChange: async () => {\n try {\n const result = await query.execute();\n onResult(result);\n }\n catch (error) {\n onError(error);\n }\n },\n onError\n }, {\n ...(options ?? {}),\n tables: resolvedTables,\n // Override the abort signal since we intercept it\n signal: abortSignal\n });\n }\n catch (error) {\n onError(error);\n }\n };\n runOnSchemaChange(watchQuery, db, options);\n}\n\nconst MAX_OP_ID = '9223372036854775807';\n\nclass SqliteBucketStorage extends BaseObserver {\n db;\n logger;\n tableNames;\n _hasCompletedSync;\n updateListener;\n _clientId;\n constructor(db, logger = Logger.get('SqliteBucketStorage')) {\n super();\n this.db = db;\n this.logger = logger;\n this._hasCompletedSync = false;\n this.tableNames = new Set();\n this.updateListener = db.registerListener({\n tablesUpdated: (update) => {\n const tables = extractTableUpdates(update);\n if (tables.includes(PSInternalTable.CRUD)) {\n this.iterateListeners((l) => l.crudUpdate?.());\n }\n }\n });\n }\n async init() {\n this._hasCompletedSync = false;\n const existingTableRows = await this.db.getAll(`SELECT name FROM sqlite_master WHERE type='table' AND name GLOB 'ps_data_*'`);\n for (const row of existingTableRows ?? []) {\n this.tableNames.add(row.name);\n }\n }\n async dispose() {\n this.updateListener?.();\n }\n async _getClientId() {\n const row = await this.db.get('SELECT powersync_client_id() as client_id');\n return row['client_id'];\n }\n getClientId() {\n if (this._clientId == null) {\n this._clientId = this._getClientId();\n }\n return this._clientId;\n }\n getMaxOpId() {\n return MAX_OP_ID;\n }\n /**\n * Reset any caches.\n */\n startSession() { }\n async getBucketStates() {\n const result = await this.db.getAll(\"SELECT name as bucket, cast(last_op as TEXT) as op_id FROM ps_buckets WHERE pending_delete = 0 AND name != '$local'\");\n return result;\n }\n async getBucketOperationProgress() {\n const rows = await this.db.getAll('SELECT name, count_at_last, count_since_last FROM ps_buckets');\n return Object.fromEntries(rows.map((r) => [r.name, { atLast: r.count_at_last, sinceLast: r.count_since_last }]));\n }\n async saveSyncData(batch, fixedKeyFormat = false) {\n await this.writeTransaction(async (tx) => {\n for (const b of batch.buckets) {\n await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', [\n 'save',\n JSON.stringify({ buckets: [b.toJSON(fixedKeyFormat)] })\n ]);\n this.logger.debug(`Saved batch of data for bucket: ${b.bucket}, operations: ${b.data.length}`);\n }\n });\n }\n async removeBuckets(buckets) {\n for (const bucket of buckets) {\n await this.deleteBucket(bucket);\n }\n }\n /**\n * Mark a bucket for deletion.\n */\n async deleteBucket(bucket) {\n await this.writeTransaction(async (tx) => {\n await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', ['delete_bucket', bucket]);\n });\n this.logger.debug(`Done deleting bucket ${bucket}`);\n }\n async hasCompletedSync() {\n if (this._hasCompletedSync) {\n return true;\n }\n const r = await this.db.get(`SELECT powersync_last_synced_at() as synced_at`);\n const completed = r.synced_at != null;\n if (completed) {\n this._hasCompletedSync = true;\n }\n return completed;\n }\n async syncLocalDatabase(checkpoint, priority) {\n const r = await this.validateChecksums(checkpoint, priority);\n if (!r.checkpointValid) {\n this.logger.error('Checksums failed for', r.checkpointFailures);\n for (const b of r.checkpointFailures ?? []) {\n await this.deleteBucket(b);\n }\n return { ready: false, checkpointValid: false, checkpointFailures: r.checkpointFailures };\n }\n if (priority == null) {\n this.logger.debug(`Validated checksums checkpoint ${checkpoint.last_op_id}`);\n }\n else {\n this.logger.debug(`Validated checksums for partial checkpoint ${checkpoint.last_op_id}, priority ${priority}`);\n }\n let buckets = checkpoint.buckets;\n if (priority !== undefined) {\n buckets = buckets.filter((b) => hasMatchingPriority(priority, b));\n }\n const bucketNames = buckets.map((b) => b.bucket);\n await this.writeTransaction(async (tx) => {\n await tx.execute(`UPDATE ps_buckets SET last_op = ? WHERE name IN (SELECT json_each.value FROM json_each(?))`, [\n checkpoint.last_op_id,\n JSON.stringify(bucketNames)\n ]);\n if (priority == null && checkpoint.write_checkpoint) {\n await tx.execute(\"UPDATE ps_buckets SET last_op = ? WHERE name = '$local'\", [checkpoint.write_checkpoint]);\n }\n });\n const valid = await this.updateObjectsFromBuckets(checkpoint, priority);\n if (!valid) {\n return { ready: false, checkpointValid: true };\n }\n return {\n ready: true,\n checkpointValid: true\n };\n }\n /**\n * Atomically update the local state to the current checkpoint.\n *\n * This includes creating new tables, dropping old tables, and copying data over from the oplog.\n */\n async updateObjectsFromBuckets(checkpoint, priority) {\n let arg = '';\n if (priority !== undefined) {\n const affectedBuckets = [];\n for (const desc of checkpoint.buckets) {\n if (hasMatchingPriority(priority, desc)) {\n affectedBuckets.push(desc.bucket);\n }\n }\n arg = JSON.stringify({ priority, buckets: affectedBuckets });\n }\n return this.writeTransaction(async (tx) => {\n const { insertId: result } = await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', [\n 'sync_local',\n arg\n ]);\n if (result == 1) {\n if (priority == null) {\n const bucketToCount = Object.fromEntries(checkpoint.buckets.map((b) => [b.bucket, b.count]));\n // The two parameters could be replaced with one, but: https://github.com/powersync-ja/better-sqlite3/pull/6\n const jsonBucketCount = JSON.stringify(bucketToCount);\n await tx.execute(\"UPDATE ps_buckets SET count_since_last = 0, count_at_last = ?->name WHERE name != '$local' AND ?->name IS NOT NULL\", [jsonBucketCount, jsonBucketCount]);\n }\n return true;\n }\n else {\n return false;\n }\n });\n }\n async validateChecksums(checkpoint, priority) {\n if (priority !== undefined) {\n // Only validate the buckets within the priority we care about\n const newBuckets = checkpoint.buckets.filter((cs) => hasMatchingPriority(priority, cs));\n checkpoint = { ...checkpoint, buckets: newBuckets };\n }\n const rs = await this.db.execute('SELECT powersync_validate_checkpoint(?) as result', [\n JSON.stringify({ ...checkpoint })\n ]);\n const resultItem = rs.rows?.item(0);\n if (!resultItem) {\n return {\n checkpointValid: false,\n ready: false,\n checkpointFailures: []\n };\n }\n const result = JSON.parse(resultItem['result']);\n if (result['valid']) {\n return { ready: true, checkpointValid: true };\n }\n else {\n return {\n checkpointValid: false,\n ready: false,\n checkpointFailures: result['failed_buckets']\n };\n }\n }\n async updateLocalTarget(cb) {\n const rs1 = await this.db.getAll(\"SELECT target_op FROM ps_buckets WHERE name = '$local' AND target_op = CAST(? as INTEGER)\", [MAX_OP_ID]);\n if (!rs1.length) {\n // Nothing to update\n return false;\n }\n const rs = await this.db.getAll(\"SELECT seq FROM main.sqlite_sequence WHERE name = 'ps_crud'\");\n if (!rs.length) {\n // Nothing to update\n return false;\n }\n const seqBefore = rs[0]['seq'];\n const opId = await cb();\n return this.writeTransaction(async (tx) => {\n const anyData = await tx.execute('SELECT 1 FROM ps_crud LIMIT 1');\n if (anyData.rows?.length) {\n // if isNotEmpty\n this.logger.debug(`New data uploaded since write checkpoint ${opId} - need new write checkpoint`);\n return false;\n }\n const rs = await tx.execute(\"SELECT seq FROM main.sqlite_sequence WHERE name = 'ps_crud'\");\n if (!rs.rows?.length) {\n // assert isNotEmpty\n throw new Error('SQLite Sequence should not be empty');\n }\n const seqAfter = rs.rows?.item(0)['seq'];\n if (seqAfter != seqBefore) {\n this.logger.debug(`New data uploaded since write checpoint ${opId} - need new write checkpoint (sequence updated)`);\n // New crud data may have been uploaded since we got the checkpoint. Abort.\n return false;\n }\n this.logger.debug(`Updating target write checkpoint to ${opId}`);\n await tx.execute(\"UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'\", [opId]);\n return true;\n });\n }\n async nextCrudItem() {\n const next = await this.db.getOptional('SELECT * FROM ps_crud ORDER BY id ASC LIMIT 1');\n if (!next) {\n return;\n }\n return CrudEntry.fromRow(next);\n }\n async hasCrud() {\n const anyData = await this.db.getOptional('SELECT 1 FROM ps_crud LIMIT 1');\n return !!anyData;\n }\n /**\n * Get a batch of objects to send to the server.\n * When the objects are successfully sent to the server, call .complete()\n */\n async getCrudBatch(limit = 100) {\n if (!(await this.hasCrud())) {\n return null;\n }\n const crudResult = await this.db.getAll('SELECT * FROM ps_crud ORDER BY id ASC LIMIT ?', [limit]);\n const all = [];\n for (const row of crudResult) {\n all.push(CrudEntry.fromRow(row));\n }\n if (all.length === 0) {\n return null;\n }\n const last = all[all.length - 1];\n return {\n crud: all,\n haveMore: true,\n complete: async (writeCheckpoint) => {\n return this.writeTransaction(async (tx) => {\n await tx.execute('DELETE FROM ps_crud WHERE id <= ?', [last.clientId]);\n if (writeCheckpoint) {\n const crudResult = await tx.execute('SELECT 1 FROM ps_crud LIMIT 1');\n if (crudResult.rows?.length) {\n await tx.execute(\"UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'\", [\n writeCheckpoint\n ]);\n }\n }\n else {\n await tx.execute(\"UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'\", [\n this.getMaxOpId()\n ]);\n }\n });\n }\n };\n }\n async writeTransaction(callback, options) {\n return this.db.writeTransaction(callback, options);\n }\n /**\n * Set a target checkpoint.\n */\n async setTargetCheckpoint(checkpoint) {\n // No-op for now\n }\n async control(op, payload) {\n return await this.writeTransaction(async (tx) => {\n const [[raw]] = await tx.executeRaw('SELECT powersync_control(?, ?)', [op, payload]);\n return raw;\n });\n }\n async hasMigratedSubkeys() {\n const { r } = await this.db.get('SELECT EXISTS(SELECT * FROM ps_kv WHERE key = ?) as r', [\n SqliteBucketStorage._subkeyMigrationKey\n ]);\n return r != 0;\n }\n async migrateToFixedSubkeys() {\n await this.writeTransaction(async (tx) => {\n await tx.execute('UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);');\n await tx.execute('INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);', [\n SqliteBucketStorage._subkeyMigrationKey,\n '1'\n ]);\n });\n }\n static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';\n}\nfunction hasMatchingPriority(priority, bucket) {\n return bucket.priority != null && bucket.priority <= priority;\n}\n\n// TODO JSON\nclass SyncDataBatch {\n buckets;\n static fromJSON(json) {\n return new SyncDataBatch(json.buckets.map((bucket) => SyncDataBucket.fromRow(bucket)));\n }\n constructor(buckets) {\n this.buckets = buckets;\n }\n}\n\n/**\n * Thrown when an underlying database connection is closed.\n * This is particularly relevant when worker connections are marked as closed while\n * operations are still in progress.\n */\nclass ConnectionClosedError extends Error {\n static NAME = 'ConnectionClosedError';\n static MATCHES(input) {\n /**\n * If there are weird package issues which cause multiple versions of classes to be present, the instanceof\n * check might fail. This also performs a failsafe check.\n * This might also happen if the Error is serialized and parsed over a bridging channel like a MessagePort.\n */\n return (input instanceof ConnectionClosedError || (input instanceof Error && input.name == ConnectionClosedError.NAME));\n }\n constructor(message) {\n super(message);\n this.name = ConnectionClosedError.NAME;\n }\n}\n\n/**\n * A schema is a collection of tables. It is used to define the structure of a database.\n */\nclass Schema {\n /*\n Only available when constructing with mapped typed definition columns\n */\n types;\n props;\n tables;\n rawTables;\n constructor(tables) {\n if (Array.isArray(tables)) {\n /*\n We need to validate that the tables have a name here because a user could pass in an array\n of Tables that don't have a name because they are using the V2 syntax.\n Therefore, 'convertToClassicTables' won't be called on the tables resulting in a runtime error.\n */\n for (const table of tables) {\n if (table.name === '') {\n throw new Error(\"It appears you are trying to create a new Schema with an array instead of an object. Passing in an object instead of an array into 'new Schema()' may resolve your issue.\");\n }\n }\n this.tables = tables;\n }\n else {\n // Update the table entries with the provided table name key\n this.props = Object.fromEntries(Object.entries(tables).map(([tableName, table]) => [tableName, table.copyWithName(tableName)]));\n this.tables = Object.values(this.props);\n }\n this.rawTables = [];\n }\n /**\n * Adds raw tables to this schema. Raw tables are identified by their name, but entirely managed by the application\n * developer instead of automatically by PowerSync.\n * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow\n * using client-side table and column constraints.\n * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.\n *\n * @param tables An object of (table name, raw table definition) entries.\n * @experimental Note that the raw tables API is still experimental and may change in the future.\n */\n withRawTables(tables) {\n for (const [name, rawTableDefinition] of Object.entries(tables)) {\n this.rawTables.push({ name, ...rawTableDefinition });\n }\n }\n validate() {\n for (const table of this.tables) {\n table.validate();\n }\n }\n toJSON() {\n return {\n tables: this.tables.map((t) => t.toJSON()),\n raw_tables: this.rawTables.map(Schema.rawTableToJson)\n };\n }\n /**\n * Returns a representation of the raw table that is understood by the PowerSync SQLite core extension.\n *\n * The output of this can be passed through `JSON.serialize` and then used in `powersync_create_raw_table_crud_trigger`\n * to define triggers for this table.\n */\n static rawTableToJson(table) {\n const serialized = {\n name: table.name,\n put: table.put,\n delete: table.delete,\n clear: table.clear\n };\n if ('schema' in table) {\n // We have schema options, those are flattened into the outer JSON object for the core extension.\n const schema = table.schema;\n serialized.table_name = schema.tableName ?? table.name;\n serialized.synced_columns = schema.syncedColumns;\n Object.assign(serialized, encodeTableOptions(table.schema));\n }\n return serialized;\n }\n}\n\n/**\n Generate a new table from the columns and indexes\n @deprecated You should use {@link Table} instead as it now allows TableV2 syntax.\n This will be removed in the next major release.\n*/\nclass TableV2 extends Table {\n}\n\nfunction sanitizeString(input) {\n return `'${input.replace(/'/g, \"''\")}'`;\n}\n/**\n * Helper function for sanitizing UUID input strings.\n * Typically used with {@link sanitizeSQL}.\n */\nfunction sanitizeUUID(uuid) {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n const isValid = uuidRegex.test(uuid);\n if (!isValid) {\n throw new Error(`${uuid} is not a valid UUID`);\n }\n return uuid;\n}\n/**\n * SQL string template function for {@link TrackDiffOptions#when} and {@link CreateDiffTriggerOptions#when}.\n *\n * This function performs basic string interpolation for SQLite WHEN clauses.\n *\n * **String placeholders:**\n * - All string values passed as placeholders are automatically wrapped in single quotes (`'`).\n * - Do not manually wrap placeholders in single quotes in your template string; the function will handle quoting and escaping for you.\n * - Any single quotes within the string value are escaped by doubling them (`''`), as required by SQL syntax.\n *\n * **Other types:**\n * - `null` and `undefined` are converted to SQL `NULL`.\n * - Objects are stringified using `JSON.stringify()` and wrapped in single quotes, with any single quotes inside the stringified value escaped.\n * - Numbers and other primitive types are inserted directly.\n *\n * **Usage example:**\n * ```typescript\n * const myID = \"O'Reilly\";\n * const clause = sanitizeSQL`New.id = ${myID}`;\n * // Result: \"New.id = 'O''Reilly'\"\n * ```\n *\n * Avoid manually quoting placeholders:\n * ```typescript\n * // Incorrect:\n * sanitizeSQL`New.id = '${myID}'` // Produces double quotes: New.id = ''O''Reilly''\n * ```\n */\nfunction sanitizeSQL(strings, ...values) {\n let result = '';\n strings.forEach((str, i) => {\n result += str;\n if (i < values.length) {\n // For SQL, escape single quotes in string values\n const value = values[i];\n if (typeof value == 'string') {\n result += sanitizeString(value);\n }\n else if (value == null) {\n result += 'NULL';\n }\n else if (typeof value == 'object') {\n // Stringify the object and escape single quotes in the result\n const stringified = JSON.stringify(value);\n result += sanitizeString(stringified);\n }\n else {\n result += value;\n }\n }\n });\n return result;\n}\n\n/**\n * Performs a {@link AbstractPowerSyncDatabase.getAll} operation for a watched query.\n */\nclass GetAllQuery {\n options;\n constructor(options) {\n this.options = options;\n }\n compile() {\n return {\n sql: this.options.sql,\n parameters: this.options.parameters ?? []\n };\n }\n async execute(options) {\n const { db } = options;\n const { sql, parameters = [] } = this.compile();\n const rawResult = await db.getAll(sql, [...parameters]);\n if (this.options.mapper) {\n return rawResult.map(this.options.mapper);\n }\n return rawResult;\n }\n}\n\nconst TypedLogger = Logger;\nconst LogLevel = {\n TRACE: TypedLogger.TRACE,\n DEBUG: TypedLogger.DEBUG,\n INFO: TypedLogger.INFO,\n TIME: TypedLogger.TIME,\n WARN: TypedLogger.WARN,\n ERROR: TypedLogger.ERROR,\n OFF: TypedLogger.OFF\n};\n/**\n * Retrieves the base (default) logger instance.\n *\n * This base logger controls the default logging configuration and is shared\n * across all loggers created with `createLogger`. Adjusting settings on this\n * base logger affects all loggers derived from it unless explicitly overridden.\n *\n */\nfunction createBaseLogger() {\n return Logger;\n}\n/**\n * Creates and configures a new named logger based on the base logger.\n *\n * Named loggers allow specific modules or areas of your application to have\n * their own logging levels and behaviors. These loggers inherit configuration\n * from the base logger by default but can override settings independently.\n */\nfunction createLogger(name, options = {}) {\n const logger = Logger.get(name);\n if (options.logLevel) {\n logger.setLevel(options.logLevel);\n }\n return logger;\n}\n\nconst parseQuery = (query, parameters) => {\n let sqlStatement;\n if (typeof query == 'string') {\n sqlStatement = query;\n }\n else {\n const hasAdditionalParameters = parameters.length > 0;\n if (hasAdditionalParameters) {\n throw new Error('You cannot pass parameters to a compiled query.');\n }\n const compiled = query.compile();\n sqlStatement = compiled.sql;\n parameters = compiled.parameters;\n }\n return { sqlStatement, parameters: parameters };\n};\n\nexport { ATTACHMENT_TABLE, AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, AttachmentContext, AttachmentQueue, AttachmentService, AttachmentState, AttachmentTable, BaseObserver, Column, ColumnType, ConnectionClosedError, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_PRESSURE_LIMITS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DataStream, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, EncodingType, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, MEMORY_TRIGGER_CLAIM_MANAGER, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, SyncingService, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, attachmentFromSql, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, mutexRunExclusive, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID };\n//# sourceMappingURL=bundle.mjs.map\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Check if module exists (development only)\n\tif (__webpack_modules__[moduleId] === undefined) {\n\t\tvar e = new Error(\"Cannot find module '\" + moduleId + \"'\");\n\t\te.code = 'MODULE_NOT_FOUND';\n\t\tthrow e;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"worker/\" + chunkId + \".umd.js\";\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT')\n\t\tscriptUrl = document.currentScript.src;\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) {\n\t\t\tvar i = scripts.length - 1;\n\t\t\twhile (i > -1 && (!scriptUrl || !/^http(s?):/.test(scriptUrl))) scriptUrl = scripts[i--].src;\n\t\t}\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/^blob:/, \"\").replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl + \"../\";","__webpack_require__.b = self.location + \"/../../\";\n\n// object to store loaded chunks\n// \"1\" means \"already loaded\"\nvar installedChunks = {\n\t\"WASQLiteDB\": 1\n};\n\n// importScripts chunk loading\nvar installChunk = (data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\tfor(var moduleId in moreModules) {\n\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t}\n\t}\n\tif(runtime) runtime(__webpack_require__);\n\twhile(chunkIds.length)\n\t\tinstalledChunks[chunkIds.pop()] = 1;\n\tparentChunkLoadingFunction(data);\n};\n__webpack_require__.f.i = (chunkId, promises) => {\n\t// \"1\" is the signal for \"already loaded\"\n\tif(!installedChunks[chunkId]) {\n\t\tif(true) { // all chunks have JS\n\t\t\timportScripts(__webpack_require__.p + __webpack_require__.u(chunkId));\n\t\t}\n\t}\n};\n\nvar chunkLoadingGlobal = self[\"webpackChunksdk_web\"] = self[\"webpackChunksdk_web\"] || [];\nvar parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);\nchunkLoadingGlobal.push = installChunk;\n\n// no HMR\n\n// no HMR manifest","/**\n * Supports both shared and dedicated workers, based on how the worker is constructed (new SharedWorker vs new Worker()).\n */\nimport '@journeyapps/wa-sqlite';\nimport { createBaseLogger, createLogger } from '@powersync/common';\nimport * as Comlink from 'comlink';\nimport { getNavigatorLocks } from '../../shared/navigator.js';\nimport { SharedWASQLiteConnection } from './SharedWASQLiteConnection.js';\nimport { WorkerWASQLiteConnection } from './WorkerWASQLiteConnection.js';\nconst baseLogger = createBaseLogger();\nbaseLogger.useDefaults();\nconst logger = createLogger('db-worker');\nconst DBMap = new Map();\nconst OPEN_DB_LOCK = 'open-wasqlite-db';\nlet nextClientId = 1;\nconst openDBShared = async (options) => {\n // Prevent multiple simultaneous opens from causing race conditions\n return getNavigatorLocks().request(OPEN_DB_LOCK, async () => {\n const clientId = nextClientId++;\n const { dbFilename, logLevel } = options;\n logger.setLevel(logLevel);\n if (!DBMap.has(dbFilename)) {\n const clientIds = new Set();\n // This format returns proxy objects for function callbacks\n const connection = new WorkerWASQLiteConnection(options);\n await connection.init();\n connection.registerListener({\n holdOverwritten: async () => {\n /**\n * The previous hold has been overwritten, without being released.\n * we need to cleanup any resources associated with it.\n * We can perform a rollback to release any potential transactions that were started.\n */\n await connection.execute('ROLLBACK').catch(() => { });\n }\n });\n DBMap.set(dbFilename, {\n clientIds,\n db: connection\n });\n }\n // Associates this clientId with the shared connection entry\n const sharedConnection = new SharedWASQLiteConnection({\n dbMap: DBMap,\n dbFilename,\n clientId,\n logger\n });\n return Comlink.proxy(sharedConnection);\n });\n};\n// Check if we're in a SharedWorker context\nif (typeof SharedWorkerGlobalScope !== 'undefined') {\n const _self = self;\n _self.onconnect = function (event) {\n const port = event.ports[0];\n Comlink.expose(openDBShared, port);\n };\n}\nelse {\n // A dedicated worker can be shared externally\n Comlink.expose(openDBShared);\n}\naddEventListener('unload', () => {\n Array.from(DBMap.values()).forEach(async (dbConnection) => {\n const { db } = dbConnection;\n db.close?.();\n });\n});\n"],"names":[],"sourceRoot":""}
|