@dittolive/ditto 4.7.2 → 4.7.3
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/README.md +2 -2
- package/node/ditto.cjs.js +1 -1
- package/node/ditto.darwin-arm64.node +0 -0
- package/node/ditto.darwin-x64.node +0 -0
- package/node/ditto.linux-arm.node +0 -0
- package/node/ditto.linux-arm64.node +0 -0
- package/node/ditto.linux-x64.node +0 -0
- package/node/ditto.win32-x64.node +0 -0
- package/node/transports.darwin-arm64.node +0 -0
- package/node/transports.darwin-x64.node +0 -0
- package/package.json +1 -1
- package/react-native/android/build.gradle +1 -1
- package/web/ditto.es6.js +1 -1
- package/web/ditto.umd.js +1 -1
- package/web/ditto.wasm +0 -0
package/web/ditto.es6.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
class KeepAlive{get isActive(){return null!==this.intervalID}constructor(){this.countsByID={},this.intervalID=null}retain(e){if(void 0===this.countsByID[e]&&(this.countsByID[e]=0),this.countsByID[e]+=1,null===this.intervalID){const e=2147483647;this.intervalID=setInterval((()=>{}),e),KeepAlive.finalizationRegistry.register(this,this.intervalID,this)}}release(e){if(void 0===this.countsByID[e])throw new Error(`Internal inconsistency, trying to release a keep-alive ID that hasn't been retained before or isn't tracked anymore: ${e}`);this.countsByID[e]-=1,0===this.countsByID[e]&&delete this.countsByID[e],0===Object.keys(this.countsByID).length&&(KeepAlive.finalizationRegistry.unregister(this),clearInterval(this.intervalID),this.intervalID=null)}currentIDs(){return Object.keys(this.countsByID)}countForID(e){var t;return null!==(t=this.countsByID[e])&&void 0!==t?t:null}}KeepAlive.finalizationRegistry=new FinalizationRegistry(clearInterval);class Observer{get token(){return this._token}constructor(e,t,n={}){this.observerManager=e,this._token=t,this.options=n,n.stopsWhenFinalized&&Observer.finalizationRegistry.register(this,{observerManager:e,token:t},this)}get isStopped(){return void 0!==this.token&&this.observerManager.hasObserver(this.token)}stop(){const e=this.token;e&&(delete this._token,Observer.finalizationRegistry.unregister(this),this.observerManager.removeObserver(e))}static finalize(e){const{observerManager:t,token:n}=e;t.removeObserver(n)}}Observer.finalizationRegistry=new FinalizationRegistry(Observer.finalize);const privateToken$1=Symbol("privateConstructorToken");class Counter{get value(){return this._value}constructor(){this._value=0}static"@ditto.create"(e,t,n){const r=e?new MutableCounter(privateToken$1):new Counter;return r.mutDoc=e,r.path=t,r._value=n,r}}class MutableCounter extends Counter{increment(e){const t=this.mutDoc,n=this.path;if(!t)throw new Error("Can't increment counter, only possible within the closure of a collection's update() method.");t.at(n)["@ditto.increment"](e),this._value+=e}constructor(){if(arguments[0]!==privateToken$1)throw new Error("MutableCounter constructor is for internal use only.");super()}}const privateToken="@ditto.ff82dae89821c5ab822a8b539056bce4";class Register{get value(){return this["@ditto.value"]}constructor(e){this["@ditto.value"]=e}static"@ditto.create"(e,t,n){const r=e?new MutableRegister(n,privateToken):new Register(n);return r["@ditto.mutableDocument"]=e,r["@ditto.path"]=t,r["@ditto.value"]=n,r}}class MutableRegister extends Register{get value(){return super.value}set value(e){this.set(e)}set(e){const t=this["@ditto.mutableDocument"],n=this["@ditto.path"];t.at(n)["@ditto.set"](e),this["@ditto.value"]=e}constructor(e){if(arguments[1]!==privateToken)throw new Error("MutableRegister constructor is for internal use only.");super(e)}}function to_string(e){return e.toString()}function is_number(e){return"number"==typeof e}function try_downsize(e){switch(typeof e){case"bigint":if(-Number.MAX_SAFE_INTEGER<=e&&e<=Number.MAX_SAFE_INTEGER)return Number(e);case"number":return e;default:throw new Error(`number or bigint expected, got \`${e}\``)}}function from_string(e){return BigInt(e)}function get_element(e,t){return e[t]}function typeof_(e){return typeof e}function mk_send_ret(){return function send_ret(e){return e}}let wasm;const cachedTextDecoder="undefined"!=typeof TextDecoder?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};"undefined"!=typeof TextDecoder&&cachedTextDecoder.decode();let cachedUint8Memory0=null;function getUint8Memory0(){return null!==cachedUint8Memory0&&0!==cachedUint8Memory0.byteLength||(cachedUint8Memory0=new Uint8Array(wasm.memory.buffer)),cachedUint8Memory0}function getStringFromWasm0(e,t){return e>>>=0,cachedTextDecoder.decode(getUint8Memory0().subarray(e,e+t))}const heap=new Array(128).fill(void 0);heap.push(void 0,null,!0,!1);let heap_next=heap.length;function addHeapObject(e){heap_next===heap.length&&heap.push(heap.length+1);const t=heap_next;return heap_next=heap[t],heap[t]=e,t}function getObject(e){return heap[e]}function dropObject(e){e<132||(heap[e]=heap_next,heap_next=e)}function takeObject(e){const t=getObject(e);return dropObject(e),t}let WASM_VECTOR_LEN=0;const cachedTextEncoder="undefined"!=typeof TextEncoder?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},encodeString="function"==typeof cachedTextEncoder.encodeInto?function(e,t){return cachedTextEncoder.encodeInto(e,t)}:function(e,t){const n=cachedTextEncoder.encode(e);return t.set(n),{read:e.length,written:n.length}};function passStringToWasm0(e,t,n){if(void 0===n){const n=cachedTextEncoder.encode(e),r=t(n.length,1)>>>0;return getUint8Memory0().subarray(r,r+n.length).set(n),WASM_VECTOR_LEN=n.length,r}let r=e.length,i=t(r,1)>>>0;const o=getUint8Memory0();let a=0;for(;a<r;a++){const t=e.charCodeAt(a);if(t>127)break;o[i+a]=t}if(a!==r){0!==a&&(e=e.slice(a)),i=n(i,r,r=a+3*e.length,1)>>>0;const t=getUint8Memory0().subarray(i+a,i+r);a+=encodeString(e,t).written}return WASM_VECTOR_LEN=a,i}function isLikeNone(e){return null==e}let cachedInt32Memory0=null;function getInt32Memory0(){return null!==cachedInt32Memory0&&0!==cachedInt32Memory0.byteLength||(cachedInt32Memory0=new Int32Array(wasm.memory.buffer)),cachedInt32Memory0}function debugString(e){const t=typeof e;if("number"==t||"boolean"==t||null==e)return`${e}`;if("string"==t)return`"${e}"`;if("symbol"==t){const t=e.description;return null==t?"Symbol":`Symbol(${t})`}if("function"==t){const t=e.name;return"string"==typeof t&&t.length>0?`Function(${t})`:"Function"}if(Array.isArray(e)){const t=e.length;let n="[";t>0&&(n+=debugString(e[0]));for(let r=1;r<t;r++)n+=", "+debugString(e[r]);return n+="]",n}const n=/\[object ([^\]]+)\]/.exec(toString.call(e));let r;if(!(n.length>1))return toString.call(e);if(r=n[1],"Object"==r)try{return"Object("+JSON.stringify(e)+")"}catch(e){return"Object"}return e instanceof Error?`${e.name}: ${e.message}\n${e.stack}`:r}const CLOSURE_DTORS=new FinalizationRegistry((e=>{wasm.__wbindgen_export_2.get(e.dtor)(e.a,e.b)}));function makeMutClosure(e,t,n,r){const i={a:e,b:t,cnt:1,dtor:n},real=(...e)=>{i.cnt++;const t=i.a;i.a=0;try{return r(t,i.b,...e)}finally{0==--i.cnt?(wasm.__wbindgen_export_2.get(i.dtor)(t,i.b),CLOSURE_DTORS.unregister(i)):i.a=t}};return real.original=i,CLOSURE_DTORS.register(real,i,i),real}function __wbg_adapter_32(e,t,n){wasm.wasm_bindgen__convert__closures__invoke1_mut__h5fa4a845720bf5a6(e,t,addHeapObject(n))}function __wbg_adapter_35(e,t){wasm.wasm_bindgen__convert__closures__invoke0_mut__hbd4f2b534f6fcbb0(e,t)}function __wbg_adapter_38(e,t,n){wasm.wasm_bindgen__convert__closures__invoke1_mut__h26969dfdcbb658aa(e,t,addHeapObject(n))}function __wbg_adapter_41(e,t){wasm.wasm_bindgen__convert__closures__invoke0_mut__h7bd4c67ecefe53ea(e,t)}function __wbg_adapter_44(e,t,n){wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hcdb08c50a53c7d7a(e,t,addHeapObject(n))}function dittoffi_query_result_mutated_document_id_at(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_mutated_document_id_at(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_mutated_document_id_count(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_mutated_document_id_count(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_item_at(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_item_at(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_item_count(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_item_count(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_item_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_item_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_item_json(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_item_json(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_item_cbor(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_item_cbor(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_exec_statement(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_exec_statement(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_get(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_get(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_remove(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_remove(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_evict(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_evict(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_update_multiple(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_update_multiple(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_update(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_update(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_insert_value(e,t,n,r,i,o){try{const c=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_insert_value(c,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o));var a=getInt32Memory0()[c/4+0],s=getInt32Memory0()[c/4+1];if(getInt32Memory0()[c/4+2])throw takeObject(s);return takeObject(a)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_get_collection_names(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_collection_names(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_documents_hash(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_documents_hash(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_documents_hash_mnemonic(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_documents_hash_mnemonic(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_evict_query_str(e,t,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_evict_query_str(l,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_remove_query_str(e,t,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_remove_query_str(l,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_exec_query_str(e,t,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_exec_query_str(l,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function jsDocsToCDocs(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.jsDocsToCDocs(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function websocket_client_free_handle(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.websocket_client_free_handle(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_write_transaction_rollback(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction_rollback(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_write_transaction_commit(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction_commit(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_write_transaction(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_read_transaction_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_read_transaction_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_read_transaction(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_read_transaction(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_validate_document_id(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_validate_document_id(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_id_query_compatible(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_id_query_compatible(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_remove_sync_subscription(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_remove_sync_subscription(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_add_sync_subscription(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_add_sync_subscription(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_add_subscription(e,t,n,r,i,o,a){try{const d=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_add_subscription(d,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a));var s=getInt32Memory0()[d/4+0],c=getInt32Memory0()[d/4+1];if(getInt32Memory0()[d/4+2])throw takeObject(c);return takeObject(s)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_remove_subscription(e,t,n,r,i,o,a){try{const d=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_remove_subscription(d,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a));var s=getInt32Memory0()[d/4+0],c=getInt32Memory0()[d/4+1];if(getInt32Memory0()[d/4+2])throw takeObject(c);return takeObject(s)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_base64_decode(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_base64_decode(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_base64_encode(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_base64_encode(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_signal_available_next(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_signal_available_next(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_stop(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_stop(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_register_store_observer_webhook(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_register_store_observer_webhook(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_start(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_start(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_register_str_detached(e,t,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_register_str_detached(l,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_experimental_register_change_observer_str_detached(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_experimental_register_change_observer_str_detached(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_webhook_register_str(e,t,n,r,i,o,a){try{const d=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_webhook_register_str(d,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a));var s=getInt32Memory0()[d/4+0],c=getInt32Memory0()[d/4+1];if(getInt32Memory0()[d/4+2])throw takeObject(c);return takeObject(s)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_get_sync_scope(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_get_sync_scope(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_sync_scope(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_sync_scope(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_get_is_enabled(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_get_is_enabled(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_enabled(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_enabled(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_get_metadata(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_get_metadata(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_metadata(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_metadata(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_transport_config_data(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_transport_config_data(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_logout(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_logout(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_connection_request_authorize(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_connection_request_authorize(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_connection_request_connection_type(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_connection_request_connection_type(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_connection_request_peer_key_string(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_connection_request_peer_key_string(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_connection_request_identity_service_metadata_json(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_connection_request_identity_service_metadata_json(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_connection_request_peer_metadata_json(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_connection_request_peer_metadata_json(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_connection_request_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_connection_request_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_presence_peer_metadata_json(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_presence_peer_metadata_json(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_presence_try_set_peer_metadata_json(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_presence_try_set_peer_metadata_json(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_login_with_credentials(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_login_with_credentials(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_login_with_token(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_login_with_token(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_is_x509_valid(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_is_x509_valid(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_is_web_valid(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_is_web_valid(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_user_id(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_user_id(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_get_app_id(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_get_app_id(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_get_site_id(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_get_site_id(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_set_login_provider(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_set_login_provider(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_manual_v0(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_manual_v0(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_shared_key(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_shared_key(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_offline_playground(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_offline_playground(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_online_playground(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_online_playground(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_online_with_authentication(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_online_with_authentication(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_presence_set_connection_request_handler(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_presence_set_connection_request_handler(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_make_login_provider(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_login_provider(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_set_validity_listener(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_set_validity_listener(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_error_message(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_error_message(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_init_sdk_version(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_init_sdk_version(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_get_sdk_semver(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_get_sdk_semver(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_get_sdk_version(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_sdk_version(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_disable_sync_with_v3(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_disable_sync_with_v3(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_run_garbage_collection(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_run_garbage_collection(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_sync_group(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_sync_group(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_connect_retry_interval(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_connect_retry_interval(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_device_name(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_device_name(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_presence_v3(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_presence_v3(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_presence_v1(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_presence_v1(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_clear_presence_v3_callback(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_clear_presence_v3_callback(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_clear_presence_callback(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_clear_presence_callback(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_shutdown(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_shutdown(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_make(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_make(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_static_websocket_clients(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_static_websocket_clients(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_transport_condition_changed_callback(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_transport_condition_changed_callback(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_verify_license(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_verify_license(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_presence_v1_callback(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_presence_v1_callback(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_presence_v3_callback(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_presence_v3_callback(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_cancel_resolve_attachment(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_cancel_resolve_attachment(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_free_attachment_handle(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_free_attachment_handle(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_get_complete_attachment_data(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_complete_attachment_data(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_new_attachment_from_bytes(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_new_attachment_from_bytes(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_resolve_attachment(e,t,n,r,i){try{const s=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_resolve_attachment(s,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_get_cbor_with_path_type(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_get_cbor_with_path_type(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_remove(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_remove(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_set_cbor_with_timestamp(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_set_cbor_with_timestamp(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_set_cbor(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_set_cbor(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_increment_counter(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_increment_counter(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_id(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_id(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_log(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_log(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_minimum_log_level_get(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_minimum_log_level_get(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_minimum_log_level(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_minimum_log_level(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_emoji_headings_enabled_get(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_emoji_headings_enabled_get(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_emoji_headings_enabled(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_emoji_headings_enabled(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_enabled_get(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_enabled_get(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_enabled(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_enabled(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_init(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_init(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_set_log_file(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_set_log_file(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_set_custom_log_cb(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_set_custom_log_cb(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_error_description(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_error_description(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_error_code(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_error_code(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_error_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_error_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function handleError(e,t){try{return e.apply(this,t)}catch(e){wasm.__wbindgen_exn_store(addHeapObject(e))}}function notDefined(e){return()=>{throw new Error(`${e} is not defined`)}}function getArrayU8FromWasm0(e,t){return e>>>=0,getUint8Memory0().subarray(e/1,e/1+t)}function __wbg_adapter_393(e,t,n,r){wasm.wasm_bindgen__convert__closures__invoke2_mut__h4a79cbbfae79c36f(e,t,addHeapObject(n),addHeapObject(r))}function boxCStringIntoString(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.boxCStringIntoString(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function refCStringToString(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.refCStringToString(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function boxCBytesIntoBuffer(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.boxCBytesIntoBuffer(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function refCBytesIntoBuffer(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.refCBytesIntoBuffer(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function withOutBoxCBytes(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.withOutBoxCBytes(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function cStringVecToStringArray(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.cStringVecToStringArray(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}async function __wbg_load(e,t){if("function"==typeof Response&&e instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if("application/wasm"==e.headers.get("Content-Type"))throw t;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",t)}const n=await e.arrayBuffer();return await WebAssembly.instantiate(n,t)}{const n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}}function __wbg_get_imports(){const e={wbg:{}};return e.wbg.__wbindgen_string_new=function(e,t){return addHeapObject(getStringFromWasm0(e,t))},e.wbg.__wbindgen_object_drop_ref=function(e){takeObject(e)},e.wbg.__wbindgen_cb_drop=function(e){const t=takeObject(e).original;if(1==t.cnt--)return t.a=0,!0;return!1},e.wbg.__wbg_log_f7c904296a5a8ff0=function(e,t){let n,r;try{n=e,r=t,console.log(getStringFromWasm0(e,t))}finally{wasm.__wbindgen_free(n,r,1)}},e.wbg.__wbg_new_abda76e883ba8a5f=function(){return addHeapObject(new Error)},e.wbg.__wbg_stack_658279fe44541cf6=function(e,t){const n=passStringToWasm0(getObject(t).stack,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbg_error_f851667af71bcfc6=function(e,t){let n,r;try{n=e,r=t,console.error(getStringFromWasm0(e,t))}finally{wasm.__wbindgen_free(n,r,1)}},e.wbg.__wbindgen_is_string=function(e){return"string"==typeof getObject(e)},e.wbg.__wbindgen_string_get=function(e,t){const n=getObject(t),r="string"==typeof n?n:void 0;var i=isLikeNone(r)?0:passStringToWasm0(r,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),o=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=o,getInt32Memory0()[e/4+0]=i},e.wbg.__wbg_fetch_6a2624d7f767e331=function(e){return addHeapObject(fetch(getObject(e)))},e.wbg.__wbindgen_object_clone_ref=function(e){return addHeapObject(getObject(e))},e.wbg.__wbg_clearTimeout_23ee6db72c0ad922="function"==typeof clearTimeout?clearTimeout:notDefined("clearTimeout"),e.wbg.__wbg_setTimeout_09074a1669d0f224=function(){return handleError((function(e,t){return setTimeout(getObject(e),t)}),arguments)},e.wbg.__wbg_clearInterval_d5655e407a861314="function"==typeof clearInterval?clearInterval:notDefined("clearInterval"),e.wbg.__wbg_setInterval_fa82463ae3f43f48=function(){return handleError((function(e,t){return setInterval(getObject(e),t)}),arguments)},e.wbg.__wbindgen_number_new=function(e){return addHeapObject(e)},e.wbg.__wbg_crypto_58f13aa23ffcb166=function(e){return addHeapObject(getObject(e).crypto)},e.wbg.__wbindgen_is_object=function(e){const t=getObject(e);return"object"==typeof t&&null!==t},e.wbg.__wbg_process_5b786e71d465a513=function(e){return addHeapObject(getObject(e).process)},e.wbg.__wbg_versions_c2ab80650590b6a2=function(e){return addHeapObject(getObject(e).versions)},e.wbg.__wbg_node_523d7bd03ef69fba=function(e){return addHeapObject(getObject(e).node)},e.wbg.__wbg_msCrypto_abcb1295e768d1f2=function(e){return addHeapObject(getObject(e).msCrypto)},e.wbg.__wbg_require_2784e593a4674877=function(){return handleError((function(){return addHeapObject(module.require)}),arguments)},e.wbg.__wbindgen_is_function=function(e){return"function"==typeof getObject(e)},e.wbg.__wbg_randomFillSync_a0d98aa11c81fe89=function(){return handleError((function(e,t){getObject(e).randomFillSync(takeObject(t))}),arguments)},e.wbg.__wbg_getRandomValues_504510b5564925af=function(){return handleError((function(e,t){getObject(e).getRandomValues(getObject(t))}),arguments)},e.wbg.__wbg_mksendret_2fbc0bd0b52dee17=function(){return addHeapObject(mk_send_ret())},e.wbg.__wbg_trydownsize_28e49b8073c2a2fc=function(e){return addHeapObject(try_downsize(takeObject(e)))},e.wbg.__wbg_isnumber_c97122a46d4ace09=function(e){return is_number(getObject(e))},e.wbg.__wbg_tostring_7847f1b7af649ba5=function(e,t){const n=passStringToWasm0(to_string(getObject(t)),wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbindgen_error_new=function(e,t){return addHeapObject(new Error(getStringFromWasm0(e,t)))},e.wbg.__wbg_fromstring_721719aff319c1fe=function(e,t){return addHeapObject(from_string(getStringFromWasm0(e,t)))},e.wbg.__wbg_typeof_cb5c1bc26a697ea8=function(e,t){const n=passStringToWasm0(typeof_(getObject(t)),wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbindgen_is_null=function(e){return null===getObject(e)},e.wbg.__wbindgen_is_undefined=function(e){return void 0===getObject(e)},e.wbg.__wbg_getelement_cd48f1e89008c242=function(e,t){return addHeapObject(get_element(getObject(e),t>>>0))},e.wbg.__wbg_fetch_749a56934f95c96c=function(e,t){return addHeapObject(getObject(e).fetch(getObject(t)))},e.wbg.__wbg_now_8172cd917e5eda6b=function(e){return getObject(e).now()},e.wbg.__wbg_new_39f0e6d61fc67f0e=function(){return handleError((function(){return addHeapObject(new FormData)}),arguments)},e.wbg.__wbg_append_1b70fd81d162ab50=function(){return handleError((function(e,t,n,r){getObject(e).append(getStringFromWasm0(t,n),getObject(r))}),arguments)},e.wbg.__wbg_append_32853c33a2dd22f0=function(){return handleError((function(e,t,n,r,i,o){getObject(e).append(getStringFromWasm0(t,n),getObject(r),getStringFromWasm0(i,o))}),arguments)},e.wbg.__wbg_new_2d0053ee81e4dd2a=function(){return handleError((function(){return addHeapObject(new Headers)}),arguments)},e.wbg.__wbg_append_de37df908812970d=function(){return handleError((function(e,t,n,r,i){getObject(e).append(getStringFromWasm0(t,n),getStringFromWasm0(r,i))}),arguments)},e.wbg.__wbg_url_1f1b597f64482fd0=function(e,t){const n=passStringToWasm0(getObject(t).url,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbg_readyState_9c0f66433e329c9e=function(e){return getObject(e).readyState},e.wbg.__wbg_setonopen_9ce48dce57e549b5=function(e,t){getObject(e).onopen=getObject(t)},e.wbg.__wbg_setonerror_02393260b3e29972=function(e,t){getObject(e).onerror=getObject(t)},e.wbg.__wbg_setonclose_4ce49fd8fd7783fb=function(e,t){getObject(e).onclose=getObject(t)},e.wbg.__wbg_setonmessage_c5a806b62a0c5607=function(e,t){getObject(e).onmessage=getObject(t)},e.wbg.__wbg_setbinaryType_ee55743ddf4beb37=function(e,t){getObject(e).binaryType=takeObject(t)},e.wbg.__wbg_new_d29e507f6606de91=function(){return handleError((function(e,t){return addHeapObject(new WebSocket(getStringFromWasm0(e,t)))}),arguments)},e.wbg.__wbg_newwithstrsequence_7b0c4aadc1ae1635=function(){return handleError((function(e,t,n){return addHeapObject(new WebSocket(getStringFromWasm0(e,t),getObject(n)))}),arguments)},e.wbg.__wbg_close_45d053bea59e7746=function(){return handleError((function(e){getObject(e).close()}),arguments)},e.wbg.__wbg_send_80b256d87a6779e5=function(){return handleError((function(e,t,n){getObject(e).send(getStringFromWasm0(t,n))}),arguments)},e.wbg.__wbg_send_640853f8eb0f0385=function(){return handleError((function(e,t,n){getObject(e).send(getArrayU8FromWasm0(t,n))}),arguments)},e.wbg.__wbg_instanceof_Blob_d18d26355bccfd22=function(e){let t;try{t=getObject(e)instanceof Blob}catch{t=!1}return t},e.wbg.__wbg_newwithu8arraysequenceandoptions_b0ee96dd3232b69c=function(){return handleError((function(e,t){return addHeapObject(new Blob(getObject(e),getObject(t)))}),arguments)},e.wbg.__wbg_signal_31753ac644b25fbb=function(e){return addHeapObject(getObject(e).signal)},e.wbg.__wbg_new_6396e586b56e1dff=function(){return handleError((function(){return addHeapObject(new AbortController)}),arguments)},e.wbg.__wbg_abort_064ae59cda5cd244=function(e){getObject(e).abort()},e.wbg.__wbg_instanceof_Response_eaa426220848a39e=function(e){let t;try{t=getObject(e)instanceof Response}catch{t=!1}return t},e.wbg.__wbg_url_74285ddf2747cb3d=function(e,t){const n=passStringToWasm0(getObject(t).url,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbg_status_c4ef3dd591e63435=function(e){return getObject(e).status},e.wbg.__wbg_headers_fd64ad685cf22e5d=function(e){return addHeapObject(getObject(e).headers)},e.wbg.__wbg_arrayBuffer_4c27b6f00c530232=function(){return handleError((function(e){return addHeapObject(getObject(e).arrayBuffer())}),arguments)},e.wbg.__wbg_wasClean_2af04e6cf2076497=function(e){return getObject(e).wasClean},e.wbg.__wbg_code_24e161f043adce8a=function(e){return getObject(e).code},e.wbg.__wbg_reason_40159cc3d2fc655d=function(e,t){const n=passStringToWasm0(getObject(t).reason,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbg_code_b09504754e0520f1=function(e){return getObject(e).code},e.wbg.__wbg_data_7b1f01f4e6a64fbe=function(e){return addHeapObject(getObject(e).data)},e.wbg.__wbg_newwithstrandinit_05d7180788420c40=function(){return handleError((function(e,t,n){return addHeapObject(new Request(getStringFromWasm0(e,t),getObject(n)))}),arguments)},e.wbg.__wbg_new_898a68150f225f2e=function(){return addHeapObject(new Array)},e.wbg.__wbg_valueOf_e39b017d2100ede0=function(e){return getObject(e).valueOf()},e.wbg.__wbg_newnoargs_581967eacc0e2604=function(e,t){return addHeapObject(new Function(getStringFromWasm0(e,t)))},e.wbg.__wbg_next_526fc47e980da008=function(e){return addHeapObject(getObject(e).next)},e.wbg.__wbg_next_ddb3312ca1c4e32a=function(){return handleError((function(e){return addHeapObject(getObject(e).next())}),arguments)},e.wbg.__wbg_done_5c1f01fb660d73b5=function(e){return getObject(e).done},e.wbg.__wbg_value_1695675138684bd5=function(e){return addHeapObject(getObject(e).value)},e.wbg.__wbg_iterator_97f0c81209c6c35a=function(){return addHeapObject(Symbol.iterator)},e.wbg.__wbg_get_97b561fb56f034b5=function(){return handleError((function(e,t){return addHeapObject(Reflect.get(getObject(e),getObject(t)))}),arguments)},e.wbg.__wbg_call_cb65541d95d71282=function(){return handleError((function(e,t){return addHeapObject(getObject(e).call(getObject(t)))}),arguments)},e.wbg.__wbg_new_b51585de1b234aff=function(){return addHeapObject(new Object)},e.wbg.__wbg_self_1ff1d729e9aae938=function(){return handleError((function(){return addHeapObject(self.self)}),arguments)},e.wbg.__wbg_window_5f4faef6c12b79ec=function(){return handleError((function(){return addHeapObject(window.window)}),arguments)},e.wbg.__wbg_globalThis_1d39714405582d3c=function(){return handleError((function(){return addHeapObject(globalThis.globalThis)}),arguments)},e.wbg.__wbg_global_651f05c6a0944d1c=function(){return handleError((function(){return addHeapObject(global.global)}),arguments)},e.wbg.__wbg_push_ca1c26067ef907ac=function(e,t){return getObject(e).push(getObject(t))},e.wbg.__wbg_instanceof_ArrayBuffer_39ac22089b74fddb=function(e){let t;try{t=getObject(e)instanceof ArrayBuffer}catch{t=!1}return t},e.wbg.__wbg_apply_64be369596a02ae0=function(){return handleError((function(e,t,n){return addHeapObject(getObject(e).apply(getObject(t),getObject(n)))}),arguments)},e.wbg.__wbg_call_01734de55d61e11d=function(){return handleError((function(e,t,n){return addHeapObject(getObject(e).call(getObject(t),getObject(n)))}),arguments)},e.wbg.__wbg_valueOf_7d8df3cd4f3f583b=function(e){return getObject(e).valueOf()},e.wbg.__wbg_getTime_5e2054f832d82ec9=function(e){return getObject(e).getTime()},e.wbg.__wbg_new0_c0be7df4b6bd481f=function(){return addHeapObject(new Date)},e.wbg.__wbg_now_9c5990bda04c7e53=function(){return Date.now()},e.wbg.__wbg_instanceof_Object_3daa8298c86298be=function(e){let t;try{t=getObject(e)instanceof Object}catch{t=!1}return t},e.wbg.__wbg_new_43f1b47c28813cbd=function(e,t){try{var n={a:e,b:t};const r=new Promise(((e,t)=>{const r=n.a;n.a=0;try{return __wbg_adapter_393(r,n.b,e,t)}finally{n.a=r}}));return addHeapObject(r)}finally{n.a=n.b=0}},e.wbg.__wbg_resolve_53698b95aaf7fcf8=function(e){return addHeapObject(Promise.resolve(getObject(e)))},e.wbg.__wbg_then_f7e06ee3c11698eb=function(e,t){return addHeapObject(getObject(e).then(getObject(t)))},e.wbg.__wbg_then_b2267541e2a73865=function(e,t,n){return addHeapObject(getObject(e).then(getObject(t),getObject(n)))},e.wbg.__wbg_buffer_085ec1f694018c4f=function(e){return addHeapObject(getObject(e).buffer)},e.wbg.__wbg_newwithbyteoffsetandlength_6da8e527659b86aa=function(e,t,n){return addHeapObject(new Uint8Array(getObject(e),t>>>0,n>>>0))},e.wbg.__wbg_new_8125e318e6245eed=function(e){return addHeapObject(new Uint8Array(getObject(e)))},e.wbg.__wbg_set_5cf90238115182c3=function(e,t,n){getObject(e).set(getObject(t),n>>>0)},e.wbg.__wbg_length_72e2208bbc0efc61=function(e){return getObject(e).length},e.wbg.__wbg_instanceof_Uint8Array_d8d9cb2b8e8ac1d4=function(e){let t;try{t=getObject(e)instanceof Uint8Array}catch{t=!1}return t},e.wbg.__wbg_newwithlength_e5d69174d6984cd7=function(e){return addHeapObject(new Uint8Array(e>>>0))},e.wbg.__wbg_subarray_13db269f57aa838d=function(e,t,n){return addHeapObject(getObject(e).subarray(t>>>0,n>>>0))},e.wbg.__wbg_stringify_e25465938f3f611f=function(){return handleError((function(e){return addHeapObject(JSON.stringify(getObject(e)))}),arguments)},e.wbg.__wbg_has_c5fcd020291e56b8=function(){return handleError((function(e,t){return Reflect.has(getObject(e),getObject(t))}),arguments)},e.wbg.__wbg_set_092e06b0f9d71865=function(){return handleError((function(e,t,n){return Reflect.set(getObject(e),getObject(t),getObject(n))}),arguments)},e.wbg.__wbindgen_debug_string=function(e,t){const n=passStringToWasm0(debugString(getObject(t)),wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbindgen_throw=function(e,t){throw new Error(getStringFromWasm0(e,t))},e.wbg.__wbindgen_memory=function(){return addHeapObject(wasm.memory)},e.wbg.__wbindgen_closure_wrapper2311=function(e,t,n){return addHeapObject(makeMutClosure(e,t,899,__wbg_adapter_32))},e.wbg.__wbindgen_closure_wrapper2313=function(e,t,n){return addHeapObject(makeMutClosure(e,t,899,__wbg_adapter_35))},e.wbg.__wbindgen_closure_wrapper18672=function(e,t,n){return addHeapObject(makeMutClosure(e,t,5114,__wbg_adapter_38))},e.wbg.__wbindgen_closure_wrapper24371=function(e,t,n){return addHeapObject(makeMutClosure(e,t,7121,__wbg_adapter_41))},e.wbg.__wbindgen_closure_wrapper26012=function(e,t,n){return addHeapObject(makeMutClosure(e,t,7607,__wbg_adapter_44))},e}function __wbg_finalize_init(e,t){return wasm=e.exports,init$2.__wbindgen_wasm_module=t,cachedInt32Memory0=null,cachedUint8Memory0=null,wasm}async function init$2(e){if(void 0!==wasm)return wasm;if(void 0===e)throw new Error("Can't load ditto.wasm, expected module to be provided at initialization time but got nothing.");const t=__wbg_get_imports();("string"==typeof e||"function"==typeof Request&&e instanceof Request||"function"==typeof URL&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await __wbg_load(await e,t);return __wbg_finalize_init(n,r)}const isWebBuild=!0,PREFIX_REGEX=new RegExp(/^<.*?>\s*/);class DittoFFIError extends Error{constructor(e,t,n){const r=ffiErrorMessage();super(t||r||n),this.code=e}}function throwOnErrorResult(e,t){if(null!==e){let n,r;try{n=dittoffi_error_code(e),r=boxCStringIntoString(dittoffi_error_description(e)),dittoffi_error_free(e)}catch(e){throw new DittoFFIError(-1,`Failed to retrieve Ditto core error message: ${e.message}`)}throw r=null==r?`${t}() failed with error code: ${n}`:r.replace(PREFIX_REGEX,""),new DittoFFIError(n,r)}}function ffiErrorMessage(){return boxCStringIntoString(ditto_error_message())}const DittoCRDTTypeKey="_ditto_internal_type_jkb12973t4b",DittoCRDTValueKey="_value";var DittoCRDTType;function documentSetCBORWithTimestamp(e,t,n,r){ensureInitialized();const i=ditto_document_set_cbor_with_timestamp(e,bytesFromString(t),n,r);if(0!==i)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${i}`)}function documentSetCBOR(e,t,n){ensureInitialized();const r=ditto_document_set_cbor(e,bytesFromString(t),n);if(0!==r)throw new Error(errorMessage()||`ditto_document_set_cbor() failed with error code: ${r}`)}function documentID(e){ensureInitialized();return boxCBytesIntoBuffer(ditto_document_id(e))}function documentGetCBORWithPathType(e,t,n){ensureInitialized();const r=ditto_document_get_cbor_with_path_type(e,bytesFromString(t),n);return{statusCode:r.status_code,cbor:boxCBytesIntoBuffer(r.cbor)}}function documentRemove(e,t){ensureInitialized();const n=ditto_document_remove(e,bytesFromString(t));if(0!==n)throw new Error(errorMessage()||`ditto_document_remove() failed with error code: ${n}`)}function documentIncrementCounter(e,t,n){ensureInitialized();const r=ditto_document_increment_counter(e,bytesFromString(t),n);if(0!==r)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${r}`)}function documentFree(e){ensureInitialized(),ditto_document_free(e)}function documentIDQueryCompatible(e,t){ensureInitialized();return boxCStringIntoString(ditto_document_id_query_compatible(e,t))}function validateDocumentID(e){ensureInitialized();return boxCBytesIntoBuffer(withOutBoxCBytes((t=>{const n=ditto_validate_document_id(e,t);if(0!==n)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${n}`);return t})))}async function collectionGet(e,t,n,r){ensureInitialized();const i=bytesFromString(t),{status_code:o,document:a}=await ditto_collection_get(e,i,n,r);if(o===NOT_FOUND_ERROR_CODE)return null;if(0!==o)throw new Error(errorMessage()||`ditto_collection_get() failed with error code: ${o}`);return a}async function collectionInsertValue(e,t,n,r,i){ensureInitialized();const o=bytesFromString(t);let a;switch(r){case"merge":a="Merge";break;case"insertIfAbsent":a="InsertIfAbsent";break;case"insertDefaultIfAbsent":a="InsertDefaultIfAbsent";break;case"updateDifferentValues":a="UpdateDifferentValues";break;default:throw new Error(`Unsupported write strategy '${r}' provided.`)}const{status_code:s,id:c}=await ditto_collection_insert_value(e,o,n,a,null,null!=i?i:null);if(0!==s)throw new Error(errorMessage()||`ditto_collection_insert_value() failed with error code: ${s}`);return boxCBytesIntoBuffer(c)}async function collectionRemove(e,t,n,r){ensureInitialized();const i=bytesFromString(t),{status_code:o,bool_value:a}=await ditto_collection_remove(e,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${o}`);return a}async function collectionEvict(e,t,n,r){ensureInitialized();const i=bytesFromString(t),{status_code:o,bool_value:a}=await ditto_collection_evict(e,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${o}`);return a}async function collectionUpdate(e,t,n,r){ensureInitialized();const i=bytesFromString(t),o=await ditto_collection_update(e,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${o}`)}async function collectionUpdateMultiple(e,t,n,r){ensureInitialized();const i=bytesFromString(t),o=jsDocsToCDocs(r),a=await ditto_collection_update_multiple(e,i,n,o);if(0!==a)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${a}`)}async function collectionExecQueryStr(e,t,n,r,i,o,a,s){ensureInitialized();const c=bytesFromString(t),d=bytesFromString(r);return await ditto_collection_exec_query_str(e,c,n,d,i,o,a,s)}async function collectionRemoveQueryStr(e,t,n,r,i,o,a,s){ensureInitialized();const c=bytesFromString(t),d=bytesFromString(r);return await ditto_collection_remove_query_str(e,c,n,d,i,o,a,s)}async function collectionEvictQueryStr(e,t,n,r,i,o,a,s){ensureInitialized();const c=bytesFromString(t),d=bytesFromString(r);return await ditto_collection_evict_query_str(e,c,n,d,i,o,a,s)}async function tryExecStatement(e,t,n,r){ensureInitialized();const i=bytesFromString(n),o=await dittoffi_try_exec_statement(e,t,i,r);return throwOnErrorResult(o.error,"dittoffi_try_exec_statement"),o.success}function addSubscription(e,t,n,r,i,o,a){ensureInitialized();const s=ditto_add_subscription(e,bytesFromString(t),bytesFromString(n),r,i,o,a);if(0!==s)throw new Error(errorMessage()||`ditto_add_subscription() failed with error code: ${s}`)}function removeSubscription(e,t,n,r,i,o,a){ensureInitialized();const s=ditto_remove_subscription(e,bytesFromString(t),bytesFromString(n),r,i,o,a);if(0!==s)throw new Error(errorMessage()||`ditto_remove_subscription() failed with error code: ${s}`)}function tryAddSyncSubscription(e,t,n){ensureInitialized();throwOnErrorResult(dittoffi_try_add_sync_subscription(e,bytesFromString(t),n).error,"dittoffi_try_add_sync_subscription")}function tryRemoveSyncSubscription(e,t,n){ensureInitialized();throwOnErrorResult(dittoffi_try_remove_sync_subscription(e,bytesFromString(t),n).error,"dittoffi_try_remove_sync_subscription")}function queryResultFree(e){ensureInitialized(),dittoffi_query_result_free(e)}function queryResultItemFree(e){ensureInitialized(),dittoffi_query_result_item_free(e)}function queryResultItems(e){ensureInitialized();const t=[],n=dittoffi_query_result_item_count(e);for(let r=0;r<n;r++)t.push(dittoffi_query_result_item_at(e,r));return t}function queryResultMutatedDocumentIDs(e){ensureInitialized();const t=[],n=dittoffi_query_result_mutated_document_id_count(e);for(let r=0;r<n;r++){const n=dittoffi_query_result_mutated_document_id_at(e,r);t.push(boxCBytesIntoBuffer(n))}return t}function queryResultItemCBOR(e){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_query_result_item_cbor(e))}function queryResultItemJSON(e){ensureInitialized();return boxCStringIntoString(dittoffi_query_result_item_json(e))}function liveQueryRegister(e,t,n,r,i,o,a,s,c){ensureInitialized();const d=bytesFromString(t),l=bytesFromString(n),{status_code:u,i64:_}=ditto_live_query_register_str_detached(e,d,l,r,i,o,a,wrapBackgroundCbForFFI(c,s));if(0!==u)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${u}`);return _}function tryExperimentalRegisterChangeObserver(e,t,n,r){ensureInitialized();const i=wrapBackgroundCbForFFI((e=>log("Error",`The registered store observer callback failed with ${e}`)),r),o=dittoffi_try_experimental_register_change_observer_str_detached(e,bytesFromString(t),n,i);return throwOnErrorResult(o.error,"dittoffi_try_experimental_register_change_observer_str_detached"),o.success}async function liveQueryStart(e,t){ensureInitialized();const n=await ditto_live_query_start(e,t);if(0!==n)throw new Error(errorMessage()||`\`ditto_live_query_start()\` failed with error code: ${n}`)}function liveQueryStop(e,t){ensureInitialized(),ditto_live_query_stop(e,t)}async function liveQuerySignalAvailableNext(e,t){ensureInitialized(),await ditto_live_query_signal_available_next(e,t)}async function liveQueryWebhookRegister(e,t,n,r,i,o,a){ensureInitialized();const s=bytesFromString(t),c=bytesFromString(n),d=bytesFromString(a),{status_code:l,id:u}=await ditto_live_query_webhook_register_str(e,s,c,r,i,o,d);if(0!==l)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${l}`);return boxCBytesIntoBuffer(u)}async function tryRegisterStoreObserverWebhook(e,t,n,r){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(r),a=await dittoffi_try_register_store_observer_webhook(e,i,n,o);throwOnErrorResult(a.error,"dittoffi_try_register_store_observer_webhook");return boxCBytesIntoBuffer(a.success)}async function readTransaction(e){ensureInitialized();const{status_code:t,txn:n}=await ditto_read_transaction(e);if(0!==t)throw new Error(errorMessage()||`\`ditto_read_transaction()\` failed with error code: ${t}`);return n}function readTransactionFree(e){return ensureInitialized(),ditto_read_transaction_free(e)}async function writeTransaction(e){ensureInitialized();const{status_code:t,txn:n}=await ditto_write_transaction(e,null);if(0!==t)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${t}`);return n}async function writeTransactionCommit(e,t){ensureInitialized();const n=await ditto_write_transaction_commit(e,t);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_commit() failed with error code: ${n}`)}async function writeTransactionRollback(e,t){ensureInitialized();const n=await ditto_write_transaction_rollback(e,t);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_rollback() failed with error code: ${n}`)}function staticTCPClientFreeHandle(e){(void 0)(e)}function websocketClientFreeHandle(e){ensureInitialized(),websocket_client_free_handle(e)}function loggerInit(){ensureInitialized(),ditto_logger_init()}async function loggerSetCustomLogCb(e){if(ensureInitialized(),null===e)await ditto_logger_set_custom_log_cb(null);else{const t=wrapBackgroundCbForFFI(null,((t,n)=>{try{const r=boxCStringIntoString(n);e(t,r)}catch(e){log("Error",`The registered cb in \`ditto_logger_set_custom_log_cb()\` failed with: ${e}`)}}));await ditto_logger_set_custom_log_cb(t)}}function loggerEnabled(e){ensureInitialized(),ditto_logger_enabled(!!e)}function loggerEnabledGet(){return ensureInitialized(),!!ditto_logger_enabled_get()}function loggerEmojiHeadingsEnabled(e){ensureInitialized(),ditto_logger_emoji_headings_enabled(e)}function loggerEmojiHeadingsEnabledGet(){return ensureInitialized(),ditto_logger_emoji_headings_enabled_get()}function loggerMinimumLogLevel(e){ensureInitialized(),ditto_logger_minimum_log_level(e)}function loggerMinimumLogLevelGet(){return ensureInitialized(),ditto_logger_minimum_log_level_get()}function loggerSetLogFile(e){ensureInitialized();if(0!==ditto_logger_set_log_file(e?bytesFromString(e):null))throw errorMessage(),new Error(`Can't set log file, due to error: ${errorMessage}`)}function log(e,t){ensureInitialized();ditto_log(e,bytesFromString(t))}function dittoIdentityConfigMakeOnlinePlayground(e,t,n){ensureInitialized();const r=bytesFromString(e),i=bytesFromString(t),o=bytesFromString(n),{status_code:a,identity_config:s}=ditto_identity_config_make_online_playground(r,i,o);if(0!==a)throw new Error(errorMessage()||`ditto_identity_config_make_online_playground() failed with error code: ${a}`);return s}function dittoIdentityConfigMakeOnlineWithAuthentication(e,t){ensureInitialized();const n=bytesFromString(e),r=bytesFromString(t),{status_code:i,identity_config:o}=ditto_identity_config_make_online_with_authentication(n,r);if(0!==i)throw new Error(errorMessage()||`ditto_identity_config_make_online_with_authentication() failed with error code: ${i}`);return o}function dittoIdentityConfigMakeOfflinePlayground(e,t){ensureInitialized();const n=bytesFromString(e),r=Number(t),{status_code:i,identity_config:o}=ditto_identity_config_make_offline_playground(n,r);if(0!==i)throw new Error(errorMessage()||`ditto_identity_config_make_offline_playground() failed with error code: ${i}`);return o}function dittoIdentityConfigMakeSharedKey(e,t,n){ensureInitialized();const r=bytesFromString(e),i=bytesFromString(t),o=Number(n),{status_code:a,identity_config:s}=ditto_identity_config_make_shared_key(r,i,o);if(0!==a)throw new Error(errorMessage()||`ditto_identity_config_make_shared_key() failed with error code: ${a}`);return s}function dittoIdentityConfigMakeManual(e){ensureInitialized();const t=bytesFromString(e),{status_code:n,identity_config:r}=ditto_identity_config_make_manual_v0(t);if(0!==n)throw new Error(errorMessage()||`ditto_identity_config_make_manual_v0() failed with error code: ${n}`);return r}function dittoAuthClientGetSiteID(e){return ensureInitialized(),ditto_auth_client_get_site_id(e)}function dittoAuthClientGetAppID(e){ensureInitialized();return boxCStringIntoString(ditto_auth_client_get_app_id(e))}function dittoAuthClientUserID(e){ensureInitialized();return boxCStringIntoString(ditto_auth_client_user_id(e))}function dittoAuthClientIsWebValid(e){return ensureInitialized(),0!==ditto_auth_client_is_web_valid(e)}function dittoAuthClientIsX509Valid(e){return ensureInitialized(),0!==ditto_auth_client_is_x509_valid(e)}async function dittoAuthClientLoginWithToken(e,t,n){ensureInitialized();const r=bytesFromString(t),i=bytesFromString(n),o=await ditto_auth_client_login_with_token(e,r,i);if(0!==o)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${o}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(e,t,n,r){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(n),a=bytesFromString(r),s=await ditto_auth_client_login_with_credentials(e,i,o,a);if(0!==s)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${s}).`)}async function dittoAuthClientLogout(e){ensureInitialized();const t=await ditto_auth_client_logout(e);if(0!==t)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${t}).`)}function dittoMake(e,t,n){ensureInitialized();return ditto_make(bytesFromString(e),t,n)}async function dittoGetCollectionNames(e){ensureInitialized();const t=await ditto_get_collection_names(e),n=t.status_code,r=t.names;if(0!==n)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${n}`);return cStringVecToStringArray(r)}function dittoFree(e){return ensureInitialized(),ditto_free(e)}function dittoRegisterPresenceV1Callback(e,t){ensureInitialized(),ditto_register_presence_v1_callback(e,wrapBackgroundCbForFFI((e=>log("Error",`The registered presence callback v1 errored with ${e}`)),(e=>{const n=refCStringToString(e);t(n)})))}async function dittoClearPresenceCallback(e){return ensureInitialized(),ditto_clear_presence_callback(e)}function dittoRegisterPresenceV3Callback(e,t){ensureInitialized(),ditto_register_presence_v3_callback(e,wrapBackgroundCbForFFI((e=>log("Error",`The registered presence callback v3 errored with ${e}`)),(e=>{const n=refCStringToString(e);t(n)})))}async function dittoClearPresenceV3Callback(e){return ensureInitialized(),ditto_clear_presence_v3_callback(e)}function presencePeerMetadataJSON(e){ensureInitialized();const t=boxCBytesIntoBuffer(dittoffi_presence_peer_metadata_json(e));return(new TextDecoder).decode(t)}async function presenceTrySetPeerMetadataJSON(e,t){ensureInitialized();const n=bytesFromString(t);throwOnErrorResult((await dittoffi_presence_try_set_peer_metadata_json(e,n)).error,"dittoffi_presence_try_set_peer_metadata_json")}function connectionRequestPeerKeyString(e){ensureInitialized();return boxCStringIntoString(dittoffi_connection_request_peer_key_string(e))}function connectionRequestPeerMetadataJSON(e){ensureInitialized();const t=refCBytesIntoBuffer(dittoffi_connection_request_peer_metadata_json(e));return(new TextDecoder).decode(t)}function connectionRequestIdentityServiceMetadataJSON(e){ensureInitialized();const t=refCBytesIntoBuffer(dittoffi_connection_request_identity_service_metadata_json(e));return(new TextDecoder).decode(t)}function connectionRequestConnectionType(e){return ensureInitialized(),dittoffi_connection_request_connection_type(e)}function connectionRequestAuthorize(e,t){ensureInitialized(),dittoffi_connection_request_authorize(e,t)}function connectionRequestFree(e){ensureInitialized(),dittoffi_connection_request_free(e)}function presenceSetConnectionRequestHandler(e,t,n){if(ensureInitialized(),null==t)dittoffi_presence_set_connection_request_handler(e,null);else{dittoffi_presence_set_connection_request_handler(e,wrapAsyncBackgroundCbForFFI(n,t))}}function dittoSmallPeerInfoGetIsEnabled(e){return ensureInitialized(),ditto_small_peer_info_get_is_enabled(e)}async function dittoSmallPeerInfoSetEnabled(e,t){ensureInitialized(),ditto_small_peer_info_set_enabled(e,t)}async function dittoSmallPeerInfoGetSyncScope(e){return ensureInitialized(),ditto_small_peer_info_get_sync_scope(e)}async function dittoSmallPeerInfoSetSyncScope(e,t){return ensureInitialized(),ditto_small_peer_info_set_sync_scope(e,t)}function dittoSmallPeerInfoGetMetadata(e){ensureInitialized();return boxCStringIntoString(ditto_small_peer_info_get_metadata(e))}function dittoSmallPeerInfoSetMetadata(e,t){ensureInitialized();const n=ditto_small_peer_info_set_metadata(e,bytesFromString(t));switch(n){case 0:return;case-1:throw new Error("Internal inconsistency, the observability subsystem is unavailable.");case 1:throw new Error(`Validation error, size limit exceeded: ${errorMessage()||"metadata is too big"}`);case 2:throw new Error(`Validation error, ${errorMessage()||"depth limit for metadata object exceeded"}`);case 3:throw new Error(`Validation error, ${errorMessage()||`'${t}' is not a valid JSON object`}`);default:throw new Error(errorMessage()||`Internal inconsistency, ditto_small_peer_info_set_metadata() returned an unknown error code: ${n}`)}}function dittoSmallPeerInfoCollectionSetTransportConfigData(e,t){ensureInitialized(),ditto_small_peer_info_set_transport_config_data(e,t)}function dittoRegisterTransportConditionChangedCallback(e,t){ensureInitialized(),ditto_register_transport_condition_changed_callback(e,t?wrapBackgroundCbForFFI((e=>log("Error",`The registered "transport condition changed" callback errored with ${e}`)),t):null)}function dittoSetDeviceName(e,t){ensureInitialized();return boxCStringIntoString(ditto_set_device_name(e,bytesFromString(t)))}function dittoSetConnectRetryInterval(e,t){ensureInitialized();return ditto_set_connect_retry_interval(e,Math.min(Math.max(0,t),4294967295))}function dittoSetSyncGroup(e,t){return ensureInitialized(),ditto_set_sync_group(e,t)}async function dittoNewAttachmentFromBytes(e,t){ensureInitialized();const n={},r=await ditto_new_attachment_from_bytes(e,t,n);if(0!==r)throw new DittoFFIError(r,null,`ditto_new_attachment_from_bytes() failed with error code: ${r}`);return n}async function dittoResolveAttachment(e,t,n,r){ensureInitialized();const{onComplete:i,onProgress:o,onDelete:a}=n,s=wrapBackgroundCbForFFI(r,i),c=wrapBackgroundCbForFFI(r,o),d=wrapBackgroundCbForFFI(r,a),{status_code:l,cancel_token:u}=await ditto_resolve_attachment(e,t,s,c,d);if(0!==l)throw new DittoFFIError(l,null,`ditto_resolve_attachment() failed with error code: ${l}`);return u}function dittoCancelResolveAttachment(e,t,n){ensureInitialized();const r=ditto_cancel_resolve_attachment(e,t,n);if(0!==r)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${r}`)}function freeAttachmentHandle(e){ensureInitialized(),ditto_free_attachment_handle(e)}async function dittoGetCompleteAttachmentData(e,t){ensureInitialized();const{status:n,data:r}=await ditto_get_complete_attachment_data(e,t);if(0!==n)throw new Error(errorMessage()||`\`ditto_get_complete_attachment_data()\` failed with error code: ${n}`);return boxCBytesIntoBuffer(r)}function dittoGetSDKVersion(e){ensureInitialized();return boxCStringIntoString(ditto_get_sdk_version())}function dittoGetSDKSemver(){ensureInitialized();return boxCStringIntoString(dittoffi_get_sdk_semver())}function dittoPresenceV1(e){ensureInitialized();return boxCStringIntoString(ditto_presence_v1(e))}function dittoPresenceV3(e){ensureInitialized();return boxCStringIntoString(ditto_presence_v3(e))}function dittoStartTCPServer(e,t){ensureInitialized();return(void 0)(e,bytesFromString(t))}function dittoStopTCPServer(e){return ensureInitialized(),(void 0)(e)}async function dittoShutdown(e){return ensureInitialized(),await ditto_shutdown(e)}function dittoStartHTTPServer(e,t,n,r,i,o){ensureInitialized();return(void 0)(e,bytesFromString(t),bytesFromString(n),r,bytesFromString(i),bytesFromString(o))}function dittoStopHTTPServer(e){return ensureInitialized(),(void 0)(e)}function dittoRunGarbageCollection(e){return ensureInitialized(),ditto_run_garbage_collection(e)}async function dittoDisableSyncWithV3(e){ensureInitialized();const t=await ditto_disable_sync_with_v3(e);if(0!==t)throw new Error(errorMessage()||`ditto_disable_sync_with_v3() failed with error code: ${t}`)}function dittoSetStaticTCPClients(e,t){if(ensureInitialized(),t.length>0)throw new Error(`Web variant of Ditto does not support connecting to TCP servers: ${t.join(", ")}`)}function dittoSetStaticWebsocketClients(e,t,n){ensureInitialized();ditto_set_static_websocket_clients(e,t.map((e=>bytesFromString(e))),n)}function documentsHash(e){ensureInitialized();const{status_code:t,u64:n}=ditto_documents_hash(e);if(0!==t)throw new Error(errorMessage()||`\`ditto_documents_hash()\` failed with error code: ${t}`);return BigInt(n)}function documentsHashMnemonic(e){ensureInitialized();const{status_code:t,c_string:n}=ditto_documents_hash_mnemonic(e);if(0!==t)throw new Error(errorMessage()||`\`ditto_documents_hash_mnemonic()\` failed with error code: ${t}`);return boxCStringIntoString(n)}function base64encode(e,t){return boxCStringIntoString(dittoffi_base64_encode(e,t))}function tryBase64Decode(e,t){const n=dittoffi_try_base64_decode(bytesFromString(e),t||null);return throwOnErrorResult(n.error,"dittoffi_try_base64_decode"),boxCBytesIntoBuffer(n.success)}async function dittoAuthSetLoginProvider(e,t){return ensureInitialized(),await ditto_auth_set_login_provider(e,t)}function dittoAuthClientMakeLoginProvider(e,t){return ensureInitialized(),ditto_auth_client_make_login_provider(wrapBackgroundCbForFFI(t,e))}function dittoAuthClientSetValidityListener(e,t,n){ensureInitialized();return ditto_auth_client_set_validity_listener(e,wrapBackgroundCbForFFI(n,(function(e,n){return t(1===e,1===n)})))}function transportsInit(){ensureInitialized()}function transportsBLEIsAvailable(e){return ensureInitialized(),!1}function transportsLANIsAvailable(e){return ensureInitialized(),!1}function transportsAWDLIsAvailable(e){return ensureInitialized(),!1}!function(e){e[e.counter=0]="counter",e[e.register=1]="register",e[e.attachment=2]="attachment",e[e.rga=3]="rga",e[e.rwMap=4]="rwMap"}(DittoCRDTType||(DittoCRDTType={}));let isInitialized$1=!1;async function init$1(e){e?await init$2(e):await init$2(),isInitialized$1=!0}function initSDKVersion(e,t,n){ensureInitialized(),bytesFromString(e),bytesFromString(t);const r=ditto_init_sdk_version(e,t,bytesFromString(n));if(void 0!==r&&0!==r)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${r}`)}function tryVerifyLicense(e){ensureInitialized();throwOnErrorResult(dittoffi_try_verify_license(bytesFromString(e)).error,"dittoffi_try_verify_license")}const NOT_FOUND_ERROR_CODE=-30798;function wrapBackgroundCbForFFI(e,t){const n=null!=e?e:e=>log("Error",`The registered callback failed with ${e}`);return(e,...r)=>{let i;try{i=t(...r)}catch(e){try{n(e)}catch(e){log("Error",`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${e}`)}}return e(i)}}function wrapAsyncBackgroundCbForFFI(e,t){const n=null!=e?e:e=>log("Error",`The registered callback failed with ${e}`);return async(e,...r)=>{let i;try{i=await t(...r)}catch(e){try{n(e)}catch(e){log("Error",`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${e}`)}}return e(i)}}function bytesFromString(e){if(void 0===e)return;if(null===e)return null;if("string"!=typeof e)throw new Error(`Can't convert string to Uint8Array, not a string: ${e}`);return(new TextEncoder).encode(`${e}\0`)}function errorMessage(){ensureInitialized();return boxCStringIntoString(ditto_error_message())}function ensureInitialized(){if(!isInitialized$1)throw new Error("Ditto needs to be initialized before using any of its API, please make sure to call `await init()` first.")}const ERROR_CODES={internal:"An unexpected internal error occurred. Please get in touch with Ditto customer service to report this incident.","internal/unknown-error":"An unexpected internal error occurred. Please get in touch with Ditto customer service to report this incident.","sdk/unsupported":"The feature is not supported by the current environment.","query/arguments-invalid":"The query arguments were invalid.","query/execution":"The query could not be executed.","query/invalid":"The query was invalid.","query/unsupported":"The query contains unsupported features.","query/parameter":"The query to update system parameters failed.","store/backend":"An error occurred with the storage backend.","store/crdt":"An error occurred processing a CRDT.","store/document-not-found":"The document with the provided ID could not be found.","store/attachment-file-permission-denied":"Permission has been denied for a file operation when working with attachments.","store/attachment-file-not-found":"The source file for the attachment does not exist.","store/attachment-not-found":"The attachment could not be found.","store/attachment-token-invalid":"The attachment token is invalid.","store/failed-to-create-attachment":"The attachment could not be created.","store/failed-to-fetch-attachment":"The attachment could not be fetched.","activation/license-token-verification-failed":"Please provide a valid license token.","activation/license-token-expired":"The license token expired. Please renew it.","activation/license-token-unsupported-future-version":"The provided license token is in an unsupported future format.","activation/not-activated":"The operation failed because the Ditto instance has not yet been activated.","validation/depth-limit-exceeded":"The maximum depth limit has been exceeded.","validation/invalid-cbor":"The value provided is not valid CBOR.","validation/invalid-json":"The value provided is not valid JSON.","validation/not-an-object":"The value provided is not of type object.","validation/not-json-compatible":"Value is not serializable as JSON.","validation/size-limit-exceeded":"The size limit has been exceeded."},DEFAULT_STATUS_CODE_MAPPING={ActivationLicenseTokenExpired:["activation/license-token-expired"],ActivationLicenseTokenInvalid:["activation/license-token-verification-failed"],ActivationLicenseUnsupportedFutureVersion:["activation/license-token-unsupported-future-version"],ActivationNotActivated:["activation/not-activated"],JsFloatingStoreOperation:["internal","Internal inconsistency, an outstanding store operation was not awaited."],DqlQueryCompilation:["query/invalid"],DqlInvalidQueryArgs:["query/arguments-invalid"],DqlUnsupported:["query/unsupported"],StoreQuery:["query/execution"],ParameterQuery:["query/parameter"],StoreDocumentNotFound:["store/document-not-found"],StoreDatabase:["store/backend"],Crdt:["store/crdt"],Base64Invalid:["internal","Invalid base64 encoding."],ValidationDepthLimitExceeded:["validation/depth-limit-exceeded"],ValidationInvalidCbor:["validation/invalid-cbor"],ValidationInvalidJson:["validation/invalid-json"],ValidationNotAMap:["validation/not-an-object"],ValidationSizeLimitExceeded:["validation/size-limit-exceeded"],default:["internal/unknown-error"]};class DittoError extends Error{constructor(e,t,n={}){if(null==ERROR_CODES[e])throw new DittoError("internal",`Invalid error code: ${e}`);super(t||ERROR_CODES[e]),this.code="internal",this.code=e,this.context=Object.freeze({...n})}static fromFFIError(e,t,n,r){const i=n||e.message,o={coreError:e.code,coreErrorMessage:e.message,...r},a=new DittoError(t,i,o);return null!=e.stack&&(a.stack=e.stack),a}}function mapFFIErrors(e,t,n){try{return e()}catch(e){if(e instanceof DittoFFIError)throw translateFFIError(e,t,n);throw e}}async function mapFFIErrorsAsync(e,t,n){try{return await e()}catch(e){if(e instanceof DittoFFIError)throw translateFFIError(e,t,n);throw e}}const translateFFIError=(e,t,n)=>{var r;const i=e.code.toString();let o,a;return null!=t&&null!=t[i]?[o,a]=t[i]:[o,a]=null!==(r=DEFAULT_STATUS_CODE_MAPPING[i])&&void 0!==r?r:DEFAULT_STATUS_CODE_MAPPING.default,DittoError.fromFFIError(e,o,a,n)};class AttachmentToken{constructor(e){let t,n,r;null!=e[DittoCRDTTypeKey]?({id:t,len:n,meta:r}=AttachmentToken.validateTypedInput(e)):({id:t,len:n,meta:r}=AttachmentToken.validateUntypedInput(e)),this.id=mapFFIErrors((()=>base64encode(t,"Unpadded"))),this.idBytes=t,this.len=n,this.metadata=r}static validateTypedInput(e){if(e[DittoCRDTTypeKey]!==DittoCRDTType.attachment)throw new Error("Invalid attachment token");const t=e._id;if(!(t instanceof Uint8Array))throw new Error("Invalid attachment token id");const n=e._len;if("number"!=typeof n&&"bigint"!=typeof n||n<0)throw new Error("Invalid attachment token length, must be a non-negative number or bigint");const r=e._meta;if("object"!=typeof r)throw new Error("Invalid attachment token meta");return{id:t,len:n,meta:r}}static validateUntypedInput(e){const t=e.id;if("string"!=typeof t)throw new Error("Invalid attachment token id");const n=mapFFIErrors((()=>tryBase64Decode(t,"Unpadded")),{Base64Invalid:["store/attachment-token-invalid","Failed to decode attachment token id from base64 input"]},{attachmentTokenID:t}),r=e.len;if("number"!=typeof r&&"bigint"!=typeof r||r<0)throw new Error("Invalid attachment token length, must be a non-negative number or bigint");const i=e.metadata;if("object"!=typeof i)throw new Error("Invalid attachment token meta");return{id:n,len:r,meta:i}}}const fullBuildVersionString="4.7.2",defaultDittoWasmFileURL="https://software.ditto.live/js/Ditto/4.7.2/ditto.wasm";let isInitialized=!1;async function init(e={}){if(!isInitialized){{const t=e.webAssemblyModule||defaultDittoWasmFileURL;await init$1(t),initSDKVersion("Web","JavaScript","4.7.2"),loggerInit()}isInitialized=!0}}class Logger{static get logFile(){return this._logFile}static setLogFile(e){e?(loggerSetLogFile(e),this._logFile=e):(loggerSetLogFile(void 0),delete this._logFile)}static setLogFileURL(e){var t;this.setLogFile(null!==(t=null==e?void 0:e.pathname)&&void 0!==t?t:null)}static get enabled(){return loggerEnabledGet()}static set enabled(e){loggerEnabled(e)}static get emojiLogLevelHeadingsEnabled(){return loggerEmojiHeadingsEnabledGet()}static set emojiLogLevelHeadingsEnabled(e){loggerEmojiHeadingsEnabled(e)}static get minimumLogLevel(){return loggerMinimumLogLevelGet()}static set minimumLogLevel(e){loggerMinimumLogLevel(e)}static get customLogCallback(){return this._customLogCallback}static async setCustomLogCallback(e){e?(await loggerSetCustomLogCb(e),this._customLogCallback=e):(await loggerSetCustomLogCb(null),delete this._customLogCallback)}static log(e,t){log(e,t)}static error(e){this.log("Error",e)}static warning(e){this.log("Warning",e)}static info(e){this.log("Info",e)}static debug(e){this.log("Debug",e)}static verbose(e){this.log("Verbose",e)}constructor(){throw new Error("Logger can't be instantiated, use its static properties & methods directly instead.")}}const CBOR_OPTIONS=Object.freeze({dictionary:"object",mode:"strict"}),EMPTY_KEY=Symbol("EMPTY_KEY"),OMIT_VALUE=Symbol("OMIT_VALUE"),POW_2_24=5.960464477539063e-8,POW_2_32=4294967296,POW_2_53=9007199254740992,MAX_SAFE_INTEGER=18446744073709551616n,DECODE_CHUNK_SIZE=8192,kCborTag=6,kCborTagUint8=64,kCborTagUint16=69,kCborTagUint32=70,kCborTagInt8=72,kCborTagInt16=77,kCborTagInt32=78,kCborTagFloat32=85,kCborTagFloat64=86;function objectIs(e,t){return"function"==typeof Object.is?Object.is(e,t):e===t?0!==e||1/e==1/t:e!=e&&t!=t}function options(e){const t={...CBOR_OPTIONS};return"object"==typeof e&&(t.dictionary=function isDictionary(e){return"string"==typeof e&&["object","map"].includes(e)}(e.dictionary)?e.dictionary:CBOR_OPTIONS.dictionary,t.mode=function isMode(e){return"string"==typeof e&&["loose","strict","sequence"].includes(e)}(e.mode)?e.mode:CBOR_OPTIONS.mode),Object.freeze(t)}function lexicographicalCompare(e,t){const n=Math.min(e.byteLength,t.byteLength);for(let r=0;r<n;r++){const n=e[r]-t[r];if(0!==n)return n}return e.byteLength-t.byteLength}var _Sequence_instances,_Sequence_toInspectString,__classPrivateFieldGet=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class Sequence{static from(e){return new Sequence(Array.from(e))}constructor(e){_Sequence_instances.add(this),Object.defineProperty(this,"_data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._data=e||[]}add(e){return this._data.push(e)-1}remove(e){return this._data.splice(e,1)[0]}get(e){return this._data[e]}clone(){return new Sequence(this.data)}get data(){return Array.from(this._data)}get size(){return this._data.length}[(_Sequence_instances=new WeakSet,Symbol.toStringTag)](){return"Sequence"}[(_Sequence_toInspectString=function _Sequence_toInspectString(e){return`${this[Symbol.toStringTag]()}(${this.size}) ${e(this._data)}`},Symbol.for("Deno.customInspect"))](e){return __classPrivateFieldGet(this,_Sequence_instances,"m",_Sequence_toInspectString).call(this,e)}[Symbol.for("nodejs.util.inspect.custom")](e,t,n){return __classPrivateFieldGet(this,_Sequence_instances,"m",_Sequence_toInspectString).call(this,n)}}class SimpleValue{static create(e){if(void 0===e)return new SimpleValue(23);if(null===e)return new SimpleValue(22);if(!0===e)return new SimpleValue(21);if(!1===e)return new SimpleValue(20);if("number"==typeof e&&e>=0&&e<=255)return new SimpleValue(e);throw new Error("CBORError: Value out of range or not a simple value.")}constructor(e){switch(Object.defineProperty(this,"semantic",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!0){case 20===e:this.semantic="false";break;case 21===e:this.semantic="true";break;case 22===e:this.semantic="null";break;case 23===e:this.semantic="undefined";break;case e>23&&e<32:this.semantic="reserved";break;default:this.semantic="unassigned"}this.value=e}toPrimitive(){switch(this.semantic){case"false":return!1;case"true":return!0;case"null":return null;default:return}}}class TaggedValue{constructor(e,t){Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e,this.tag=t}}function decode(e,t,n={}){const{dictionary:r,mode:i}=options(n),o="sequence"===i||"strict"===i,a=new DataView(e),s=new Uint8Array(e);let c=0,reviverFunction=function(e,t){return t};function commitRead(e,t){return c+=e,t}function readArrayBuffer(t){return commitRead(t,new Uint8Array(e,c,t))}function readUint8(){return commitRead(1,s[c])}function readUint16(){return commitRead(2,a.getUint16(c))}function readBreak(){return 255===s[c]&&(c+=1,!0)}function readLength(e){if(e<24)return e;if(24===e)return readUint8();if(25===e)return readUint16();if(26===e)return function readUint32(){return commitRead(4,a.getUint32(c))}();if(27===e){const e=function readUint64(){return commitRead(8,a.getBigUint64(c))}();return e<POW_2_53?Number(e):e}if(31===e)return-1;throw new Error("CBORError: Invalid length encoding")}function readIndefiniteStringLength(e){const t=readUint8();if(255===t)return-1;const n=readLength(31&t);if(n<0||t>>5!==e)throw new Error("CBORError: Invalid indefinite length element");return Number(n)}function appendUtf16Data(e,t){for(let n=0;n<t;++n){let n=readUint8();128&n&&(n<224?(n=(31&n)<<6|63&readUint8(),t-=1):n<240?(n=(15&n)<<12|(63&readUint8())<<6|63&readUint8(),t-=2):(n=(15&n)<<18|(63&readUint8())<<12|(63&readUint8())<<6|63&readUint8(),t-=3)),n<65536?e.push(n):(n-=65536,e.push(55296|n>>10),e.push(56320|1023&n))}}function decodeItem(){const e=readUint8(),t=e>>5,n=31&e;let i,s;if(7===t)switch(n){case 25:return function readFloat16(){const e=new ArrayBuffer(4),t=new DataView(e),n=readUint16(),r=32768&n;let i=31744&n;const o=1023&n;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==o)return(r?-1:1)*o*POW_2_24;return t.setUint32(0,r<<16|i<<13|o<<13),t.getFloat32(0)}();case 26:return function readFloat32(){return commitRead(4,a.getFloat32(c))}();case 27:return function readFloat64(){return commitRead(8,a.getFloat64(c))}()}if(s=readLength(n),s<0&&(t<2||6<t))throw new Error("CBORError: Invalid length");switch(t){case 0:return reviverFunction(EMPTY_KEY,s);case 1:return reviverFunction(EMPTY_KEY,"number"==typeof s?-1-s:-1n-s);case 2:if(s<0){const e=[];let n=0;for(;(s=readIndefiniteStringLength(t))>=0;)n+=s,e.push(readArrayBuffer(s));const r=new Uint8Array(n);let o=0;for(i=0;i<e.length;++i)r.set(e[i],o),o+=e[i].length;return reviverFunction(EMPTY_KEY,r)}return reviverFunction(EMPTY_KEY,readArrayBuffer(s));case 3:{const e=[];if(s<0)for(;(s=readIndefiniteStringLength(t))>=0;)appendUtf16Data(e,s);else appendUtf16Data(e,s);let n="";for(i=0;i<e.length;i+=DECODE_CHUNK_SIZE)n+=String.fromCharCode.apply(null,e.slice(i,i+DECODE_CHUNK_SIZE));return reviverFunction(EMPTY_KEY,n)}case 4:{let e;if(s<0){e=[];let t=0;for(;!readBreak();)e.push(reviverFunction(t++,decodeItem()))}else for(e=new Array(s),i=0;i<s;++i)e[i]=reviverFunction(i,decodeItem());return reviverFunction(EMPTY_KEY,e)}case 5:{if("map"===r){const e=new Map;for(i=0;i<s||s<0&&!readBreak();++i){const t=decodeItem();if(o&&e.has(t))throw new Error("CBORError: Duplicate key encountered");e.set(t,reviverFunction(t,decodeItem()))}return reviverFunction(EMPTY_KEY,e)}const e={};for(i=0;i<s||s<0&&!readBreak();++i){const t=decodeItem();if(o&&Object.prototype.hasOwnProperty.call(e,t))throw new Error("CBORError: Duplicate key encountered");e[t]=reviverFunction(t,decodeItem())}return reviverFunction(EMPTY_KEY,e)}case 6:{const e=decodeItem(),t=s;if(e instanceof Uint8Array){const n=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);switch(t){case kCborTagUint8:return reviverFunction(EMPTY_KEY,new Uint8Array(n));case kCborTagInt8:return reviverFunction(EMPTY_KEY,new Int8Array(n));case kCborTagUint16:return reviverFunction(EMPTY_KEY,new Uint16Array(n));case kCborTagInt16:return reviverFunction(EMPTY_KEY,new Int16Array(n));case kCborTagUint32:return reviverFunction(EMPTY_KEY,new Uint32Array(n));case kCborTagInt32:return reviverFunction(EMPTY_KEY,new Int32Array(n));case kCborTagFloat32:return reviverFunction(EMPTY_KEY,new Float32Array(n));case kCborTagFloat64:return reviverFunction(EMPTY_KEY,new Float64Array(n))}}return reviverFunction(EMPTY_KEY,new TaggedValue(e,t))}case 7:switch(s){case 20:return reviverFunction(EMPTY_KEY,!1);case 21:return reviverFunction(EMPTY_KEY,!0);case 22:return reviverFunction(EMPTY_KEY,null);case 23:return reviverFunction(EMPTY_KEY,void 0);default:return reviverFunction(EMPTY_KEY,new SimpleValue(s))}}}"function"==typeof t&&(reviverFunction=t);const d=decodeItem();if(c!==e.byteLength){if("sequence"!==i)throw new Error("CBORError: Remaining bytes");const t=new Sequence([d]);for(;c<e.byteLength;)t.add(reviverFunction(EMPTY_KEY,decodeItem()));return t}return"sequence"===i?new Sequence([d]):d}function parse(e,t,n){return decode(e,t,n)}function encode(e,t){let n,r=new ArrayBuffer(256),i=new DataView(r),o=new Uint8Array(r),a=0,replacerFunction=(e,t)=>t;if("function"==typeof t&&(replacerFunction=t),Array.isArray(t)){const e=t.slice();replacerFunction=(t,n)=>t===EMPTY_KEY||e.includes(t)?n:OMIT_VALUE}function prepareWrite(e){let t=r.byteLength;const s=a+e;for(;t<s;)t<<=1;if(t!==r.byteLength){const e=i;r=new ArrayBuffer(t),i=new DataView(r),o=new Uint8Array(r);const n=a+3>>2;for(let t=0;t<n;++t)i.setUint32(t<<2,e.getUint32(t<<2))}return n=e,i}function commitWrite(...e){a+=n}function writeUint8(e){commitWrite(prepareWrite(1).setUint8(a,e))}function writeUint8Array(e){prepareWrite(e.length),o.set(e,a),commitWrite()}function writeUint16(e){commitWrite(prepareWrite(2).setUint16(a,e))}function writeUint32(e){commitWrite(prepareWrite(4).setUint32(a,e))}function writeUint64(e){const t=e%POW_2_32,n=(e-t)/POW_2_32,r=prepareWrite(8);r.setUint32(a,n),r.setUint32(a+4,t),commitWrite()}function writeBigUint64(e){commitWrite(prepareWrite(8).setBigUint64(a,e))}function writeVarUint(e,t){e<=255?e<24?writeUint8(Number(e)|t):(writeUint8(24|t),writeUint8(Number(e))):e<=65535?(writeUint8(25|t),writeUint16(Number(e))):e<=4294967295?(writeUint8(26|t),writeUint32(Number(e))):(writeUint8(27|t),"number"==typeof e?writeUint64(e):writeBigUint64(e))}function writeTypeAndLength(e,t){t<24?writeUint8(e<<5|t):t<256?(writeUint8(e<<5|24),writeUint8(t)):t<65536?(writeUint8(e<<5|25),writeUint16(t)):t<4294967296?(writeUint8(e<<5|26),writeUint32(t)):(writeUint8(e<<5|27),writeUint64(t))}function encodeItem(e){if(e!==OMIT_VALUE){if(!1===e)return writeUint8(244);if(!0===e)return writeUint8(245);if(null===e)return writeUint8(246);if(void 0===e)return writeUint8(247);if(objectIs(e,-0))return writeUint8Array([249,128,0]);switch(typeof e){case"bigint":return function writeBigInteger(e){let t=0;if(0<=e&&e<=MAX_SAFE_INTEGER)t=0;else{if(!(-MAX_SAFE_INTEGER<=e&&e<0))throw new Error("CBORError: Encountered unsafe integer outside of valid CBOR range.");t=1,e=-(e+1n)}if(e<0x100000000n)return writeTypeAndLength(t,Number(e));writeUint8(t<<5|27),writeBigUint64(e)}(e);case"number":if(Math.floor(e)===e){if(0<=e&&e<=POW_2_53)return writeTypeAndLength(0,e);if(-POW_2_53<=e&&e<0)return writeTypeAndLength(1,-(e+1))}return writeUint8(251),function writeFloat64(e){commitWrite(prepareWrite(8).setFloat64(a,e))}(e);case"string":{const t=[],n=e.length;for(let r=0;r<n;++r){let n=e.charCodeAt(r);n<128?t.push(n):n<2048?(t.push(192|n>>6),t.push(128|63&n)):n<55296||n>=57344?(t.push(224|n>>12),t.push(128|n>>6&63),t.push(128|63&n)):(n=(1023&n)<<10,n|=1023&e.charCodeAt(++r),n+=65536,t.push(240|n>>18),t.push(128|n>>12&63),t.push(128|n>>6&63),t.push(128|63&n))}return writeTypeAndLength(3,t.length),writeUint8Array(t)}default:{let t;if(Array.isArray(e))!function writeArray(e){const t=a,n=e.length;let r=0;writeTypeAndLength(4,n);const i=a;for(let t=0;t<n;t+=1){const n=replacerFunction(t,e[t]);n!==OMIT_VALUE&&(encodeItem(n),r+=1)}if(n>r){const e=o.slice(i,a);a=t,writeTypeAndLength(4,r),writeUint8Array(e)}}(e);else if(e instanceof Uint8Array)writeVarUint(kCborTagUint8,kCborTag<<5),writeTypeAndLength(2,e.length),writeUint8Array(e);else if(e instanceof Int8Array)writeVarUint(kCborTagInt8,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(e instanceof Uint16Array)writeVarUint(kCborTagUint16,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(e instanceof Int16Array)writeVarUint(kCborTagInt16,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(e instanceof Uint32Array)writeVarUint(kCborTagUint32,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(e instanceof Int32Array)writeVarUint(kCborTagInt32,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(e instanceof Float32Array)writeVarUint(kCborTagFloat32,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(e instanceof Float64Array)writeVarUint(kCborTagFloat64,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(ArrayBuffer.isView(e))t=new Uint8Array(e.buffer),writeTypeAndLength(2,t.length),writeUint8Array(t);else if(e instanceof ArrayBuffer||"function"==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)t=new Uint8Array(e),writeTypeAndLength(2,t.length),writeUint8Array(t);else if(e instanceof TaggedValue)writeVarUint(e.tag,192),encodeItem(e.value);else if(e instanceof SimpleValue)writeTypeAndLength(7,e.value);else if(e instanceof Sequence){if(0!==a)throw new Error("CBORError: A CBOR Sequence may not be nested.");const t=e.size;for(let n=0;n<t;n+=1)encodeItem(e.get(n))}else!function writeDictionary(e){const t=[],n=a;let r=a,i=0,s=0;if(e instanceof Map){i=e.size,writeTypeAndLength(5,i),r=a;for(const[n,r]of e.entries()){const e=replacerFunction(n,r);if(e===OMIT_VALUE)continue;let i=a;encodeItem(n);const c=o.slice(i,a);i=a,encodeItem(e);const d=o.slice(i,a);s+=1,t.push([c,d])}}else{const n=Object.keys(e);i=n.length,writeTypeAndLength(5,i),r=a;for(let r=0;r<i;r+=1){const i=n[r],c=replacerFunction(i,e[i]);if(c===OMIT_VALUE)continue;let d=a;encodeItem(i);const l=o.slice(d,a);d=a,encodeItem(c);const u=o.slice(d,a);s+=1,t.push([l,u])}}function sortEncodedKeys(e){a=n,writeTypeAndLength(5,s),t.sort((([e],[t])=>lexicographicalCompare(e,t)));for(let n=0;n<e;n+=1){const[e,r]=t[n];writeUint8Array(e),writeUint8Array(r)}}if(i>s){const e=t.length;if(e>1)sortEncodedKeys(e);else{const e=o.slice(r,a);a=n,writeTypeAndLength(5,s),writeUint8Array(e)}}else{const e=t.length;e>1&&sortEncodedKeys(e)}}(e)}}}}if(encodeItem(replacerFunction(EMPTY_KEY,e)),"slice"in r)return r.slice(0,a);const s=new ArrayBuffer(a),c=new DataView(s);for(let e=0;e<a;++e)c.setUint8(e,i.getUint8(e));return s}function binarify(e,t){return encode(e,t)}const CBOR$1={binarify:binarify,decode:decode,encode:encode,parse:parse};class CBOR{static encode(e,t){const n=CBOR$1.encode(e,t);return new Uint8Array(n)}static decode(e,t){const n=e.buffer;return CBOR$1.decode(n,t)}}class DocumentID{get value(){let e=this["@ditto.value"];return void 0===e&&(e=CBOR.decode(this["@ditto.cbor"]),this["@ditto.value"]=e),e}constructor(e,t=!1,n=!1){const r=t?e:CBOR.encode(e),i=n?r:validateDocumentIDCBOR(r);if(!i)throw new Error(`Can't create DocumentID, passed in value is not valid: ${e}`);this.isValidated=!n,this["@ditto.cbor"]=i}equals(e){const t=this["@ditto.cbor"],n=e["@ditto.cbor"];if(t===n)return!0;if(!(t instanceof Uint8Array))return!1;if(!(n instanceof Uint8Array))return!1;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e+=1)if(t[e]!==n[e])return!1;return!0}toString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithoutQuotes")}toBase64String(){return mapFFIErrors((()=>base64encode(this["@ditto.cbor"],"Padded")))}toQueryCompatibleString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithQuotes")}toCBOR(){return this["@ditto.cbor"]}}function validateDocumentIDValue(e){if(void 0===e)throw new Error(`Invalid document ID: ${e}`);return e}function validateDocumentIDCBOR(e){const t=validateDocumentID(e);return null!=t?t:e}var _a;const DEBUG_TYPE_NAMES=[],DEBUG_ALL_TYPES=!1;class Handle{constructor(e,t,n){this.isClosed=!1,this.isFinalized=!1,this.isUnregistered=!1,this.bridge=e,this.objectWeakRef=new WeakRef(t),this.pointer=n}get type(){return this.bridge.type}deref(){if(this.isClosed)throw new Error("Bridging error: can't get pointer for an object that has been closed.");if(this.isFinalized)throw new Error("Bridging error: can't get pointer for an object that has been finalized.");if(this.isUnregistered)throw new Error("Bridging error: can't get pointer for an object that has been unregistered.");return this.pointer}derefOrNull(){var e;return this.isClosed||this.isFinalized||this.isUnregistered?null:null!==(e=this.pointer)&&void 0!==e?e:null}object(){const e=this.objectWeakRef.deref();if(null==e)throw new Error(`Bridging error: ${this.bridge.type.name} object has been garbage collected.`);if(this.isClosed)throw new Error(`Bridging error: ${this.bridge.type.name} object has been closed.`);if(this.isUnregistered)throw new Error(`Bridging error: ${this.bridge.type.name} object has been unregistered.`);return e}objectOrNull(){var e;return null!==(e=this.objectWeakRef.deref())&&void 0!==e?e:null}toString(){const e=this.derefOrNull();return`{ Handle | type: ${this.bridge.type}, object: ${this.objectWeakRef.deref()}, FFI address: ${null==e?void 0:e.addr}, FFI type: ${null==e?void 0:e.type} }`}bridgeWillClose(){this.isClosed=!0}bridgeDidClose(){this.pointer=null}bridgeWillFinalize(){this.isFinalized=!0}bridgeDidFinalize(){this.pointer=null}bridgeWillUnregister(){this.isUnregistered=!0}bridgeDidUnregister(){this.pointer=null}}class Handles{constructor(e,t){this.handles=t.map((t=>e.handleFor(t)))}deref(){return this.handles.map((e=>e.deref()))}}class Bridge{constructor(e){this.internalType=null,this.release=e,this.handlesByAddress={},this.handlesByObject=new WeakMap,this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this)),_a.all.push(new WeakRef(this))}get type(){if(null==this.internalType)throw new Error("Bridge type has not been registered yet.");return this.internalType}registerType(e){if(this.internalType!==e){if(this.internalType)throw new Error(`Can't register bridged type '${e.name}', another type was already registered: ${this.internalType}`);this.internalType=e}}handleFor(e){const t=this.handlesByObject.get(e);if(null==t)throw new Error(`Bridging error: ${this.type.name} object is not currently registered in this bridge.`);return t}handlesFor(e){return new Handles(this,e)}objectFor(e){const t=this.handlesByAddress[e.addr];if(t){if(t.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${t.type} but this bridge is configured for ${this.type}`);return t.object()}}bridge(e,t){const n=this.objectFor(e);if(n)return n;let r;if(t||(t=()=>Reflect.construct(this.type,[])),"function"==typeof t){if(r=t(),!(r instanceof this.type))throw new Error(`Can't bridge, expected passed in create function to return a ${this.type.name} object but got: ${r}`)}else r=t;return this.register(r,e),r}register(e,t){const n=e.constructor;if(n!==this.type)throw new Error(`Can't register, bridge is configured for type ${this.type.name} but passed in object is of type ${n.name}`);const r=this.handlesByObject.get(e),i=r?r.pointer:null;if(null!=i&&null!=r)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${r.object()}`);if(null!=i&&null==r)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no handle entry: ${n.name} at ${i.type} ${i.addr}`);if(null==i&&null!=r)throw new Error(`Internal inconsistency, trying to register an object which has a handle entry but no associated pointer: ${n.name} ${e}`);const o=new Handle(this,e,t);this.handlesByAddress[t.addr]=o,this.handlesByObject.set(e,o),this.finalizationRegistry.register(e,o,e),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge REGISTERED a new instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}unregister(e){const t=e.constructor,n=this.type;if(t!==n)throw new Error(`Can't unregister, bridge is configured for type ${n.name} but passed in object is of type ${t.name}`);const r=this.handlesByObject.get(e);if(null==r)throw new Error(`Can't unregister, object has not been registered before: ${e}`);if(r.type!==n)throw new Error(`Internal inconsistency, trying to unregister an object that has a handle with a different type than that of the bridge: ${r}`);if(r.objectOrNull()!==e)throw new Error(`Internal inconsistency, trying to unregister an object whose associated handle holds a different object: ${r}`);if(r.isClosed)throw new Error(`Can't unregister, object has been closed before: ${e}`);if(r.isFinalized)throw new Error(`Can't unregister, object has been finalized before: ${e}`);if(r.isUnregistered)throw new Error(`Can't unregister, object has been unregistered already: ${e}`);r.bridgeWillUnregister(),this.finalizationRegistry.unregister(e),delete this.handlesByAddress[r.pointer.addr],this.handlesByObject.delete(e),r.bridgeDidUnregister(),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge UNREGISTERED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}unregisterAll(){DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Unregistering ALL bridged instances of type ${this.type.name}.`);for(const e of Object.values(this.handlesByAddress)){const t=e.object();t&&this.unregister(t)}}async close(e){const t=e.constructor,n=this.type;if(t!==n)throw new Error(`Can't close, bridge is configured for type ${n.name} but passed in object is of type ${t.name}`);const r=this.handlesByObject.get(e);if(null==r)throw new Error(`Can't close an object that has not been registered before: ${e}`);if(r.type!==n)throw new Error(`Internal inconsistency, trying to close an object that has a handle with a different type than that of the bridge: ${r}`);if(r.isUnregistered)throw new Error("Can't close object, object has been unregistered.");if(r.isFinalized)throw new Error("Internal inconsistency, trying to close an object that has already been finalized.");if(r.isClosed)return;const i=r.pointer;if(!i)throw new Error("Internal inconsistency, trying to close an object whose pointer is null.");r.bridgeWillClose(),delete this.handlesByAddress[i.addr],await this.release(i),r.bridgeDidClose(),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge CLOSED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}get count(){return Object.keys(this.handlesByAddress).length}async finalize(e){if(e.isFinalized)throw new Error("Internal inconsistency, trying to finalize an object that has already been finalized.");if(e.isUnregistered)throw new Error("Internal inconsistency, trying to finalize an object that has been unregistered before.");if(e.bridgeWillFinalize(),!e.isClosed){const t=e.pointer;if(!t)throw new Error("Internal inconsistency, trying to finalize an object whose pointer is null.");delete this.handlesByAddress[t.addr],await this.release(t)}e.bridgeDidFinalize(),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge FINALIZED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}}_a=Bridge,Bridge.all=[],Bridge.attachment=new _a(freeAttachmentHandle),Bridge.connectionRequest=new _a(connectionRequestFree),Bridge.document=new _a(documentFree),Bridge.mutableDocument=new _a(documentFree),Bridge.queryResult=new _a(queryResultFree),Bridge.queryResultItem=new _a(queryResultItemFree),Bridge.staticTCPClient=new _a(staticTCPClientFreeHandle),Bridge.websocketClient=new _a(websocketClientFreeHandle),Bridge.ditto=new _a((async e=>{await dittoClearPresenceCallback(e),await dittoShutdown(e),dittoFree(e)}));class Attachment{get id(){return this.token.id}get len(){return this.token.len}get metadata(){return this.token.metadata}data(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return this.ditto.deferCloseAsync((async()=>{{const e=Bridge.attachment.handleFor(this);return await dittoGetCompleteAttachmentData(t.deref(),e.deref())}}))}getData(){return this.data()}copyToPath(e){const t=this.ditto;return Bridge.ditto.handleFor(t),this.ditto.deferCloseAsync((async()=>{throw new Error("Can't copy attachment to path, not available when running in the browser.")}))}constructor(e,t){this.ditto=e,this.token=t}}function validateAttachmentMetadata(e){if("object"!=typeof e)throw new DittoError("store/failed-to-create-attachment",`Invalid attachment metadata: expected a value of type object but got ${typeof e}.`);for(const t in e)if("string"!=typeof e[t])throw new DittoError("store/failed-to-create-attachment",`Invalid attachment metadata: metadata values must be strings but key '${t}' has a value of type ${typeof e[t]}.`)}function augmentJSONValue(e,t,n){if(e&&"object"==typeof e){if(Array.isArray(e))return e.map(((e,r)=>augmentJSONValue(e,t,`${n}[${r}]`)));if(e[DittoCRDTTypeKey]===DittoCRDTType.counter)return Counter["@ditto.create"](t,n,e._value);if(e[DittoCRDTTypeKey]===DittoCRDTType.register)return Register["@ditto.create"](t,n,e._value);if(e[DittoCRDTTypeKey]===DittoCRDTType.attachment)return new AttachmentToken(e);for(const[r,i]of Object.entries(e))e[r]=augmentJSONValue(i,t,`${n}['${r}']`);return e}return e}function desugarJSObject(e){if(e&&"object"==typeof e){if(Array.isArray(e))return e.map(((e,t)=>desugarJSObject(e)));if(e instanceof DocumentID)return e.value;if(e instanceof Counter){const t={};return t[DittoCRDTTypeKey]=DittoCRDTType.counter,t._value=e.value,t}if(e instanceof Register){const t={};return t[DittoCRDTTypeKey]=DittoCRDTType.register,t._value=e.value,t}if(e instanceof Attachment){const t={_id:e.token.idBytes,_len:e.token.len,_meta:e.token.metadata};return t[DittoCRDTTypeKey]=DittoCRDTType.attachment,t}{const t={};for(const[n,r]of Object.entries(e))t[n]=desugarJSObject(r);return t}}return checkForUnsupportedValues(e),e}function checkForUnsupportedValues(e){if(Number.isNaN(e)||e===1/0||e===-1/0)throw new Error("Non-finite float values are not supported")}class UpdateResult{static set(e,t,n){return new UpdateResult("set",e,t,n,void 0)}static incremented(e,t,n){return new UpdateResult("incremented",e,t,void 0,n)}static removed(e,t){return new UpdateResult("removed",e,t,void 0,void 0)}constructor(e,t,n,r,i){this.type=e,this.docID=t,this.path=n,void 0!==r&&(this.value=r),void 0!==i&&(this.amount=i)}}const defaultDittoCloudDomain="cloud.ditto.live";function defaultAuthURL(e){return`https://${e}.${defaultDittoCloudDomain}`}function defaultDittoCloudURL(e){return`wss://${e}.${defaultDittoCloudDomain}`}function validateNumber(e,t={}){var n;const r=null!==(n=t.errorMessagePrefix)&&void 0!==n?n:"Number validation failed:",i=!!t.integer,o=t.min,a=t.max,s=t.minX,c=t.maxX;if("number"!=typeof e)throw new Error(`${r} '${e}' is not a number.`);if(i&&Math.floor(e)!==e)throw new Error(`${r} '${e}' is not an integer.`);if(void 0!==o&&e<o)throw new Error(`${r} '${e}' must be >= ${o}.`);if(void 0!==a&&e>a)throw new Error(`${r} '${e}' must be <= ${a}.`);if(void 0!==s&&e<=s)throw new Error(`${r} '${e}' must be > ${s}.`);if(void 0!==c&&e>=c)throw new Error(`${r} '${e}' must be < ${c}.`);return e}function validateQuery(e,t={}){var n;const r=null!==(n=t.errorMessagePrefix)&&void 0!==n?n:"Query validation failed,";if("string"!=typeof e)throw new Error(`${r} query is not a string: ${e}`);if(""===e)throw new Error(`${r} query is an empty string.`);const i=e.trim();if(""===i)throw new Error(`${r} query contains only whitespace characters.`);return i}function generateEphemeralToken(){let e,t=new Uint16Array(16);e=crypto,e.getRandomValues(t);return Array.from(t).map((e=>e.toString(16))).join("")}function customInspectRepresentation(e,t){return void 0===t?`${e.constructor.name} ${JSON.stringify({value:e.value},null,2)}`:`${e.constructor.name} ${t({value:e.value})}`}function sleep(e){return new Promise(((t,n)=>{setTimeout(t,e)}))}async function step(e){return await sleep(0),e()}const performAsyncToWorkaroundNonAsyncFFIAPI=step,regularKeyPattern=/\.([A-Za-z_]\w*)/.source,subscriptIndexPattern=/\[(\d+)\]/.source,subscriptSingleQuoteKeyPattern=/\[\'(.+?)\'\]/.source,subscriptDoubleQuoteKeyPattern=/\[\"(.+?)\"\]/.source,validKeyPathPattern=`((${regularKeyPattern})|(${subscriptIndexPattern})|(${subscriptSingleQuoteKeyPattern})|(${subscriptDoubleQuoteKeyPattern}))*`,regularKeyRegExp=new RegExp(`^${regularKeyPattern}`),subscriptIndexRegExp=new RegExp(`^${subscriptIndexPattern}`),subscriptSingleQuoteKeyRegExp=new RegExp(`^${subscriptSingleQuoteKeyPattern}`),subscriptDoubleQuoteKeyRegExp=new RegExp(`^${subscriptDoubleQuoteKeyPattern}`),validKeyPathRegExp=new RegExp(`^${validKeyPathPattern}$`);class KeyPath{static withLeadingDot(e){if("number"==typeof e)return e;if("string"!=typeof e)throw new Error(`Key-path must be a string or a number but is ${typeof e}: ${e}`);return"string"==typeof e&&!!e.match(/^[A-Za-z_]/)?`.${e}`:e}static withoutLeadingDot(e){if("number"==typeof e)return e;if("string"!=typeof e)throw new Error(`Key-path must be a string or a number but is ${typeof e}: ${e}`);return"string"==typeof e&&!!e.match(/^\./)?e.slice(1):e}static validate(e,t={}){var n;const r=null!==(n=t.isInitial)&&void 0!==n&&n;if("number"==typeof e)return Math.floor(Math.abs(e));if("string"!=typeof e)throw new Error(`Key-path must be a string or a number but is ${typeof e}: ${e}`);const i=this.withLeadingDot(e);if(!validKeyPathRegExp.test(i))throw new Error(`Key-path is not valid: ${e}`);return r?e:i}static evaluate(e,t,n={}){var r;const i=null!==(r=n.stopAtLastContainer)&&void 0!==r&&r,o={keyPath:e,object:t,options:{...n},coveredPath:null,nextPathComponent:null,remainingPath:e,value:t};return function recurse(e,t){if(""===t)return o.value=e,o;const{nextPathComponentRaw:n,nextPathComponent:r,remainingPath:a}=function advance(e){if("number"==typeof e)return{nextPathComponentRaw:e,nextPathComponent:e,remainingPath:""};if("string"!=typeof e)throw new Error(`Can't return value at given keyPath, expected keyPath to be a string or a number but got ${typeof e}: ${e}`);const t=e.match(regularKeyRegExp);if(null!==t){const n=t[0],r=t[1];return{nextPathComponentRaw:n,nextPathComponent:r,remainingPath:e.slice(r.length+1)}}const n=e.match(subscriptIndexRegExp);if(null!==n){const t=n[0],r=n[1];return{nextPathComponentRaw:t,nextPathComponent:parseInt(r),remainingPath:e.slice(r.length+2)}}const r=e.match(subscriptSingleQuoteKeyRegExp);if(null!==r){const t=r[0],n=r[1];return{nextPathComponentRaw:t,nextPathComponent:n,remainingPath:e.slice(n.length+4)}}const i=e.match(subscriptDoubleQuoteKeyRegExp);if(null!==i){const t=i[0],n=i[1];return{nextPathComponentRaw:t,nextPathComponent:n,remainingPath:e.slice(n.length+4)}}throw new Error(`Can't return value at keyPath because the following part of the keyPath is invalid: ${e}`)}(t);return o.nextPathComponent=r,o.remainingPath=a,null===o.coveredPath||"number"==typeof n?o.coveredPath=n:o.coveredPath+=n,""===a&&i?(o.value=e,o):recurse(e[r],a)}(t,this.withLeadingDot(e))}constructor(){}}class DocumentPath{at(e){if("string"==typeof e){const t=e,n=KeyPath.validate(t),r=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new DocumentPath(this.document,r,!1)}if("number"==typeof e){const t=validateNumber(e,{integer:!0,min:0,errorMessagePrefix:"DocumentPath.at() validation failed index:"});return new DocumentPath(this.document,`${this.path}[${t.toString()}]`,!1)}throw new Error(`Can't return document path at key-path or index, string or number expected but got ${typeof e}: ${e}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const e=this.underlyingValueForPathType("Counter");return void 0!==e?Counter["@ditto.create"](null,this.path,e):null}get register(){const e=this.underlyingValueForPathType("Register");return void 0!==e?Register["@ditto.create"](null,this.path,e):null}get attachmentToken(){const e=this.underlyingValueForPathType("Attachment");return void 0!==e?new AttachmentToken(e):null}constructor(e,t,n){this.document=e,this.path=n?KeyPath.validate(t,{isInitial:!0}):t}underlyingValueForPathType(e){const t=this.path,n=this.document,r=documentGetCBORWithPathType(Bridge.document.handleFor(n).deref(),t,e);return null!==r.cbor?CBOR.decode(r.cbor):void 0}}class MutableDocumentPath{at(e){if("string"==typeof e){const t=e,n=KeyPath.validate(t),r=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new MutableDocumentPath(this.mutableDocument,r,!1)}if("number"==typeof e){const t=validateNumber(e,{integer:!0,min:0,errorMessagePrefix:"MutableDocumentPath.at() validation failed index:"});return new MutableDocumentPath(this.mutableDocument,`${this.path}[${t.toString()}]`,!1)}throw new Error(`Can't return mutable document path at key-path or index, string or number expected but got ${typeof e}: ${e}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const e=this.underlyingValueForPathType("Counter");return void 0!==e?Counter["@ditto.create"](this.mutableDocument,this.path,e):null}get register(){const e=this.underlyingValueForPathType("Register");return void 0!==e?Register["@ditto.create"](this.mutableDocument,this.path,e):null}get attachmentToken(){const e=this.underlyingValueForPathType("Attachment");return void 0!==e?new AttachmentToken(e):null}set(e,t){return this["@ditto.set"](e,t)}remove(){return this["@ditto.remove"]()}constructor(e,t,n){this.mutableDocument=e,this.path=n?KeyPath.validate(t,{isInitial:!0}):t}underlyingValueForPathType(e){const t=this.path,n=this.mutableDocument,r=documentGetCBORWithPathType(Bridge.mutableDocument.handleFor(n).deref(),t,e);return null!==r.cbor?CBOR.decode(r.cbor):void 0}"@ditto.increment"(e){documentIncrementCounter(Bridge.mutableDocument.handleFor(this.mutableDocument).deref(),this.path,e);const t=UpdateResult.incremented(this.mutableDocument.id,this.path,e);this.recordUpdateResult(t)}"@ditto.set"(e,t){const n=Bridge.mutableDocument.handleFor(this.mutableDocument),r=desugarJSObject(e),i=CBOR.encode(r);t?documentSetCBORWithTimestamp(n.deref(),this.path,i,0):documentSetCBOR(n.deref(),this.path,i);const o=augmentJSONValue(CBOR.decode(i),this.mutableDocument,this.path),a=UpdateResult.set(this.mutableDocument.id,this.path,o);this.recordUpdateResult(a)}"@ditto.remove"(){documentRemove(Bridge.mutableDocument.handleFor(this.mutableDocument).deref(),this.path),this.updateInMemory(((e,t)=>{Array.isArray(e)&&"number"==typeof t?e.splice(t,1):delete e[t]}));const e=UpdateResult.removed(this.mutableDocument.id,this.path);this.recordUpdateResult(e)}updateInMemory(e){const t=this.mutableDocument.value,n=KeyPath.evaluate(this.path,t,{stopAtLastContainer:!0});e(n.value,n.nextPathComponent)}recordUpdateResult(e){const t=this.mutableDocument["@ditto.updateResults"].slice();t.push(e),Object.freeze(t),this.mutableDocument["@ditto.updateResults"]=t}}const CUSTOM_INSPECT_SYMBOL$1=Symbol.for("nodejs.util.inspect.custom");class Document{static hash(e){return documentsHash(documentsFrom(e).map((e=>Bridge.document.handleFor(e))).map((e=>e.deref())))}static hashMnemonic(e){const t=documentsFrom(e);return documentsHashMnemonic(Bridge.document.handlesFor(t).deref())}get id(){let e=this["@ditto.id"];if(void 0===e){const t=documentID(Bridge.document.handleFor(this).deref());e=new DocumentID(t,!0),this["@ditto.id"]=e}return e}get path(){return new DocumentPath(this,"",!1)}get value(){let e=this["@ditto.value"];return void 0===e&&(e=this.path.value,this["@ditto.value"]=e),e}at(e){return this.path.at(e)}constructor(){}static idCBOR(e){return documentID(Bridge.document.handleFor(e).deref())}static canonicalizedIDCBOR(e){return validateDocumentIDCBOR(e)}static isIDCBORCanonical(e){return e===this.canonicalizedIDCBOR(e)}toString(){return`${this.constructor.name}(${this.id})`}[CUSTOM_INSPECT_SYMBOL$1](e,t,n){return customInspectRepresentation(this,n)}}class MutableDocument{get id(){let e=this["@ditto.id"];if(void 0===e){const t=documentID(Bridge.mutableDocument.handleFor(this).deref());e=new DocumentID(t,!0),this["@ditto.id"]=e}return e}get path(){return new MutableDocumentPath(this,"",!1)}get value(){return this.path.value}at(e){return this.path.at(e)}constructor(){this["@ditto.updateResults"]=[]}static idCBOR(e){return documentID(Bridge.mutableDocument.handleFor(e).deref())}toString(){return`${this.constructor.name}(${this.id})`}[CUSTOM_INSPECT_SYMBOL$1](e,t,n){return customInspectRepresentation(this,n)}}function documentsFrom(e){if(!e)return[];if(e instanceof Document)return[e];if(e instanceof Array)return e;throw new Error(`Expected null, a single document, or an array of documents but got value of type ${typeof e}: ${e}`)}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR,MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;class UpdateResultsMap{get(e){const t=(e instanceof DocumentID?e:new DocumentID(e)).toString();return this.updateResultsByDocumentIDString[t]}keys(){return this.documentIDs.slice()}constructor(e,t){const n=e.map((e=>e.toString())).sort().join(", ");if(n!==Object.keys(t).sort().join(", "))throw new Error("Internal inconsistency, can't construct update results map, documentIDs must all be keys in update results (by document ID string)");this.documentIDs=e.slice(),this.updateResultsByDocumentIDString={...t}}}class BasePendingCursorOperation{sort(e,t="ascending"){return this.orderBys.push({query:e,direction:"ascending"===t?"Ascending":"Descending"}),this}offset(e){if(e<0)throw new Error(`Can't offset by '${e}', offset must be >= 0`);if(!Number.isFinite(e))throw new Error(`Can't offset by '${e}', offset must be a finite number`);if(Number.isNaN(e))throw new Error(`Can't offset by '${e}', offset must be a valid number`);if(e!==Math.round(e))throw new Error(`Can't offset by '${e}', offset must be an integer number`);return this.currentOffset=e,this}limit(e){if(e<-1)throw new Error(`Can't limit to '${e}', limit must be >= -1 (where -1 means unlimited)`);if(!Number.isFinite(e))throw new Error(`Can't limit to '${e}', limit must be a finite number`);if(Number.isNaN(e))throw new Error(`Can't limit to '${e}', limit must be a valid number`);if(e!==Math.round(e))throw new Error(`Can't limit to '${e}', limit must be an integer number`);return this.currentLimit=e,this}async exec(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.query;return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionExecQueryStr(t.deref(),this.collection.name,null,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((e=>Bridge.document.bridge(e)))}))}async updateWithTransaction(e,t){const n=this.collection.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const n=this.query,i=await collectionExecQueryStr(r.deref(),this.collection.name,t,n,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset),o=i.map((e=>Bridge.mutableDocument.bridge(e,(()=>new MutableDocument))));e(o);const a=[],s={};for(const e of o){const t=e.id,n=t.toString(),r=e["@ditto.updateResults"];if(s[n])throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${n}`);a.push(t),s[n]=r,Bridge.mutableDocument.unregister(e)}return await collectionUpdateMultiple(r.deref(),this.collection.name,t,i),new UpdateResultsMap(a,s)}))))}constructor(e,t,n){if(this.currentLimit=-1,this.currentOffset=0,this.orderBys=[],this.query=validateQuery(e),this.queryArgs=t?Object.freeze({...t}):null,this.collection=n,null==t)this.queryArgsCBOR=null;else{const e=desugarJSObject(t);this.queryArgsCBOR=CBOR.encode(e)}}then(e,t){return this.exec().then(e,t)}}class BasePendingIDSpecificOperation{async exec(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await readTransaction(t.deref()),n=await collectionGet(t.deref(),this.collection.name,this.documentIDCBOR,e);let r;return n&&(r=Bridge.document.bridge(n)),readTransactionFree(e),r}))))}constructor(e,t){this.documentID=e,this.collection=t,this.documentIDCBOR=e.toCBOR()}then(e,t){return this.exec().then(e,t)}get query(){return`_id == ${this.documentID.toQueryCompatibleString()}`}}class ConnectionRequest{get peerKeyString(){return connectionRequestPeerKeyString(this.deref())}get peerMetadata(){return JSON.parse(this.peerMetadataJSONString)}get peerMetadataJSONString(){return connectionRequestPeerMetadataJSON(this.deref())}get identityServiceMetadata(){return JSON.parse(this.identityServiceMetadataJSONString)}get identityServiceMetadataJSONString(){return connectionRequestIdentityServiceMetadataJSON(this.deref())}get connectionType(){return connectionRequestConnectionType(this.deref())}toString(){return`ConnectionRequest(${this.peerKeyString} via ${this.connectionType})`}[Symbol.for("nodejs.util.inspect.custom")](e,t,n){return this.toString()}deref(){return Bridge.connectionRequest.handleFor(this).deref()}}class ObserverManager{constructor(e,t={}){var n,r,i,o;const a=null!==(n=t.keepAlive)&&void 0!==n?n:null,s=null!==(r=t.register)&&void 0!==r?r:null,c=null!==(i=t.unregister)&&void 0!==i?i:null,d=null!==(o=t.process)&&void 0!==o?o:null;this.id=e,this.keepAlive=a,this.isClosed=!1,this.isRegistered=!1,this.callbacksByToken={},null!==s&&(this.register=s),null!==c&&(this.unregister=c),null!==d&&(this.process=d)}addObserver(e){var t;if(this.isClosed)throw new Error(`Internal inconsistency, can't add '${this.id}' observer, observer mananger close()-ed.`);this.registerIfNeeded();const n=generateEphemeralToken();return this.callbacksByToken[n]=e,null===(t=this.keepAlive)||void 0===t||t.retain(`${this.id}.${n}`),n}removeObserver(e){var t;const n=this.callbacksByToken[e];if(void 0===n)throw new Error(`Can't remove '${this.id}' observer, token '${e}' has never been registered before.`);null!==n&&(this.callbacksByToken[e]=null,null===(t=this.keepAlive)||void 0===t||t.release(`${this.id}.${e}`),this.unregisterIfNeeded())}hasObserver(e){return void 0!==this.callbacksByToken[e]}notify(...e){if(this.isClosed)return;const t=this.process(...e);for(const e in this.callbacksByToken){const n=this.callbacksByToken[e];n&&n(...t)}}close(){this.isClosed=!0;for(const e in this.callbacksByToken)this.removeObserver(e)}register(e){}unregister(){}process(...e){return e}hasObservers(){return Object.keys(this.callbacksByToken).length>0}registerIfNeeded(){if(!this.isRegistered){const e=new WeakRef(this);this.isRegistered=!0,this.register((function(...t){const n=e.deref();n&&n.notify(...t)}))}}unregisterIfNeeded(){!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,this.unregister())}}class Authenticator{get status(){return this._status}loginWithToken(e,t){throw new Error("Authenticator.loginWithToken() is abstract and must be implemented by subclasses.")}loginWithUsernameAndPassword(e,t,n){throw new Error("Authenticator.loginWithUsernameAndPassword() is abstract and must be implemented by subclasses.")}logout(e){throw new Error("Authenticator.logout() is abstract and must be implemented by subclasses.")}observeStatus(e){const t=this.observerManager.addObserver(e);return new Observer(this.observerManager,t,{stopsWhenFinalized:!0})}constructor(e){this.keepAlive=e,this._status={isAuthenticated:!1,userID:null},this.loginSupported=!1,this.observerManager=new ObserverManager("AuthenticationStatusObservation",{keepAlive:e})}"@ditto.authenticationExpiring"(e){throw new Error("Authenticator['@ditto.authenticationExpiring']() is abstract and must be implemented by subclasses.")}"@ditto.authClientValidityChanged"(e,t){throw new Error("Authenticator['@ditto.authClientValidityChanged']() is abstract and must be implemented by subclasses.")}close(){this.observerManager.close()}}class OnlineAuthenticator extends Authenticator{async loginWithToken(e,t){const n=this.ditto.deref();if(!n)return;const r=Bridge.ditto.handleFor(n).derefOrNull();return r?n.deferCloseAsync((async()=>{await dittoAuthClientLoginWithToken(r,e,t)})):void 0}async loginWithUsernameAndPassword(e,t,n){const r=this.ditto.deref();if(!r)return;const i=Bridge.ditto.handleFor(r).derefOrNull();return i?r.deferCloseAsync((async()=>{await dittoAuthClientLoginWithUsernameAndPassword(i,e,t,n)})):void 0}async logout(e){const t=this.ditto.deref();if(!t)return;const n=Bridge.ditto.handleFor(t).derefOrNull();return n?t.deferCloseAsync((async()=>{await dittoAuthClientLogout(n),t.stopSync(),null==e||e(t)})):void 0}constructor(e,t,n){super(e),this.loginSupported=!0,this._status={isAuthenticated:!1,userID:null},this.ditto=new WeakRef(t),this.authenticationHandler=n,this.updateAndNotify(!1)}"@ditto.authenticationExpiring"(e){const t=this.authenticationHandler;e>0?t.authenticationExpiringSoon(this,e):t.authenticationRequired(this)}"@ditto.authClientValidityChanged"(e,t){this.updateAndNotify(!0)}updateAndNotify(e){var t;const n=this.ditto.deref();if(!n)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const r=Bridge.ditto.handleFor(n).derefOrNull();if(!r)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const i=this.status.isAuthenticated,o=this.status.userID,a=dittoAuthClientIsWebValid(r),s=dittoAuthClientUserID(r),c={isAuthenticated:a,userID:s};if(this._status=c,e){!!i==!!a&&o===s||(null===(t=this.authenticationHandler.authenticationStatusDidChange)||void 0===t||t.call(this.authenticationHandler,this),this.observerManager.notify(c))}}}class NotAvailableAuthenticator extends Authenticator{async loginWithToken(e,t){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}async loginWithUsernameAndPassword(e,t,n){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}logout(e){throw new Error("Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}"@ditto.authenticationExpiring"(e){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${this}`)}"@ditto.authClientValidityChanged"(e,t){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authClientValidityChanged() was called on authenticator: ${this}`)}}const IdentityTypesRequiringOfflineLicenseToken=["manual","sharedKey","offlinePlayground"];function transportConfigFromDeserializable(e){const t=e.peer_to_peer,n=t.bluetooth_le.enabled,r=t.awdl.enabled,i=t.lan,o=i.enabled,a=i.mdns_enabled,s=i.multicast_enabled,c=e.connect,d=c.tcp_servers,l=c.websocket_urls,u=c.retry_interval,_=e.listen,g=_.tcp,h=g.enabled,f=g.interface_ip,b=g.port,m=_.http,y=m.enabled,w=m.interface_ip,p=m.port,v=m.static_content_path,I=m.websocket_sync,O=m.tls_key_path,k=m.tls_certificate_path,j=e.global,C=j.sync_group,M=j.routing_hint,E=new TransportConfig;return E.peerToPeer.bluetoothLE.isEnabled=n,E.peerToPeer.awdl.isEnabled=r,E.peerToPeer.lan.isEnabled=o,E.peerToPeer.lan.isMdnsEnabled=a,E.peerToPeer.lan.isMulticastEnabled=s,E.connect.tcpServers=d,E.connect.websocketURLs=l,E.connect.retryInterval=u,E.listen.tcp.isEnabled=h,E.listen.tcp.interfaceIP=f,E.listen.tcp.port=b,E.listen.http.isEnabled=y,E.listen.http.interfaceIP=w,E.listen.http.port=p,E.listen.http.staticContentPath=v,E.listen.http.websocketSync=I,E.listen.http.tlsKeyPath=O,E.listen.http.tlsCertificatePath=k,E.global.syncGroup=C,E.global.routingHint=M,E}function transportConfigToSerializable(e){const t=e.peerToPeer,n=e.connect,r=e.listen,i=e.global,o={peer_to_peer:{bluetooth_le:{enabled:t.bluetoothLE.isEnabled},awdl:{enabled:t.awdl.isEnabled},lan:{enabled:t.lan.isEnabled,mdns_enabled:t.lan.isMdnsEnabled,multicast_enabled:t.lan.isMulticastEnabled}},connect:{tcp_servers:n.tcpServers,websocket_urls:n.websocketURLs,retry_interval:n.retryInterval},listen:{tcp:{enabled:r.tcp.isEnabled,interface_ip:r.tcp.interfaceIP,port:r.tcp.port},http:{enabled:r.http.isEnabled,interface_ip:r.http.interfaceIP,port:r.http.port,websocket_sync:r.http.websocketSync}},global:{sync_group:i.syncGroup,routing_hint:i.routingHint}};return r.http.staticContentPath&&(o.listen.http.static_content_path=r.http.staticContentPath),r.http.tlsKeyPath&&(o.listen.http.tls_key_path=r.http.tlsKeyPath),r.http.tlsCertificatePath&&(o.listen.http.tls_certificate_path=r.http.tlsCertificatePath),o}const NO_PREFERRED_ROUTE_HINT=0;class TransportConfig{constructor(){this._isFrozen=!1,this.peerToPeer={bluetoothLE:{isEnabled:!1},awdl:{isEnabled:!1},lan:{isEnabled:!1,isMdnsEnabled:!0,isMulticastEnabled:!0}},this.connect={tcpServers:[],websocketURLs:[],retryInterval:5e3},this.listen={tcp:{isEnabled:!1,interfaceIP:"[::]",port:4040},http:{isEnabled:!1,interfaceIP:"[::]",port:80,websocketSync:!0}},this.global={syncGroup:0,routingHint:0}}setAllPeerToPeerEnabled(e){this.peerToPeer.bluetoothLE.isEnabled=e,this.peerToPeer.lan.isEnabled=e,this.peerToPeer.awdl.isEnabled=e}get isFrozen(){return this._isFrozen}freeze(){return this.isFrozen||(this._isFrozen=!0,Object.freeze(this.peerToPeer.bluetoothLE),Object.freeze(this.peerToPeer.awdl),Object.freeze(this.peerToPeer.lan),Object.freeze(this.peerToPeer),Object.freeze(this.connect.tcpServers),Object.freeze(this.connect.websocketURLs),Object.freeze(this.connect),Object.freeze(this.listen.tcp),Object.freeze(this.listen.http),Object.freeze(this.listen),Object.freeze(this.global)),this}copy(){const e=new TransportConfig;return e.peerToPeer.bluetoothLE.isEnabled=this.peerToPeer.bluetoothLE.isEnabled,e.peerToPeer.awdl.isEnabled=this.peerToPeer.awdl.isEnabled,e.peerToPeer.lan.isEnabled=this.peerToPeer.lan.isEnabled,e.peerToPeer.lan.isMdnsEnabled=this.peerToPeer.lan.isMdnsEnabled,e.peerToPeer.lan.isMulticastEnabled=this.peerToPeer.lan.isMulticastEnabled,e.connect.tcpServers=this.connect.tcpServers.slice(),e.connect.websocketURLs=this.connect.websocketURLs.slice(),e.connect.retryInterval=this.connect.retryInterval,e.listen.tcp={...this.listen.tcp},e.listen.http={...this.listen.http},e.global.syncGroup=this.global.syncGroup,e.global.routingHint=this.global.routingHint,e}static areListenTCPsEqual(e,t){return e.isEnabled===t.isEnabled&&e.interfaceIP===t.interfaceIP&&e.port===t.port}static areListenHTTPsEqual(e,t){return e.isEnabled===t.isEnabled&&e.interfaceIP===t.interfaceIP&&e.port===t.port&&e.staticContentPath===t.staticContentPath&&e.websocketSync===t.websocketSync&&e.tlsKeyPath===t.tlsKeyPath&&e.tlsCertificatePath===t.tlsCertificatePath}}class AttachmentFetcher{stop(){if(null==this.manager){this.isStopped||(this.rejectPendingFetch(),this.rejectPendingFetch=null),this.ditto.store.removeAttachmentFetcher(this);const e=Bridge.ditto.handleFor(this.ditto);this.ditto.deferCloseAsync((async()=>{const t=await this.cancelTokenPromise;t&&dittoCancelResolveAttachment(e.deref(),this.token.idBytes,t)}))}else step((async()=>{await this.manager.stopAttachmentFetcher(this),null!=this.rejectPendingFetch&&(this.rejectPendingFetch(),this.rejectPendingFetch=null)}))}then(e,t){return this.attachment.then(e,t)}constructor(e,t,n,r){this.cancelTokenPromise=null,this.rejectPendingFetch=null,this.ditto=e,this.token=t,this.manager=n,this.id=generateEphemeralToken();const i=r||function(){},o=Bridge.ditto.handleFor(e);this.attachment=new Promise(((e,n)=>{const onComplete=t=>{const n=new Attachment(this.ditto,this.token);Bridge.attachment.bridge(t,(()=>n)),i({type:"Completed",attachment:n}),this.rejectPendingFetch=null,e(n)},onProgress=(e,t)=>{i({type:"Progress",totalBytes:t,downloadedBytes:e})},onDelete=()=>{i({type:"Deleted"}),null!=this.manager?(this.rejectPendingFetch=null,e(null)):(this.rejectPendingFetch=null,n(new DittoError("store/attachment-not-found","The attachment was deleted while being fetched.")))},onError=()=>{};this.rejectPendingFetch=()=>{const e=null!=this.manager?new Error("Attachment fetch was canceled"):new DittoError("store/failed-to-fetch-attachment","Attachment fetch was canceled");n(e)};const r=new WeakRef(this);this.cancelTokenPromise=(async()=>{try{return await mapFFIErrorsAsync((async()=>dittoResolveAttachment(o.deref(),t.idBytes,{onComplete:onComplete,onProgress:onProgress,onDelete:onDelete},onError)),{1:["store/failed-to-fetch-attachment","Failed to fetch the attachment."],2:["store/attachment-token-invalid","The attachment token was invalid."],3:["store/attachment-not-found","The attachment was not found."]})}catch(t){let o=!1;t instanceof DittoError&&"store/attachment-not-found"===t.code&&(o=!0,i({type:"Deleted"})),Logger.error(t.message);const a=r.deref();return null==a||(null!=a.manager&&t instanceof DittoError&&(t=new Error(t.message)),a.rejectPendingFetch=null,null!=a.manager&&o?e(null):n(t)),null}})()})),null==n&&this.attachment.then((()=>{this.rejectPendingFetch=null,this.ditto.store.removeAttachmentFetcher(this)})).catch((()=>{this.rejectPendingFetch=null,this.ditto.store.removeAttachmentFetcher(this)}))}get isStopped(){return null==this.rejectPendingFetch}}class Subscription{get isCancelled(){return this._isCancelled}get collectionName(){return this.collection.name}cancel(){this.isCancelled||(this._isCancelled=!0,this.manager.remove(this))}constructor(e,t,n,r,i,o){this._isCancelled=!1,this.query=t,this.queryArgsCBOR=n,this.collection=e,this.contextInfo={id:generateEphemeralToken(),collectionName:e.name,query:t,queryArgsCBOR:n,orderBys:r,limit:i,offset:o},this.manager=e.store.ditto.subscriptionManager,this.manager.add(this)}}class LiveQueryEventInitial{constructor(){this.isInitial=!0}hash(e){Logger.warning("LiveQueryEventInitial.hash() is deprecated, use Document.hash() instead");return documentsHash(Bridge.document.handlesFor(e).deref())}hashMnemonic(e){Logger.warning("LiveQueryEventInitial.hashMnemonic() is deprecated, use Document.hashMnemonic() instead");return documentsHashMnemonic(Bridge.document.handlesFor(e).deref())}}class LiveQueryEventUpdate{hash(e){Logger.warning("LiveQueryEventUpdate.hash() is deprecated, use Document.hash() instead");return documentsHash(Bridge.document.handlesFor(e).deref())}hashMnemonic(e){Logger.warning("LiveQueryEventUpdate.hashMnemonic() is deprecated, use Document.hashMnemonic() instead");return documentsHashMnemonic(Bridge.document.handlesFor(e).deref())}constructor(e){this.isInitial=!1,this.oldDocuments=e.oldDocuments,this.insertions=e.insertions,this.deletions=e.deletions,this.updates=e.updates,this.moves=e.moves}}class SingleDocumentLiveQueryEvent{hash(e){Logger.warning("SingleDocumentLiveQueryEvent.hash() is deprecated, use Document.hash() instead");return documentsHash(Bridge.document.handlesFor(null==e?[]:[e]).deref())}hashMnemonic(e){Logger.warning("SingleDocumentLiveQueryEvent.hashMnemonic() is deprecated, use Document.hashMnemonic() instead");return documentsHashMnemonic(Bridge.document.handlesFor(null==e?[]:[e]).deref())}constructor(e,t){this.isInitial=e,this.oldDocument=t}}class LiveQuery{get collectionName(){return this.collection.name}get isStopped(){return!this.liveQueryManager}stop(){this.isStopped||this.liveQueryManager.stopLiveQuery(this)}get liveQueryID(){return this._liveQueryID}constructor(e,t,n,r,i,o,a,s){this.query=e,this.queryArgs=t?Object.freeze({...t}):null,this.queryArgsCBOR=n,this.orderBys=r,this.limit=i,this.offset=o,this.collection=a,this.handler=s,this.liveQueryManager=null;const c=a.name,d=new WeakRef(a.store.ditto);let l;const signalNext=async()=>{const e=d.deref();if(!e)return;const t=Bridge.ditto.handleFor(e).derefOrNull();return t?e.deferCloseAsync((async()=>{await liveQuerySignalAvailableNext(t,l)})):void 0},u=a.store.ditto,_=Bridge.ditto.handleFor(u);if(u.deferClose((()=>{l=liveQueryRegister(_.deref(),c,e,n,this.orderBys,i,o,(e=>{const t=e.documents.map((e=>Bridge.document.bridge(e)));let n;n=e.is_initial?new LiveQueryEventInitial:new LiveQueryEventUpdate({oldDocuments:e.old_documents.map((e=>Bridge.document.bridge(e))),insertions:e.insertions,deletions:e.deletions,updates:e.updates,moves:e.moves.map((e=>({from:e[0],to:e[1]})))}),s(t,n,signalNext)}))})),!l)throw new Error("Internal inconsistency, couldn't create a valid live query ID.");this._liveQueryID=l}async signalNext(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);if(t.derefOrNull())return e.deferCloseAsync((async()=>{await liveQuerySignalAvailableNext(t.deref(),this.liveQueryID)}))}}class PendingCursorOperation extends BasePendingCursorOperation{sort(e,t="ascending"){return super.sort(e,t)}offset(e){return super.offset(e)}limit(e){return super.limit(e)}async remove(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.query;return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const n=await writeTransaction(t.deref()),r=await collectionRemoveQueryStr(t.deref(),this.collection.name,n,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(t.deref(),n),r}))).map((e=>new DocumentID(e,!0)))}))}async evict(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.query;return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const n=await writeTransaction(t.deref()),r=await collectionEvictQueryStr(t.deref(),this.collection.name,n,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(t.deref(),n),r}))).map((e=>new DocumentID(e,!0)))}))}async update(e){const t=this.collection.store.ditto,n=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const t=await writeTransaction(n.deref()),r=await super.updateWithTransaction(e,t);return await writeTransactionCommit(n.deref(),t),r}))))}subscribe(){const e=new Subscription(this.collection,this.query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return this.collection.store.ditto.subscriptionManager.add(e),e}observeLocal(e){return this._observe(e,!1)}observeLocalWithNextSignal(e){return this._observe(e,!0)}constructor(e,t,n){super(e,t,n)}_observe(e,t){const n=t?e:async function wrappedHandler(t,n,r){try{return await e.call(this,t,n)}finally{r()}},r=new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,n);return this.collection.store.ditto.liveQueryManager.startLiveQuery(r),r}}class PendingIDSpecificOperation extends BasePendingIDSpecificOperation{async remove(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await writeTransaction(t.deref()),n=await collectionRemove(t.deref(),this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t.deref(),e),n}))))}async evict(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await writeTransaction(t.deref()),n=await collectionEvict(t.deref(),this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t.deref(),e),n}))))}async update(e){const t=this.collection.store.ditto,n=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=await readTransaction(n.deref()),r=await collectionGet(n.deref(),this.collection.name,this.documentIDCBOR,t);if(readTransactionFree(t),!r)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const i=Bridge.mutableDocument.bridge(r,(()=>new MutableDocument));e(i),Bridge.mutableDocument.unregister(i);const o=await writeTransaction(n.deref());return await collectionUpdate(n.deref(),this.collection.name,o,r),await writeTransactionCommit(n.deref(),o),i["@ditto.updateResults"].slice()}))}subscribe(){const e=new Subscription(this.collection,this.query,null,[],-1,0);return this.collection.store.ditto.subscriptionManager.add(e),e}observeLocal(e){return this._observe(e,!1)}observeLocalWithNextSignal(e){return this._observe(e,!0)}constructor(e,t){super(e,t)}_observe(e,t){const n=new LiveQuery(this.query,null,null,[],-1,0,this.collection,(async(n,r,i)=>{if(n.length>1)throw new Error(`Internal inconsistency, single document live query returned more than one document. Query: ${this.query}}.`);if(!1===r.isInitial&&r.oldDocuments.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one old documents. Query ${this.query}.`);if(!1===r.isInitial&&r.insertions.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one insertion, which doesn't make sense for single document observations. Query ${this.query}.`);if(!1===r.isInitial&&r.deletions.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one deletion, which doesn't make sense for single document observations. Query ${this.query}.`);if(!1===r.isInitial&&r.updates.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one update, which doesn't make sense for single document observations. Query ${this.query}.`);if(!1===r.isInitial&&r.moves.length>0)throw new Error(`Internal inconsistency, single document live query returned an update event with moves, which doesn't make sense for single document observations. Query ${this.query}.`);if((!0===r.isInitial?0:r.insertions.length+r.deletions.length+r.updates.length)>1)throw new Error(`Internal inconsistency, single document live query returned a combination of inserts, updates, and/or deletes, which doesn't make sense for single document observation. Query ${this.query}.`);const o=n[0]||null,a=!0===r.isInitial?void 0:r.oldDocuments[0],s=new SingleDocumentLiveQueryEvent(r.isInitial,a);if(t)e(o,s,i);else try{await e(o,s)}finally{i()}}));return this.collection.store.ditto.liveQueryManager.startLiveQuery(n),n}}class Collection{find(e,t){return new PendingCursorOperation(e,null!=t?t:null,this)}findAll(){return this.find("true")}findByID(e){const t=e instanceof DocumentID?e:new DocumentID(e);return new PendingIDSpecificOperation(t,this)}async upsert(e,t={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{var n;const i=null!==(n=t.writeStrategy)&&void 0!==n?n:"merge",o=desugarJSObject(e),a=CBOR.encode(o),s=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionInsertValue(r.deref(),this.name,a,i,void 0)));return new DocumentID(s,!0)}))}async newAttachment(e,t={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{const{id:i,len:o,handle:a}=await(async()=>{if("string"==typeof e)throw new Error("Can't create attachment from file when running in the browser. Please pass the raw data (as a Uint8Array) instead.");if(e instanceof Uint8Array)return await dittoNewAttachmentFromBytes(r.deref(),e);throw new Error(`Can't create new attachment, only file path as string or raw data as Uint8Array are supported, but got: ${typeof e}, ${e}`)})(),s={_id:i,_len:o,_meta:{...t}};s[DittoCRDTTypeKey]=DittoCRDTType.attachment;const c=new AttachmentToken(s),d=new Attachment(n,c);return Bridge.attachment.bridge(a,(()=>d))}))}fetchAttachment(e,t){if(null==e||!(e instanceof AttachmentToken))throw new Error(`Invalid attachment token: ${e}`);const n=this.store.ditto;return n.deferClose((()=>n.attachmentFetcherManager.startAttachmentFetcher(e,t)))}constructor(e,t){this.name=e,this.store=t}findByIDCBOR(e){const t=new DocumentID(e,!0,!0);return new PendingIDSpecificOperation(t,this)}}class QueryResult{mutatedDocumentIDs(){return queryResultMutatedDocumentIDs(Bridge.queryResult.handleFor(this).deref()).map((e=>new DocumentID(e,!0)))}constructor(e){if(null==e)throw new Error("Internal inconsistency, failed to initialize query result without a response pointer");const t=queryResultItems(e);this.items=t.map((e=>Bridge.queryResultItem.bridge(e)))}}class StoreObserver{get isCancelled(){return this._isCancelled}cancel(){this._isCancelled||(this._isCancelled=!0,this.ditto.store.unregisterObserver(this))}constructor(e,t,n,r){this._isCancelled=!1,this.queryString=t,this.queryArguments=n?Object.freeze({...n}):void 0,this.ditto=e;let i,o=null;if(null!=n)try{const e=desugarJSObject(n);o=CBOR.encode(e)}catch(e){throw new DittoError("query/arguments-invalid")}const a=Bridge.ditto.handleFor(e);if(this.ditto.deferClose((()=>{const e=new WeakRef(this);function wrappedObservationHandler(t){const n=e.deref();if(null==n)return void Logger.debug(`Ignoring change event received by store observer ${i} after it was cancelled`);const o=Bridge.queryResult.bridge(t.query_result,(()=>new QueryResult(t.query_result)));Logger.debug(`Invoking user event handler with new event for store observer ${i}`),r(o,(()=>n.signalNext()))}mapFFIErrors((()=>{i=tryExperimentalRegisterChangeObserver(a.deref(),t,o,wrappedObservationHandler)}))})),null==i)throw new DittoError("internal","Internal inconsistency, store observer ID is undefined after registering");this.liveQueryID=i}signalNext(){const e=this.ditto;if(!e||e.isClosed)return;const t=Bridge.ditto.handleFor(e).derefOrNull();if(t){if(null==this.liveQueryID)throw new Error("live query ID is null while signaling ready for next event");return e.deferCloseAsync((async()=>{Logger.debug(`Signaling availability for live query ${this.liveQueryID}`),await liveQuerySignalAvailableNext(t,this.liveQueryID)}))}}}class CollectionsEvent{static initial(e){return new CollectionsEvent({isInitial:!0,collections:e,oldCollections:[],insertions:[],deletions:[],updates:[],moves:[]})}constructor(e){this.isInitial=e.isInitial,this.collections=e.collections,this.oldCollections=e.oldCollections,this.insertions=e.insertions,this.deletions=e.deletions,this.updates=e.updates,this.moves=e.moves}}class PendingCollectionsOperation{sort(e,t="ascending"){return this.pendingCursorOperation.sort(e,t),this}offset(e){return this.pendingCursorOperation.offset(e),this}limit(e){return this.pendingCursorOperation.limit(e),this}subscribe(){return this.pendingCursorOperation.subscribe()}observeLocal(e){return this._observe(e,!1)}observeLocalWithNextSignal(e){return this._observe(e,!0)}async exec(){return collectionsFromDocuments(await this.pendingCursorOperation.exec(),this.store)}constructor(e){this.store=e,this.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",e))}then(e,t){return this.exec().then(e,t)}_observe(e,t){const n=new WeakRef(this.store);return this.pendingCursorOperation._observe((function(r,i,o){const a=n.deref();if(!a)return;const s=collectionsFromDocuments(r,a);let c;if(!0===i.isInitial)c=CollectionsEvent.initial(s);else{const e=collectionsFromDocuments(i.oldDocuments,a);c=new CollectionsEvent({isInitial:!1,collections:s,oldCollections:e,insertions:i.insertions,deletions:i.deletions,updates:i.updates,moves:i.moves})}t?e(c,o):e(c)}),t)}}function collectionsFromDocuments(e,t){const n=[];for(const r of e){const e=r.at("name").value;void 0!==e&&"string"==typeof e&&n.push(new Collection(e,t))}return n}class WriteTransactionPendingCursorOperation extends BasePendingCursorOperation{sort(e,t="ascending"){return super.sort(e,t)}offset(e){return super.offset(e)}limit(e){return super.limit(e)}async remove(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.query,n=this.collection.writeTransaction,r=(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>collectionRemoveQueryStr(t.deref(),this.collection.name,n.writeTransactionPointer,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((e=>new DocumentID(e,!0)));return r.forEach((e=>{n.addResult("removed",e,this.collection.name)})),r}))}async evict(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.query,n=this.collection.writeTransaction,r=(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>collectionEvictQueryStr(t.deref(),this.collection.name,n.writeTransactionPointer,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((e=>new DocumentID(e,!0)));return r.forEach((e=>{n.addResult("evicted",e,this.collection.name)})),r}))}async update(e){const t=this.collection.writeTransaction,n=await super.updateWithTransaction(e,t.writeTransactionPointer);return n.keys().forEach((e=>{t.addResult("updated",e,this.collection.name)})),n}constructor(e,t,n){super(e,t,n)}}class WriteTransactionPendingIDSpecificOperation extends BasePendingIDSpecificOperation{async remove(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.collection.writeTransaction,n=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>collectionRemove(t.deref(),this.collection.name,e.writeTransactionPointer,this.documentIDCBOR)));return e.addResult("removed",this.documentID,this.collection.name),n}))}async evict(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.collection.writeTransaction,n=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionEvict(t.deref(),this.collection.name,e.writeTransactionPointer,this.documentIDCBOR)));return e.addResult("evicted",this.documentID,this.collection.name),n}))}async update(e){const t=this.collection.store.ditto,n=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.collection.writeTransaction,r=await readTransaction(n.deref()),i=await collectionGet(n.deref(),this.collection.name,this.documentIDCBOR,r);if(readTransactionFree(r),!i)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const o=Bridge.mutableDocument.bridge(i,(()=>new MutableDocument));return e(o),Bridge.mutableDocument.unregister(o),await collectionUpdate(n.deref(),this.collection.name,t.writeTransactionPointer,i),t.addResult("updated",this.documentID,this.collection.name),o["@ditto.updateResults"].slice()}))}constructor(e,t){super(e,t)}}class WriteTransactionCollection{find(e,t){return new WriteTransactionPendingCursorOperation(e,null!=t?t:null,this)}findAll(){return this.find("true")}findByID(e){const t=e instanceof DocumentID?e:new DocumentID(e);return new WriteTransactionPendingIDSpecificOperation(t,this)}async upsert(e,t={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{var n;const i=null!==(n=t.writeStrategy)&&void 0!==n?n:"merge",o=desugarJSObject(e),a=CBOR.encode(o),s=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionInsertValue(r.deref(),this.name,a,i,this.writeTransaction.writeTransactionPointer))),c=new DocumentID(s,!0);return this.writeTransaction.addResult("inserted",c,this.name),new DocumentID(s,!0)}))}findByIDCBOR(e){const t=new DocumentID(e,!0,!0);return new WriteTransactionPendingIDSpecificOperation(t,this)}constructor(e,t,n){this.name=e,this.store=t,this.writeTransaction=n}}class WriteTransaction{static async init(e){return e.deferCloseAsync((async()=>{const t=Bridge.ditto.handleFor(e),n=await writeTransaction(t.deref());return new WriteTransaction(e,n)}))}scoped(e){if("string"!=typeof e)throw new Error("Collection name must be a string");return new WriteTransactionCollection(e,this.ditto.store,this)}async commit(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>writeTransactionCommit(t.deref(),this.writeTransactionPointer)))}async rollback(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>writeTransactionRollback(t.deref(),this.writeTransactionPointer)))}addResult(e,t,n){this.results.push({type:e,docID:t,collectionName:n})}constructor(e,t){this.writeTransactionPointer=t,this.ditto=e,this.results=[]}}class Store{registerObserver(e,t,n){return this.registerObserverWithSignalNext(e,((e,n)=>{try{t(e)}finally{n()}}),n)}registerObserverWithSignalNext(e,t,n){if("string"!=typeof e)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof e);const r=new StoreObserver(this.ditto,e,null!=n?n:null,t);this.observers=Object.freeze([...this.observers,r]);const i=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>new Promise((e=>{step((async()=>{try{await mapFFIErrorsAsync((async()=>await liveQueryStart(i.deref(),r.liveQueryID)))}catch(e){Logger.error(`Failed to start live query: ${e.message}`)}e()}))})))),r}collection(e){return new Collection(e,this)}collections(){return new PendingCollectionsOperation(this)}collectionNames(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return e.deferClose((()=>mapFFIErrors((()=>dittoGetCollectionNames(t.deref())))))}async execute(e,t){if("string"!=typeof e)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof e);const n=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{let r=null;if(null!=t)try{const e=desugarJSObject(t);r=CBOR.encode(e)}catch(e){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${e.message}`)}const i=await mapFFIErrorsAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((()=>tryExecStatement(n.deref(),null,e,r)))));return Bridge.queryResult.bridge(i,(()=>new QueryResult(i)))}))}async write(e){return this.ditto.deferCloseAsync((async()=>{const t=await WriteTransaction.init(this.ditto);try{await e(t)}catch(e){throw await t.rollback(),Logger.warning(`Transaction rolled back due to an error: ${null==e?void 0:e.message}`),e}return await t.commit(),t.results}))}async newAttachment(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);return null!=t&&validateAttachmentMetadata(t),n.deferCloseAsync((async()=>{const{id:i,len:o,handle:a}=await(async()=>{if("string"==typeof e)throw new DittoError("sdk/unsupported","Can't create attachment from file when running in the browser. Please pass the raw data (as a Uint8Array) instead.");if(e instanceof Uint8Array)return mapFFIErrorsAsync((async()=>await dittoNewAttachmentFromBytes(r.deref(),e)),{1:["store/failed-to-create-attachment"]});throw new Error(`Can't create new attachment, only file path as string or raw data as Uint8Array are supported, but got: ${typeof e}, ${e}`)})(),s={_id:i,_len:o,_meta:{...t},[DittoCRDTTypeKey]:DittoCRDTType.attachment},c=new AttachmentToken(s),d=new Attachment(n,c);return Bridge.attachment.bridge(a,(()=>d))}))}fetchAttachment(e,t){if(null==e)throw new Error("Missing required parameter 'token'");let n;n=e instanceof AttachmentToken?e:new AttachmentToken(e);const r=this.ditto;return r.deferClose((()=>{const e=new AttachmentFetcher(r,n,null,t);return this.attachmentFetchers=Object.freeze([...this.attachmentFetchers,e]),e}))}constructor(e){this.observers=Object.freeze([]),this.attachmentFetchers=Object.freeze([]),this.ditto=e}async registerObserverWebhook(e,t,n){let r=null;if(null!=n)try{const e=desugarJSObject(n);r=CBOR.encode(e)}catch(e){throw new DittoError("query/arguments-invalid",`Invalid query arguments: ${e.message}`)}const i=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{const n=await mapFFIErrorsAsync((async()=>await tryRegisterStoreObserverWebhook(i.deref(),e,r,t)));return new DocumentID(n,!0)}))}unregisterObserver(e){if(e.ditto!==this.ditto)throw new DittoError("internal","Internal inconsistency, can't remove store observer that does not belong to this store");if(!e.isCancelled)throw new DittoError("internal","Internal inconsistency, can't remove store observer that has not been cancelled");const t=this.observers.findIndex((t=>t===e));if(-1===t)return!1;const n=[...this.observers];n.splice(t,1),this.observers=Object.freeze(n);const r=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>{mapFFIErrors((()=>liveQueryStop(r.deref(),e.liveQueryID)))})),!0}removeAttachmentFetcher(e){if(e.ditto!==this.ditto)throw new DittoError("internal","Internal inconsistency, can't finalize attachment fetcher that does not belong to this store");if(null!=e.manager)throw new DittoError("internal","Internal inconsistency, store can't remove attachment fetcher that is owned by the attachment fetcher manager");if(!e.isStopped)throw new DittoError("internal","Internal inconsistency, can't remove attachment fetcher that has not stopped");const t=this.attachmentFetchers.findIndex((t=>t===e));if(-1===t)return!1;const n=[...this.attachmentFetchers];return n.splice(t,1),this.attachmentFetchers=Object.freeze(n),!0}close(){for(const e of this.observers)e.cancel();for(const e of this.attachmentFetchers)e.stop()}async registerLiveQueryWebhook(e,t,n){const r=this.ditto,i=Bridge.ditto.handleFor(r);return r.deferCloseAsync((async()=>{const r=validateQuery(t),o=await liveQueryWebhookRegister(i.deref(),e,r,[],0,0,n);return new DocumentID(o,!0)}))}}function addressToString(e){return`${e.siteId}-${e.pubkey}`}class Presence{get connectionRequestHandler(){return this._connectionRequestHandler}set connectionRequestHandler(e){let t=null;if(null!=e){if("function"!=typeof e)throw new TypeError(`Expected parameter 'handler' to be a function but got ${typeof e} instead`);t=async t=>{const n=Bridge.connectionRequest.bridge(t),r=await e(n);if("allow"!==r&&"deny"!==r)return Logger.error(`The connection request handler must return "allow" or "deny" but returned "${r}" instead. The connection request will be denied.`),"Deny";connectionRequestAuthorize(t,"allow"===r?"Allow":"Deny")}}this._connectionRequestHandler=e;const handleError=e=>{Logger.error(`The connection request handler threw an error while handling a connection request, the connection request will be denied. ${e}`)},n=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{presenceSetConnectionRequestHandler(n.deref(),t,handleError)}))}get graph(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return e.deferClose((()=>{const e=dittoPresenceV3(t.deref());return JSON.parse(e)}))}get peerMetadataJSONString(){const e=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>mapFFIErrors((()=>presencePeerMetadataJSON(e.deref())))))}async setPeerMetadataJSONString(e){const t=Bridge.ditto.handleFor(this.ditto);await this.ditto.deferCloseAsync((async()=>mapFFIErrorsAsync((async()=>presenceTrySetPeerMetadataJSON(t.deref(),e)))))}get peerMetadata(){return JSON.parse(this.peerMetadataJSONString)}async setPeerMetadata(e){let t;try{t=JSON.stringify(e)}catch(e){throw new DittoError("validation/not-json-compatible",`Failed encoding peer metadata to JSON. ${e}`)}await this.setPeerMetadataJSONString(t)}observe(e){const t=this.observerManager.addObserver(e),n=new Observer(this.observerManager,t,{stopsWhenFinalized:!0});return e(this.graph),n}constructor(e){this._connectionRequestHandler=null,this.ditto=e,this.observerManager=new ObserverManager("PresenceObservation",{keepAlive:e.keepAlive,register:e=>{const t=this.ditto,n=Bridge.ditto.handleFor(t);t.deferClose((()=>{dittoRegisterPresenceV3Callback(n.deref(),e)}))},unregister:()=>{const e=this.ditto,t=Bridge.ditto.handleFor(e);e.deferCloseAsync((async()=>dittoClearPresenceV3Callback(t.deref())))},process:e=>[JSON.parse(e)]})}close(){this.observerManager.close()}}class LiveQueryManager{constructor(e,t){this.finalizationRegistry=new FinalizationRegistry(this.finalize),this.ditto=e,this.keepAlive=t,this.liveQueriesByID={}}startLiveQuery(e){const t=this.ditto,n=Bridge.ditto.handleFor(t);this.ditto.deferCloseAsync((async()=>{const r=e.liveQueryID;if(!r)throw new Error("Internal inconsistency, tried to add a live query that doesn't have a live query ID (probably stopped).");if(this.liveQueriesByID[r])throw new Error("Internal inconsistency, tried to add a live query with an ID that has already been added.");const i=new WeakRef(e);return this.liveQueriesByID[r]=i,this.finalizationRegistry.register(e,r,this.finalize),e.liveQueryManager=this,t.keepAlive.retain(`LiveQuery.${r}`),new Promise(((e,t)=>{step((async()=>{await liveQueryStart(n.deref(),r),e()}))}))}))}stopLiveQuery(e){this.finalizationRegistry.unregister(e);const t=e.liveQueryID;if(!t)throw new Error("Internal inconsistency, tried to remove a live query that doesn't have a live query ID (probably stopped).");e.liveQueryManager=null,this.stopLiveQueryWithID(t)}close(){for(const e in this.liveQueriesByID){const t=this.liveQueriesByID[e].deref();t&&this.stopLiveQuery(t)}}stopLiveQueryWithID(e){const t=this.ditto,n=Bridge.ditto.handleFor(t);t.deferClose((()=>{liveQueryStop(n.deref(),e),this.keepAlive.release(`LiveQuery.${e}`),delete this.liveQueriesByID[e]}))}finalize(e){this.stopLiveQueryWithID(e)}}class PresenceManager{constructor(e){this.ditto=e,this.isClosed=!1,this.isRegistered=!1,this.currentRemotePeers=[],this.callbacksByPresenceToken={}}addObserver(e){if(this.isClosed)throw new Error("Internal inconsistency, can't add presence observer, observer mananger close()-ed.");this.registerIfNeeded();const t=generateEphemeralToken();return this.callbacksByPresenceToken[t]=e,this.ditto.keepAlive.retain(`PresenceObservation.${t}`),e(this.currentRemotePeers),t}async removeObserver(e){const t=this.callbacksByPresenceToken[e];if(void 0===t)throw new Error(`Can't remove presence observer, token '${e}' has never been registered before.`);if(null!==t)return void 0!==this.callbacksByPresenceToken[e]?(this.ditto.keepAlive.release(`PresenceObservation.${e}`),this.callbacksByPresenceToken[e]=null,this.unregisterIfNeeded()):void 0}hasObserver(e){return void 0!==this.callbacksByPresenceToken[e]}async close(){this.isClosed=!0;const e=Object.keys(this.callbacksByPresenceToken);return Promise.all(e.map((e=>this.removeObserver(e))))}hasObservers(){return Object.keys(this.callbacksByPresenceToken).length>0}registerIfNeeded(){const e=this.ditto,t=Bridge.ditto.handleFor(this.ditto);e.deferClose((()=>{if(!this.isRegistered){this.isRegistered=!0;const e=dittoPresenceV1(t.deref());this.currentRemotePeers=this.decode(e).sort(this.compareRemotePeers),dittoRegisterPresenceV1Callback(t.deref(),this.handlePresenceV1Callback.bind(this))}}))}unregisterIfNeeded(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return this.ditto.deferCloseAsync((async()=>{!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,await dittoClearPresenceCallback(t.deref()),this.currentRemotePeers=[])}))}handlePresenceV1Callback(e){const t=this.decode(e).sort(this.compareRemotePeers);this.currentRemotePeers=t,this.notify()}notify(){if(!this.isClosed)for(const e in this.callbacksByPresenceToken){const t=this.callbacksByPresenceToken[e];t&&t(this.currentRemotePeers)}}decode(e){return JSON.parse(e).map((e=>{var t,n;return{networkID:e.network_id,deviceName:e.device_name,rssi:null!==(t=e.rssi)&&void 0!==t?t:void 0,approximateDistanceInMeters:null!==(n=e.approximate_distance_in_meters)&&void 0!==n?n:void 0,connections:e.connections}}))}compareRemotePeers(e,t){return 0===e.connections.length&&t.connections.length>0?1:e.connections.length>0&&0===t.connections.length||e.deviceName<t.deviceName?-1:e.deviceName>t.deviceName?1:0}}class TransportConditionsManager extends ObserverManager{constructor(e){super("TransportConditionsObservation",{keepAlive:e.keepAlive}),this.ditto=e}register(e){const t=this.ditto,n=Bridge.ditto.handleFor(t);return t.deferClose((()=>dittoRegisterTransportConditionChangedCallback(n.deref(),e)))}unregister(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return e.deferClose((()=>dittoRegisterTransportConditionChangedCallback(t.deref(),null)))}process(e,t){let n,r;switch(e){case"Bluetooth":n="BLE";break;case"Tcp":n="TCP";break;case"Awdl":n="AWDL";break;case"Mdns":n="MDNS"}switch(t){case"Unknown":r="Unknown";break;case"Ok":r="OK";break;case"GenericFailure":r="GenericFailure";break;case"AppInBackground":r="AppInBackground";break;case"MdnsFailure":r="MDNSFailure";break;case"TcpListenFailure":r="TCPListenFailure";break;case"NoBleCentralPermission":r="NoBLECentralPermission";break;case"NoBlePeripheralPermission":r="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":r="CannotEstablishConnection";break;case"BleDisabled":r="BLEDisabled";break;case"NoBleHardware":r="NoBLEHardware";break;case"WifiDisabled":r="WiFiDisabled";break;case"TemporarilyUnavailable":r="TemporarilyUnavailable"}return[r,n]}}class SyncSubscription{get isCancelled(){return this._isCancelled}cancel(){this._isCancelled||(this._isCancelled=!0,this.ditto.sync.unregisterSubscription(this))}constructor(e,t,n,r){if(this._isCancelled=!1,null==n!=(null==r))throw new DittoError("internal","Internal inconsistency, query arguments and query arguments CBOR must be both null or both non-null",{queryArguments:n,queryArgumentsCBOR:r});this.ditto=e,this.queryString=t,this.queryArguments=n?Object.freeze({...n}):void 0,this.queryArgumentsCBOR=r}}class Sync{registerSubscription(e,t){if("string"!=typeof e)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof e);let n=null;if(null!=t)try{const e=desugarJSObject(t);n=CBOR.encode(e)}catch(e){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${e.message}`)}const r=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{mapFFIErrors((()=>tryAddSyncSubscription(r.deref(),e,n)))}));const i=new SyncSubscription(this.ditto,e,t||null,n);return this.subscriptions=Object.freeze([...this.subscriptions,i]),i}get parameters(){return this.state.underlyingSyncParameters}constructor(e){this.subscriptions=Object.freeze([]),this.bluetoothLETransportPointer=null,this.awdlTransportPointer=null,this.lanTransportPointer=null,this.mdnsClientTransportPointer=null,this.mdnsServerAdvertiserPointer=null;const t={identity:e.identity,transportConfig:new TransportConfig,ditto:e,isWebValid:!1,isX509Valid:!1,isSyncActive:!1};this.ditto=e,this.state=stateFrom(t),transportsInit()}unregisterSubscription(e){if(e.ditto!==this.ditto)throw new DittoError("internal","Can't remove replication subscription that does not belong to this store");if(!e.isCancelled)throw new DittoError("internal","Internal inconsistency, can't remove replication subscription that has not been cancelled");const t=this.subscriptions.findIndex((t=>t===e));if(-1===t)return!1;const n=[...this.subscriptions];n.splice(t,1),this.subscriptions=Object.freeze(n);const r=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>{mapFFIErrors((()=>tryRemoveSyncSubscription(r.deref(),e.queryString,e.queryArgumentsCBOR)))})),!0}update(e){const t=this.state,n=stateFrom(e);this.updatePeerToPeerBluetoothLE(t,n),this.updatePeerToPeerAWDL(t,n),this.updatePeerToPeerLAN(t,n),this.updateListenTCP(t,n),this.updateListenHTTP(t,n),this.updateConnectTCPServers(t,n),this.updateConnectWebsocketURLs(t,n),this.updateGlobal(t,n),this.updateConnectRetryInterval(t,n),this.state=n}close(){if(this.parameters.isSyncActive)throw new Error("Internal inconsistency, can't close sync object while sync is active, please 'stopSync()' first.");for(const e of this.subscriptions)e.cancel()}updatePeerToPeerBluetoothLE(e,t){}updatePeerToPeerAWDL(e,t){}updatePeerToPeerLAN(e,t){}updateListenTCP(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=e.effectiveTransportConfig.listen.tcp,i=t.effectiveTransportConfig.listen.tcp;TransportConfig.areListenTCPsEqual(i,n)||(n.isEnabled&&dittoStopTCPServer(r.deref()),i.isEnabled&&dittoStartTCPServer(r.deref(),`${i.interfaceIP}:${i.port}`))}))}updateListenHTTP(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=e.effectiveTransportConfig.listen.http,i=t.effectiveTransportConfig.listen.http;TransportConfig.areListenHTTPsEqual(n,i)||(n.isEnabled&&dittoStopHTTPServer(r.deref()),i.isEnabled&&dittoStartHTTPServer(r.deref(),`${i.interfaceIP}:${i.port}`,i.staticContentPath||null,i.websocketSync?"Enabled":"Disabled",i.tlsCertificatePath||null,i.tlsKeyPath||null))}))}updateConnectTCPServers(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const e=t.effectiveTransportConfig.connect.tcpServers;dittoSetStaticTCPClients(r.deref(),e)}))}updateConnectWebsocketURLs(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const e=t.effectiveTransportConfig.connect.websocketURLs,n=t.effectiveTransportConfig.global.routingHint;dittoSetStaticWebsocketClients(r.deref(),e,n)}))}updateGlobal(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{e.effectiveTransportConfig.global.syncGroup!==t.effectiveTransportConfig.global.syncGroup&&dittoSetSyncGroup(r.deref(),t.effectiveTransportConfig.global.syncGroup)}))}updateConnectRetryInterval(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{dittoSetConnectRetryInterval(r.deref(),t.effectiveTransportConfig.connect.retryInterval)}))}}function stateFrom(e){var t,n;const r=e.identity,i=e.isSyncActive,o=e.isX509Valid,a=e.isWebValid;let s,c,d=!1;"onlinePlayground"!==r.type&&"onlineWithAuthentication"!==r.type||(s=r.appID,c=null!==(t=r.customDittoCloudURL)&&void 0!==t?t:null,d=null===(n=r.enableDittoCloudSync)||void 0===n||n),validateEnabledTransportsAvailable(e.ditto,e.transportConfig);const l=e.transportConfig.copy();if(i&&o||(l.peerToPeer.bluetoothLE.isEnabled=!1,l.peerToPeer.awdl.isEnabled=!1,l.peerToPeer.lan.isEnabled=!1,l.listen.tcp.isEnabled=!1,l.connect.tcpServers=[]),i&&a||(l.connect.websocketURLs=[]),i||(l.listen.http.isEnabled=!1),i&&a&&d){const e=null!=c?c:defaultDittoCloudURL(s);l.connect.websocketURLs.push(e)}return{underlyingSyncParameters:e,effectiveTransportConfig:l.freeze()}}function validateEnabledTransportsAvailable(e,t){const n=Bridge.ditto.handleFor(e);return e.deferClose((()=>{const e=[],r=transportsBLEIsAvailable(n.deref()),i=transportsAWDLIsAvailable(n.deref()),o=transportsLANIsAvailable(n.deref());if(t.peerToPeer.bluetoothLE.isEnabled&&!r&&e.push("BluetoothLE"),t.peerToPeer.awdl.isEnabled&&!i&&e.push("AWDL"),t.peerToPeer.lan.isEnabled&&!o&&e.push("LAN"),e.length>0)throw new Error(`The following P2P transports are enabled in the transport config but are not supported in the current environment: ${e.join(", ")}`);if(t.connect.tcpServers.length>0&&isWebBuild)throw new Error("The transport config contains TCP servers, but this transport is not supported in web environments");if(t.listen.http.isEnabled&&isWebBuild)throw new Error("The transport config contains an HTTP listener, which is not supported in web environments");if(t.listen.tcp.isEnabled&&isWebBuild)throw new Error("The transport config contains a TCP listener, which is not supported in web environments")}))}class SubscriptionManager{constructor(e){this.ditto=e,this.subscriptions={},this.finalizationRegistry=new FinalizationRegistry(this.removeWithContextInfo.bind(this))}add(e){const t=this.ditto,n=Bridge.ditto.handleFor(t),r=e.contextInfo;t.deferClose((()=>{this.subscriptions[r.id]=new WeakRef(e),this.finalizationRegistry.register(e,e.contextInfo,e),addSubscription(n.deref(),r.collectionName,r.query,r.queryArgsCBOR,r.orderBys,r.limit,r.offset)}))}remove(e){if(null==this.subscriptions[e.contextInfo.id])throw new Error(`Internal inconsistency, tried to remove a subscription that is not tracked: ${e.contextInfo.id}`);this.finalizationRegistry.unregister(e),this.removeWithContextInfo(e.contextInfo)}close(){this.ditto.deferClose((()=>{for(const e in this.subscriptions){const t=this.subscriptions[e].deref();null==t||t.cancel()}}))}removeWithContextInfo(e){const t=this.ditto,n=Bridge.ditto.handleFor(t);t.deferClose((()=>{delete this.subscriptions[e.id],removeSubscription(n.deref(),e.collectionName,e.query,e.queryArgsCBOR,e.orderBys,e.limit,e.offset)}))}}class AttachmentFetcherManager{constructor(e){this.contextInfoByID={},this.finalizationRegistry=new FinalizationRegistry(this.stopWithContextInfo),this.ditto=e}startAttachmentFetcher(e,t){return this.ditto.deferClose((()=>{const n=new AttachmentFetcher(this.ditto,e,this,t),r={id:n.id,attachmentTokenID:e.idBytes,cancelTokenPromise:n.cancelTokenPromise,attachmentFetcher:new WeakRef(n)};this.finalizationRegistry.register(n,r,n),this.contextInfoByID[n.id]=r;const resetCancelToken=()=>{null!=this.contextInfoByID[n.id]&&(this.contextInfoByID[n.id].cancelTokenPromise=null)};return n.attachment.then((e=>(resetCancelToken(),e)),(e=>(resetCancelToken(),e))),this.ditto.keepAlive.retain(`AttachmentFetcher.${n.id})`),n}))}async stopAttachmentFetcher(e){this.finalizationRegistry.unregister(e);const t=this.contextInfoByID[e.id];if(null==t)throw new Error(`Internal inconsistency: cannot stop attachment fetcher ${e.id}, which is not registered.`);await this.stopWithContextInfo(t)}close(){this.ditto.deferCloseAsync((async()=>{const e=Object.values(this.contextInfoByID).map((async e=>{const t=e.attachmentFetcher.deref();null!=t&&await this.stopAttachmentFetcher(t)}));await Promise.all(e)}))}stopWithContextInfo(e){const t=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{if(null==this.contextInfoByID[e.id])throw new Error(`Internal inconsistency: attachment fetcher ${e.id} not found in active attachment fetchers.`);delete this.contextInfoByID[e.id],this.ditto.keepAlive.release(`AttachmentFetcher.${e.id})`);const n=await e.cancelTokenPromise;n&&dittoCancelResolveAttachment(t.deref(),e.attachmentTokenID,n)}))}}class SmallPeerInfo{get isEnabled(){const e=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>dittoSmallPeerInfoGetIsEnabled(e.deref())))}set isEnabled(e){if("boolean"!=typeof e)throw new TypeError("Expected boolean, got "+typeof e);const t=Bridge.ditto.handleFor(this.ditto);this.ditto.deferCloseAsync((async()=>dittoSmallPeerInfoSetEnabled(t.deref(),e)))}get metadata(){return JSON.parse(this.metadataJSONString)}set metadata(e){this.metadataJSONString=JSON.stringify(e)}get metadataJSONString(){const e=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>dittoSmallPeerInfoGetMetadata(e.deref())))}set metadataJSONString(e){if("string"!=typeof e)throw new TypeError("Expected string, got "+typeof e);const t=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{dittoSmallPeerInfoSetMetadata(t.deref(),e)}))}async getSyncScope(){const e=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>dittoSmallPeerInfoGetSyncScope(e.deref())))}async setSyncScope(e){const t=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>dittoSmallPeerInfoSetSyncScope(t.deref(),e)))}constructor(e){this.ditto=e}}const DEFAULT_PERSISTENCE_DIRECTORY="ditto";class Ditto{static get VERSION(){return dittoGetSDKSemver()}get deviceName(){return this._deviceName}set deviceName(e){this.isSyncActive&&Logger.warning("Changes to the device name take effect when sync is restarted."),this._deviceName=e}get sdkVersion(){const e=Bridge.ditto.handleFor(this);return this.deferClose((()=>dittoGetSDKVersion(e.deref())))}get path(){return Logger.warning("⚠️ Deprecation Warning: The 'Ditto.path' property is deprecated. Please update your code to use the new 'Ditto.persistenceDirectory' property instead."),this.persistenceDirectory}get isActivated(){var e;return null!==(e=this._isActivated)&&void 0!==e&&e}get isClosed(){var e;return null!==(e=this._isClosed)&&void 0!==e&&e}get isSyncActive(){var e;return null!==(e=this._isSyncActive)&&void 0!==e&&e}constructor(e,t){if(this.deferCloseAllowed=!0,this.isWebValid=!1,this.isX509Valid=!1,this._isSyncActive=!1,this._isClosed=!1,this.pendingOperations=new Set,!Ditto.isEnvironmentSupported())throw new Error("Ditto does not support this JavaScript environment. Please consult the Ditto JavaScript documentation for a list of supported environments and browsers. You can use `Ditto.isEnvironmentSupported()` to run this check anytime.");this.persistenceDirectory=Ditto.initPersistenceDirectory(t);const n=null!=e?e:{type:"offlinePlayground",appID:""},r=Object.freeze(this.validateIdentity(n));this.identity=Object.freeze(r),this._deviceName=navigator.userAgent,this.keepAlive=new KeepAlive;let i=null;const o=new WeakRef(this),a=(()=>{var e,t,n;if("offlinePlayground"===r.type)return dittoIdentityConfigMakeOfflinePlayground(r.appID,null!==(e=r.siteID)&&void 0!==e?e:0);if("manual"===r.type)return dittoIdentityConfigMakeManual(r.certificate);if("sharedKey"===r.type)return dittoIdentityConfigMakeSharedKey(r.appID,r.sharedKey,r.siteID);if("onlinePlayground"===r.type){const e=null!==(t=r.customAuthURL)&&void 0!==t?t:defaultAuthURL(r.appID);return dittoIdentityConfigMakeOnlinePlayground(r.appID,r.token,e)}if("onlineWithAuthentication"===r.type){const e=null!==(n=r.customAuthURL)&&void 0!==n?n:defaultAuthURL(r.appID);return dittoIdentityConfigMakeOnlineWithAuthentication(r.appID,e)}throw new Error(`Can't create Ditto, unsupported identity type: ${r}`)})(),s=dittoMake(this.persistenceDirectory,a,"Disabled");dittoAuthClientSetValidityListener(s,(function(...e){const t=o.deref();null==t||t.isClosed?Logger.info("Ditto is closed, ignoring auth client validity change"):t.authClientValidityChanged(...e)}));const c=dittoAuthClientIsWebValid(s),d=dittoAuthClientIsX509Valid(s),l=dittoAuthClientGetAppID(s),u=dittoAuthClientGetSiteID(s);if(Bridge.ditto.bridge(s,this),"onlineWithAuthentication"===r.type){this.auth=new OnlineAuthenticator(this.keepAlive,this,r.authHandler);dittoAuthSetLoginProvider(s,dittoAuthClientMakeLoginProvider((function(e){const t=o.deref();t?t.auth?t.auth["@ditto.authenticationExpiring"](e):i=e:Logger.warning("Internal inconsistency, LoginProvider callback fired after the corresponding Ditto instance has been deallocated.")})))}else"onlinePlayground"===r.type?this.auth=new OnlineAuthenticator(this.keepAlive,this,{authenticationRequired:function(e){},authenticationExpiringSoon:function(e,t){}}):this.auth=new NotAvailableAuthenticator(this.keepAlive);const _=this.makeDefaultTransportConfig().freeze();this.appID=l,this.siteID=u,this.isX509Valid=d,this.isWebValid=c,this.sync=new Sync(this),this.sync.update({isSyncActive:!1,isX509Valid:d,isWebValid:c,identity:r,ditto:this,transportConfig:_}),this._isActivated=isWebBuild,this.store=new Store(this),this.smallPeerInfo=new SmallPeerInfo(this),this.presence=new Presence(this),this.presenceManager=new PresenceManager(this),this.liveQueryManager=new LiveQueryManager(this,this.keepAlive),this.attachmentFetcherManager=new AttachmentFetcherManager(this),this.transportConditionsManager=new TransportConditionsManager(this),this.subscriptionManager=new SubscriptionManager(this),null!=i&&this.auth["@ditto.authenticationExpiring"](i)}static disableDeadlockDetection(){}static hasDeadlockDetection(){return!1}static isEnvironmentSupported(){let e,t=!1;"undefined"!=typeof window&&window.navigator&&window.navigator.userAgent&&window.navigator.appVersion&&(t=-1!==window.navigator.userAgent.indexOf("MSIE")||window.navigator.appVersion.indexOf("Trident/")>-1);try{e=checkAPIs()}catch(e){throw new Error(`Error checking environment support: ${e}`)}return!t&&e}static initPersistenceDirectory(e){let t;if(null==e)t="ditto";else{if(0===e.trim().length)throw new Error(`Invalid argument for path parameter: '${e}'`);t=e}return t}setOfflineOnlyLicenseToken(e){Logger.info("Offline license token are ignored on web builds. Token validation will be skipped."),IdentityTypesRequiringOfflineLicenseToken.includes(this.identity.type)?(this._isActivated=!1,mapFFIErrors((()=>tryVerifyLicense(e))),this._isActivated=!0):Logger.error(`The identity type '${this.identity.type}' does not require an offline license token.`)}get transportConfig(){return this.sync.parameters.transportConfig}setTransportConfig(e){const t=e.copy().freeze(),n=this.identity,r=this.isWebValid,i=this.isX509Valid;this.sync.update({transportConfig:t,identity:n,isWebValid:r,isX509Valid:i,isSyncActive:this.isSyncActive,ditto:this});const o=transportConfigToSerializable(t),a=CBOR.encode(o),s=Bridge.ditto.handleFor(this);this.deferClose((()=>{dittoSmallPeerInfoCollectionSetTransportConfigData(s.deref(),a)}))}updateTransportConfig(e){const t=this.transportConfig.copy();return e(t),this.setTransportConfig(t),this}startSync(){this.setSyncActive(!0)}stopSync(){this.setSyncActive(!1)}observePeers(e){Logger.warning("`ditto.observePeers()` is deprecated, please use `ditto.presence.observe()` instead.");const t=this.presenceManager.addObserver(e);return new Observer(this.presenceManager,t,{stopsWhenFinalized:!0})}observeTransportConditions(e){const t=this.transportConditionsManager.addObserver(e);return new Observer(this.transportConditionsManager,t,{stopsWhenFinalized:!0})}runGarbageCollection(){const e=Bridge.ditto.handleFor(this);return this.deferClose((()=>{dittoRunGarbageCollection(e.deref())}))}async disableSyncWithV3(){const e=Bridge.ditto.handleFor(this);return this.deferCloseAsync((async()=>{await dittoDisableSyncWithV3(e.deref())}))}async close(){if(!this.isClosed){if(this._isClosed=!0,this.stopSync(),this.store.close(),this.presence.close(),this.auth.close(),this.sync.close(),await this.presenceManager.close(),this.liveQueryManager.close(),this.attachmentFetcherManager.close(),this.transportConditionsManager.close(),this.subscriptionManager.close(),this.keepAlive.isActive)throw new Error("Internal inconsistency, still kept alive after the Ditto object has been close()-ed. ");do{await Promise.allSettled(this.pendingOperations)}while(this.pendingOperations.size>0);this.deferCloseAllowed=!1,await Bridge.ditto.close(this)}}get numPendingOperations(){return this.pendingOperations.size}deferClose(e){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");return e()}async deferCloseAsync(e){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");const t=e();let n;this.pendingOperations.add(t);try{n=await t}finally{this.pendingOperations.delete(t)}return n}authClientValidityChanged(e,t){const n=this.transportConfig,r=this.identity,i=this.isSyncActive;this.isX509Valid,this.isWebValid,this.isX509Valid=t,this.isWebValid=e,this.auth["@ditto.authClientValidityChanged"](e,t),this.sync.update({transportConfig:n,identity:r,isWebValid:e,isX509Valid:t,isSyncActive:i,ditto:this})}validateIdentity(e){const t={...e},n=e.appID;if(!["offlinePlayground","sharedKey","manual","onlinePlayground","onlineWithAuthentication"].includes(e.type))throw new Error(`Can't create Ditto instance, unknown identity type: ${e.type}`);if(("offlinePlayground"===e.type||"sharedKey"===e.type||"onlinePlayground"===e.type||"onlineWithAuthentication"===e.type)&&void 0===n)throw new Error("Property .appID must be given for identity, but isn't.");if(void 0!==n&&"string"!=typeof n)throw new Error(`Property .appID must be be of type string, but is of type '${typeof n}': ${n}`);if(("offlinePlayground"===e.type||"sharedKey"===e.type)&&void 0!==e.siteID){const t=e.siteID;if(!("number"==typeof t||"bigint"==typeof t))throw new Error("Can't create Ditto instance, siteID must be a number or BigInt");if(t<0)throw new Error("Can't create Ditto instance, siteID must be >= 0");if(t>BigInt("0xffffffffffffffff"))throw new Error("Can't create Ditto instance, siteID must be < 2^64")}if(e.type,e.type,"onlinePlayground"===e.type){const t=e.token;if(void 0===t)throw new Error("Property .token must be given for identity but isn't. You can find the corresponding token on the Ditto Portal.");if(void 0!==t&&"string"!=typeof t)throw new Error(`Property .token of identity must be be of type string, but is of type '${typeof t}': ${t}`)}return e.type,t}setSyncActive(e){const t=Bridge.ditto.handleFor(this);this.deferClose((()=>{if(e&&IdentityTypesRequiringOfflineLicenseToken.includes(this.identity.type)&&!this.isActivated)throw new Error("Sync could not be started because Ditto has not yet been activated. This can be achieved with a successful call to `setOfflineOnlyLicenseToken`. If you need to obtain a license token then please visit https://portal.ditto.live.");!this.isSyncActive&&e&&this.keepAlive.retain("sync"),this.isSyncActive&&!e&&this.keepAlive.release("sync"),this._isSyncActive=e;const n=this.isWebValid,r=this.isX509Valid,i=this.identity,o=this.transportConfig;this._deviceName=dittoSetDeviceName(t.deref(),this.deviceName),this.sync.update({identity:i,transportConfig:o,isWebValid:n,isX509Valid:r,isSyncActive:!!e,ditto:this})}))}makeDefaultTransportConfig(){const e=Bridge.ditto.handleFor(this);return this.deferClose((()=>{const t=new TransportConfig;return transportsBLEIsAvailable(e.deref())&&(t.peerToPeer.bluetoothLE.isEnabled=!0),transportsAWDLIsAvailable(e.deref())&&(t.peerToPeer.awdl.isEnabled=!0),transportsLANIsAvailable(e.deref())&&(t.peerToPeer.lan.isEnabled=!0),t.freeze()}))}}const checkAPIs=e=>{const t=e||globalThis||global||window;return["BigInt","WeakRef","FinalizationRegistry"].every((e=>!!t[e]))},disableDeadlockTimeoutWhenDebugging=()=>{},CUSTOM_INSPECT_SYMBOL=Symbol.for("nodejs.util.inspect.custom");class QueryResultItem{get value(){if(this.materialize(),void 0===this.materializedValue)throw new Error("Internal Error: Materialized value is undefined");return this.materializedValue}get isMaterialized(){return void 0!==this.materializedValue}materialize(){if(!this.isMaterialized){const e=this.cborData();let t;try{t=CBOR.decode(e)}catch(e){throw new Error(`Internal inconsistency: CBOR decoding error while materializing result item: ${e.message}`)}if(void 0===t)throw new Error("Internal inconsistency: Materialized value is undefined");this.materializedValue=t}}dematerialize(){this.materializedValue=void 0}cborData(){return queryResultItemCBOR(Bridge.queryResultItem.handleFor(this).deref())}jsonString(){return queryResultItemJSON(Bridge.queryResultItem.handleFor(this).deref())}[CUSTOM_INSPECT_SYMBOL](e,t,n){return customInspectRepresentation(this,n)}constructor(){}}function getBridgeLoad(){const e={};return Bridge.all.map((t=>{const n=t.deref();return n?0===n.count?null:void(e[n.type.name]=n.count):null})),e}class StaticTCPClient{}class WebsocketClient{}Bridge.attachment.registerType(Attachment),Bridge.connectionRequest.registerType(ConnectionRequest),Bridge.document.registerType(Document),Bridge.queryResultItem.registerType(QueryResultItem),Bridge.queryResult.registerType(QueryResult),Bridge.mutableDocument.registerType(MutableDocument),Bridge.staticTCPClient.registerType(StaticTCPClient),Bridge.websocketClient.registerType(WebsocketClient),Bridge.ditto.registerType(Ditto);export{Attachment,AttachmentFetcher,AttachmentToken,Authenticator,BasePendingCursorOperation,BasePendingIDSpecificOperation,CBOR,Collection,CollectionsEvent,ConnectionRequest,Counter,Ditto,DittoError,Document,DocumentID,DocumentPath,ERROR_CODES,IdentityTypesRequiringOfflineLicenseToken,KeepAlive,LiveQuery,LiveQueryEventInitial,LiveQueryEventUpdate,Logger,MutableCounter,MutableDocument,MutableDocumentPath,MutableRegister,NotAvailableAuthenticator,Observer,OnlineAuthenticator,PendingCollectionsOperation,PendingCursorOperation,PendingIDSpecificOperation,Presence,QueryResult,QueryResultItem,Register,SingleDocumentLiveQueryEvent,SmallPeerInfo,Store,StoreObserver,Subscription,Sync,SyncSubscription,TransportConfig,UpdateResult,UpdateResultsMap,WriteTransaction,WriteTransactionCollection,WriteTransactionPendingCursorOperation,WriteTransactionPendingIDSpecificOperation,addressToString,checkAPIs,disableDeadlockTimeoutWhenDebugging,getBridgeLoad,init,mapFFIErrors,mapFFIErrorsAsync,transportConfigFromDeserializable,transportConfigToSerializable,validateAttachmentMetadata,validateDocumentIDCBOR,validateDocumentIDValue};
|
|
1
|
+
class KeepAlive{get isActive(){return null!==this.intervalID}constructor(){this.countsByID={},this.intervalID=null}retain(e){if(void 0===this.countsByID[e]&&(this.countsByID[e]=0),this.countsByID[e]+=1,null===this.intervalID){const e=2147483647;this.intervalID=setInterval((()=>{}),e),KeepAlive.finalizationRegistry.register(this,this.intervalID,this)}}release(e){if(void 0===this.countsByID[e])throw new Error(`Internal inconsistency, trying to release a keep-alive ID that hasn't been retained before or isn't tracked anymore: ${e}`);this.countsByID[e]-=1,0===this.countsByID[e]&&delete this.countsByID[e],0===Object.keys(this.countsByID).length&&(KeepAlive.finalizationRegistry.unregister(this),clearInterval(this.intervalID),this.intervalID=null)}currentIDs(){return Object.keys(this.countsByID)}countForID(e){var t;return null!==(t=this.countsByID[e])&&void 0!==t?t:null}}KeepAlive.finalizationRegistry=new FinalizationRegistry(clearInterval);class Observer{get token(){return this._token}constructor(e,t,n={}){this.observerManager=e,this._token=t,this.options=n,n.stopsWhenFinalized&&Observer.finalizationRegistry.register(this,{observerManager:e,token:t},this)}get isStopped(){return void 0!==this.token&&this.observerManager.hasObserver(this.token)}stop(){const e=this.token;e&&(delete this._token,Observer.finalizationRegistry.unregister(this),this.observerManager.removeObserver(e))}static finalize(e){const{observerManager:t,token:n}=e;t.removeObserver(n)}}Observer.finalizationRegistry=new FinalizationRegistry(Observer.finalize);const privateToken$1=Symbol("privateConstructorToken");class Counter{get value(){return this._value}constructor(){this._value=0}static"@ditto.create"(e,t,n){const r=e?new MutableCounter(privateToken$1):new Counter;return r.mutDoc=e,r.path=t,r._value=n,r}}class MutableCounter extends Counter{increment(e){const t=this.mutDoc,n=this.path;if(!t)throw new Error("Can't increment counter, only possible within the closure of a collection's update() method.");t.at(n)["@ditto.increment"](e),this._value+=e}constructor(){if(arguments[0]!==privateToken$1)throw new Error("MutableCounter constructor is for internal use only.");super()}}const privateToken="@ditto.ff82dae89821c5ab822a8b539056bce4";class Register{get value(){return this["@ditto.value"]}constructor(e){this["@ditto.value"]=e}static"@ditto.create"(e,t,n){const r=e?new MutableRegister(n,privateToken):new Register(n);return r["@ditto.mutableDocument"]=e,r["@ditto.path"]=t,r["@ditto.value"]=n,r}}class MutableRegister extends Register{get value(){return super.value}set value(e){this.set(e)}set(e){const t=this["@ditto.mutableDocument"],n=this["@ditto.path"];t.at(n)["@ditto.set"](e),this["@ditto.value"]=e}constructor(e){if(arguments[1]!==privateToken)throw new Error("MutableRegister constructor is for internal use only.");super(e)}}function to_string(e){return e.toString()}function is_number(e){return"number"==typeof e}function try_downsize(e){switch(typeof e){case"bigint":if(-Number.MAX_SAFE_INTEGER<=e&&e<=Number.MAX_SAFE_INTEGER)return Number(e);case"number":return e;default:throw new Error(`number or bigint expected, got \`${e}\``)}}function from_string(e){return BigInt(e)}function get_element(e,t){return e[t]}function typeof_(e){return typeof e}function mk_send_ret(){return function send_ret(e){return e}}let wasm;const heap=new Array(128).fill(void 0);function getObject(e){return heap[e]}heap.push(void 0,null,!0,!1);let heap_next=heap.length;function dropObject(e){e<132||(heap[e]=heap_next,heap_next=e)}function takeObject(e){const t=getObject(e);return dropObject(e),t}const cachedTextDecoder="undefined"!=typeof TextDecoder?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};"undefined"!=typeof TextDecoder&&cachedTextDecoder.decode();let cachedUint8Memory0=null;function getUint8Memory0(){return null!==cachedUint8Memory0&&0!==cachedUint8Memory0.byteLength||(cachedUint8Memory0=new Uint8Array(wasm.memory.buffer)),cachedUint8Memory0}function getStringFromWasm0(e,t){return e>>>=0,cachedTextDecoder.decode(getUint8Memory0().subarray(e,e+t))}function addHeapObject(e){heap_next===heap.length&&heap.push(heap.length+1);const t=heap_next;return heap_next=heap[t],heap[t]=e,t}let WASM_VECTOR_LEN=0;const cachedTextEncoder="undefined"!=typeof TextEncoder?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},encodeString="function"==typeof cachedTextEncoder.encodeInto?function(e,t){return cachedTextEncoder.encodeInto(e,t)}:function(e,t){const n=cachedTextEncoder.encode(e);return t.set(n),{read:e.length,written:n.length}};function passStringToWasm0(e,t,n){if(void 0===n){const n=cachedTextEncoder.encode(e),r=t(n.length,1)>>>0;return getUint8Memory0().subarray(r,r+n.length).set(n),WASM_VECTOR_LEN=n.length,r}let r=e.length,i=t(r,1)>>>0;const o=getUint8Memory0();let a=0;for(;a<r;a++){const t=e.charCodeAt(a);if(t>127)break;o[i+a]=t}if(a!==r){0!==a&&(e=e.slice(a)),i=n(i,r,r=a+3*e.length,1)>>>0;const t=getUint8Memory0().subarray(i+a,i+r);a+=encodeString(e,t).written}return WASM_VECTOR_LEN=a,i}function isLikeNone(e){return null==e}let cachedInt32Memory0=null;function getInt32Memory0(){return null!==cachedInt32Memory0&&0!==cachedInt32Memory0.byteLength||(cachedInt32Memory0=new Int32Array(wasm.memory.buffer)),cachedInt32Memory0}function debugString(e){const t=typeof e;if("number"==t||"boolean"==t||null==e)return`${e}`;if("string"==t)return`"${e}"`;if("symbol"==t){const t=e.description;return null==t?"Symbol":`Symbol(${t})`}if("function"==t){const t=e.name;return"string"==typeof t&&t.length>0?`Function(${t})`:"Function"}if(Array.isArray(e)){const t=e.length;let n="[";t>0&&(n+=debugString(e[0]));for(let r=1;r<t;r++)n+=", "+debugString(e[r]);return n+="]",n}const n=/\[object ([^\]]+)\]/.exec(toString.call(e));let r;if(!(n.length>1))return toString.call(e);if(r=n[1],"Object"==r)try{return"Object("+JSON.stringify(e)+")"}catch(e){return"Object"}return e instanceof Error?`${e.name}: ${e.message}\n${e.stack}`:r}const CLOSURE_DTORS=new FinalizationRegistry((e=>{wasm.__wbindgen_export_2.get(e.dtor)(e.a,e.b)}));function makeMutClosure(e,t,n,r){const i={a:e,b:t,cnt:1,dtor:n},real=(...e)=>{i.cnt++;const t=i.a;i.a=0;try{return r(t,i.b,...e)}finally{0==--i.cnt?(wasm.__wbindgen_export_2.get(i.dtor)(t,i.b),CLOSURE_DTORS.unregister(i)):i.a=t}};return real.original=i,CLOSURE_DTORS.register(real,i,i),real}function __wbg_adapter_32(e,t){wasm.wasm_bindgen__convert__closures__invoke0_mut__h1f7940e5f97415e0(e,t)}function __wbg_adapter_35(e,t,n){wasm.wasm_bindgen__convert__closures__invoke1_mut__hd6b052899a77fab8(e,t,addHeapObject(n))}function __wbg_adapter_38(e,t,n){wasm.wasm_bindgen__convert__closures__invoke1_mut__h26969dfdcbb658aa(e,t,addHeapObject(n))}function __wbg_adapter_41(e,t){wasm.wasm_bindgen__convert__closures__invoke0_mut__h7bd4c67ecefe53ea(e,t)}function __wbg_adapter_44(e,t,n){wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hcdb08c50a53c7d7a(e,t,addHeapObject(n))}function dittoffi_try_base64_decode(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_base64_decode(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_base64_encode(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_base64_encode(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_remove_sync_subscription(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_remove_sync_subscription(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_add_sync_subscription(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_add_sync_subscription(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_add_subscription(e,t,n,r,i,o,a){try{const d=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_add_subscription(d,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a));var s=getInt32Memory0()[d/4+0],c=getInt32Memory0()[d/4+1];if(getInt32Memory0()[d/4+2])throw takeObject(c);return takeObject(s)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_remove_subscription(e,t,n,r,i,o,a){try{const d=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_remove_subscription(d,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a));var s=getInt32Memory0()[d/4+0],c=getInt32Memory0()[d/4+1];if(getInt32Memory0()[d/4+2])throw takeObject(c);return takeObject(s)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_signal_available_next(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_signal_available_next(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_stop(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_stop(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_register_store_observer_webhook(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_register_store_observer_webhook(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_start(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_start(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_register_str_detached(e,t,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_register_str_detached(l,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_experimental_register_change_observer_str_detached(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_experimental_register_change_observer_str_detached(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_webhook_register_str(e,t,n,r,i,o,a){try{const d=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_webhook_register_str(d,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a));var s=getInt32Memory0()[d/4+0],c=getInt32Memory0()[d/4+1];if(getInt32Memory0()[d/4+2])throw takeObject(c);return takeObject(s)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_get_sync_scope(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_get_sync_scope(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_sync_scope(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_sync_scope(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_get_is_enabled(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_get_is_enabled(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_enabled(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_enabled(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_get_metadata(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_get_metadata(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_metadata(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_metadata(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_transport_config_data(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_transport_config_data(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_logout(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_logout(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_connection_request_authorize(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_connection_request_authorize(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_connection_request_connection_type(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_connection_request_connection_type(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_connection_request_peer_key_string(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_connection_request_peer_key_string(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_connection_request_identity_service_metadata_json(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_connection_request_identity_service_metadata_json(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_connection_request_peer_metadata_json(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_connection_request_peer_metadata_json(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_connection_request_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_connection_request_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_presence_peer_metadata_json(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_presence_peer_metadata_json(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_presence_try_set_peer_metadata_json(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_presence_try_set_peer_metadata_json(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_login_with_credentials(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_login_with_credentials(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_login_with_token(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_login_with_token(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_is_x509_valid(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_is_x509_valid(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_is_web_valid(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_is_web_valid(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_user_id(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_user_id(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_get_app_id(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_get_app_id(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_get_site_id(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_get_site_id(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_set_login_provider(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_set_login_provider(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_manual_v0(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_manual_v0(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_shared_key(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_shared_key(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_offline_playground(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_offline_playground(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_online_playground(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_online_playground(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_online_with_authentication(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_online_with_authentication(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_presence_set_connection_request_handler(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_presence_set_connection_request_handler(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_make_login_provider(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_login_provider(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_set_validity_listener(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_set_validity_listener(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_validate_document_id(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_validate_document_id(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_id_query_compatible(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_id_query_compatible(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_error_message(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_error_message(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_log(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_log(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_minimum_log_level_get(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_minimum_log_level_get(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_minimum_log_level(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_minimum_log_level(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_emoji_headings_enabled_get(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_emoji_headings_enabled_get(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_emoji_headings_enabled(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_emoji_headings_enabled(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_enabled_get(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_enabled_get(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_enabled(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_enabled(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_init(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_init(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_set_log_file(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_set_log_file(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_set_custom_log_cb(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_set_custom_log_cb(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_init_sdk_version(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_init_sdk_version(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_get_sdk_semver(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_get_sdk_semver(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_get_sdk_version(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_sdk_version(n);var e=getInt32Memory0()[n/4+0],t=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(t);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_disable_sync_with_v3(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_disable_sync_with_v3(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_run_garbage_collection(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_run_garbage_collection(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_sync_group(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_sync_group(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_connect_retry_interval(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_connect_retry_interval(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_device_name(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_device_name(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_presence_v3(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_presence_v3(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_presence_v1(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_presence_v1(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_clear_presence_v3_callback(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_clear_presence_v3_callback(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_clear_presence_callback(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_clear_presence_callback(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_shutdown(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_shutdown(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_make(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_make(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_static_websocket_clients(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_static_websocket_clients(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_transport_condition_changed_callback(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_transport_condition_changed_callback(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_verify_license(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_verify_license(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_presence_v1_callback(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_presence_v1_callback(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_presence_v3_callback(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_presence_v3_callback(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_get_cbor_with_path_type(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_get_cbor_with_path_type(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_remove(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_remove(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_set_cbor_with_timestamp(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_set_cbor_with_timestamp(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_set_cbor(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_set_cbor(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_increment_counter(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_increment_counter(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_id(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_id(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_cancel_resolve_attachment(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_cancel_resolve_attachment(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_free_attachment_handle(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_free_attachment_handle(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_get_complete_attachment_data(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_complete_attachment_data(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_new_attachment_from_bytes(e,t,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_new_attachment_from_bytes(o,addHeapObject(e),addHeapObject(t),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_resolve_attachment(e,t,n,r,i){try{const s=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_resolve_attachment(s,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_error_description(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_error_description(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_error_code(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_error_code(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_error_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_error_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_write_transaction_rollback(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction_rollback(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_write_transaction_commit(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction_commit(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_write_transaction(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_read_transaction_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_read_transaction_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_read_transaction(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_read_transaction(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_exec_statement(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_exec_statement(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_get(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_get(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_remove(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_remove(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_evict(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_evict(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_update_multiple(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_update_multiple(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_update(e,t,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_update(a,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_insert_value(e,t,n,r,i,o){try{const c=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_insert_value(c,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o));var a=getInt32Memory0()[c/4+0],s=getInt32Memory0()[c/4+1];if(getInt32Memory0()[c/4+2])throw takeObject(s);return takeObject(a)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_get_collection_names(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_collection_names(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_documents_hash(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_documents_hash(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_documents_hash_mnemonic(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_documents_hash_mnemonic(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_evict_query_str(e,t,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_evict_query_str(l,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_remove_query_str(e,t,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_remove_query_str(l,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_exec_query_str(e,t,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_exec_query_str(l,addHeapObject(e),addHeapObject(t),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function jsDocsToCDocs(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.jsDocsToCDocs(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function websocket_client_free_handle(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.websocket_client_free_handle(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_mutated_document_id_at(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_mutated_document_id_at(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_mutated_document_id_count(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_mutated_document_id_count(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_item_at(e,t){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_item_at(i,addHeapObject(e),addHeapObject(t));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_item_count(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_item_count(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_item_free(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_item_free(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_item_json(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_item_json(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_query_result_item_cbor(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_query_result_item_cbor(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function handleError(e,t){try{return e.apply(this,t)}catch(e){wasm.__wbindgen_exn_store(addHeapObject(e))}}function notDefined(e){return()=>{throw new Error(`${e} is not defined`)}}function getArrayU8FromWasm0(e,t){return e>>>=0,getUint8Memory0().subarray(e/1,e/1+t)}function __wbg_adapter_393(e,t,n,r){wasm.wasm_bindgen__convert__closures__invoke2_mut__h4a79cbbfae79c36f(e,t,addHeapObject(n),addHeapObject(r))}function boxCStringIntoString(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.boxCStringIntoString(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function refCStringToString(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.refCStringToString(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function boxCBytesIntoBuffer(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.boxCBytesIntoBuffer(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function refCBytesIntoBuffer(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.refCBytesIntoBuffer(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function withOutBoxCBytes(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.withOutBoxCBytes(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function cStringVecToStringArray(e){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.cStringVecToStringArray(r,addHeapObject(e));var t=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}async function __wbg_load(e,t){if("function"==typeof Response&&e instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if("application/wasm"==e.headers.get("Content-Type"))throw t;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",t)}const n=await e.arrayBuffer();return await WebAssembly.instantiate(n,t)}{const n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}}function __wbg_get_imports(){const e={wbg:{}};return e.wbg.__wbindgen_object_drop_ref=function(e){takeObject(e)},e.wbg.__wbindgen_cb_drop=function(e){const t=takeObject(e).original;if(1==t.cnt--)return t.a=0,!0;return!1},e.wbg.__wbindgen_string_new=function(e,t){return addHeapObject(getStringFromWasm0(e,t))},e.wbg.__wbg_log_f7c904296a5a8ff0=function(e,t){let n,r;try{n=e,r=t,console.log(getStringFromWasm0(e,t))}finally{wasm.__wbindgen_free(n,r,1)}},e.wbg.__wbg_new_abda76e883ba8a5f=function(){return addHeapObject(new Error)},e.wbg.__wbg_stack_658279fe44541cf6=function(e,t){const n=passStringToWasm0(getObject(t).stack,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbg_error_f851667af71bcfc6=function(e,t){let n,r;try{n=e,r=t,console.error(getStringFromWasm0(e,t))}finally{wasm.__wbindgen_free(n,r,1)}},e.wbg.__wbindgen_is_string=function(e){return"string"==typeof getObject(e)},e.wbg.__wbindgen_string_get=function(e,t){const n=getObject(t),r="string"==typeof n?n:void 0;var i=isLikeNone(r)?0:passStringToWasm0(r,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),o=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=o,getInt32Memory0()[e/4+0]=i},e.wbg.__wbg_fetch_6a2624d7f767e331=function(e){return addHeapObject(fetch(getObject(e)))},e.wbg.__wbindgen_object_clone_ref=function(e){return addHeapObject(getObject(e))},e.wbg.__wbg_clearTimeout_23ee6db72c0ad922="function"==typeof clearTimeout?clearTimeout:notDefined("clearTimeout"),e.wbg.__wbg_setTimeout_09074a1669d0f224=function(){return handleError((function(e,t){return setTimeout(getObject(e),t)}),arguments)},e.wbg.__wbg_clearInterval_d5655e407a861314="function"==typeof clearInterval?clearInterval:notDefined("clearInterval"),e.wbg.__wbg_setInterval_fa82463ae3f43f48=function(){return handleError((function(e,t){return setInterval(getObject(e),t)}),arguments)},e.wbg.__wbindgen_number_new=function(e){return addHeapObject(e)},e.wbg.__wbg_crypto_58f13aa23ffcb166=function(e){return addHeapObject(getObject(e).crypto)},e.wbg.__wbindgen_is_object=function(e){const t=getObject(e);return"object"==typeof t&&null!==t},e.wbg.__wbg_process_5b786e71d465a513=function(e){return addHeapObject(getObject(e).process)},e.wbg.__wbg_versions_c2ab80650590b6a2=function(e){return addHeapObject(getObject(e).versions)},e.wbg.__wbg_node_523d7bd03ef69fba=function(e){return addHeapObject(getObject(e).node)},e.wbg.__wbg_msCrypto_abcb1295e768d1f2=function(e){return addHeapObject(getObject(e).msCrypto)},e.wbg.__wbg_require_2784e593a4674877=function(){return handleError((function(){return addHeapObject(module.require)}),arguments)},e.wbg.__wbindgen_is_function=function(e){return"function"==typeof getObject(e)},e.wbg.__wbg_randomFillSync_a0d98aa11c81fe89=function(){return handleError((function(e,t){getObject(e).randomFillSync(takeObject(t))}),arguments)},e.wbg.__wbg_getRandomValues_504510b5564925af=function(){return handleError((function(e,t){getObject(e).getRandomValues(getObject(t))}),arguments)},e.wbg.__wbg_mksendret_2fbc0bd0b52dee17=function(){return addHeapObject(mk_send_ret())},e.wbg.__wbg_trydownsize_28e49b8073c2a2fc=function(e){return addHeapObject(try_downsize(takeObject(e)))},e.wbg.__wbg_isnumber_c97122a46d4ace09=function(e){return is_number(getObject(e))},e.wbg.__wbg_tostring_7847f1b7af649ba5=function(e,t){const n=passStringToWasm0(to_string(getObject(t)),wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbindgen_error_new=function(e,t){return addHeapObject(new Error(getStringFromWasm0(e,t)))},e.wbg.__wbg_fromstring_721719aff319c1fe=function(e,t){return addHeapObject(from_string(getStringFromWasm0(e,t)))},e.wbg.__wbg_typeof_cb5c1bc26a697ea8=function(e,t){const n=passStringToWasm0(typeof_(getObject(t)),wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbindgen_is_null=function(e){return null===getObject(e)},e.wbg.__wbindgen_is_undefined=function(e){return void 0===getObject(e)},e.wbg.__wbg_getelement_cd48f1e89008c242=function(e,t){return addHeapObject(get_element(getObject(e),t>>>0))},e.wbg.__wbg_fetch_749a56934f95c96c=function(e,t){return addHeapObject(getObject(e).fetch(getObject(t)))},e.wbg.__wbg_now_8172cd917e5eda6b=function(e){return getObject(e).now()},e.wbg.__wbg_new_39f0e6d61fc67f0e=function(){return handleError((function(){return addHeapObject(new FormData)}),arguments)},e.wbg.__wbg_append_1b70fd81d162ab50=function(){return handleError((function(e,t,n,r){getObject(e).append(getStringFromWasm0(t,n),getObject(r))}),arguments)},e.wbg.__wbg_append_32853c33a2dd22f0=function(){return handleError((function(e,t,n,r,i,o){getObject(e).append(getStringFromWasm0(t,n),getObject(r),getStringFromWasm0(i,o))}),arguments)},e.wbg.__wbg_new_2d0053ee81e4dd2a=function(){return handleError((function(){return addHeapObject(new Headers)}),arguments)},e.wbg.__wbg_append_de37df908812970d=function(){return handleError((function(e,t,n,r,i){getObject(e).append(getStringFromWasm0(t,n),getStringFromWasm0(r,i))}),arguments)},e.wbg.__wbg_url_1f1b597f64482fd0=function(e,t){const n=passStringToWasm0(getObject(t).url,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbg_readyState_9c0f66433e329c9e=function(e){return getObject(e).readyState},e.wbg.__wbg_setonopen_9ce48dce57e549b5=function(e,t){getObject(e).onopen=getObject(t)},e.wbg.__wbg_setonerror_02393260b3e29972=function(e,t){getObject(e).onerror=getObject(t)},e.wbg.__wbg_setonclose_4ce49fd8fd7783fb=function(e,t){getObject(e).onclose=getObject(t)},e.wbg.__wbg_setonmessage_c5a806b62a0c5607=function(e,t){getObject(e).onmessage=getObject(t)},e.wbg.__wbg_setbinaryType_ee55743ddf4beb37=function(e,t){getObject(e).binaryType=takeObject(t)},e.wbg.__wbg_new_d29e507f6606de91=function(){return handleError((function(e,t){return addHeapObject(new WebSocket(getStringFromWasm0(e,t)))}),arguments)},e.wbg.__wbg_newwithstrsequence_7b0c4aadc1ae1635=function(){return handleError((function(e,t,n){return addHeapObject(new WebSocket(getStringFromWasm0(e,t),getObject(n)))}),arguments)},e.wbg.__wbg_close_45d053bea59e7746=function(){return handleError((function(e){getObject(e).close()}),arguments)},e.wbg.__wbg_send_80b256d87a6779e5=function(){return handleError((function(e,t,n){getObject(e).send(getStringFromWasm0(t,n))}),arguments)},e.wbg.__wbg_send_640853f8eb0f0385=function(){return handleError((function(e,t,n){getObject(e).send(getArrayU8FromWasm0(t,n))}),arguments)},e.wbg.__wbg_instanceof_Blob_d18d26355bccfd22=function(e){let t;try{t=getObject(e)instanceof Blob}catch{t=!1}return t},e.wbg.__wbg_newwithu8arraysequenceandoptions_b0ee96dd3232b69c=function(){return handleError((function(e,t){return addHeapObject(new Blob(getObject(e),getObject(t)))}),arguments)},e.wbg.__wbg_signal_31753ac644b25fbb=function(e){return addHeapObject(getObject(e).signal)},e.wbg.__wbg_new_6396e586b56e1dff=function(){return handleError((function(){return addHeapObject(new AbortController)}),arguments)},e.wbg.__wbg_abort_064ae59cda5cd244=function(e){getObject(e).abort()},e.wbg.__wbg_instanceof_Response_eaa426220848a39e=function(e){let t;try{t=getObject(e)instanceof Response}catch{t=!1}return t},e.wbg.__wbg_url_74285ddf2747cb3d=function(e,t){const n=passStringToWasm0(getObject(t).url,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbg_status_c4ef3dd591e63435=function(e){return getObject(e).status},e.wbg.__wbg_headers_fd64ad685cf22e5d=function(e){return addHeapObject(getObject(e).headers)},e.wbg.__wbg_arrayBuffer_4c27b6f00c530232=function(){return handleError((function(e){return addHeapObject(getObject(e).arrayBuffer())}),arguments)},e.wbg.__wbg_wasClean_2af04e6cf2076497=function(e){return getObject(e).wasClean},e.wbg.__wbg_code_24e161f043adce8a=function(e){return getObject(e).code},e.wbg.__wbg_reason_40159cc3d2fc655d=function(e,t){const n=passStringToWasm0(getObject(t).reason,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbg_code_b09504754e0520f1=function(e){return getObject(e).code},e.wbg.__wbg_data_7b1f01f4e6a64fbe=function(e){return addHeapObject(getObject(e).data)},e.wbg.__wbg_newwithstrandinit_05d7180788420c40=function(){return handleError((function(e,t,n){return addHeapObject(new Request(getStringFromWasm0(e,t),getObject(n)))}),arguments)},e.wbg.__wbg_new_898a68150f225f2e=function(){return addHeapObject(new Array)},e.wbg.__wbg_valueOf_e39b017d2100ede0=function(e){return getObject(e).valueOf()},e.wbg.__wbg_newnoargs_581967eacc0e2604=function(e,t){return addHeapObject(new Function(getStringFromWasm0(e,t)))},e.wbg.__wbg_next_526fc47e980da008=function(e){return addHeapObject(getObject(e).next)},e.wbg.__wbg_next_ddb3312ca1c4e32a=function(){return handleError((function(e){return addHeapObject(getObject(e).next())}),arguments)},e.wbg.__wbg_done_5c1f01fb660d73b5=function(e){return getObject(e).done},e.wbg.__wbg_value_1695675138684bd5=function(e){return addHeapObject(getObject(e).value)},e.wbg.__wbg_iterator_97f0c81209c6c35a=function(){return addHeapObject(Symbol.iterator)},e.wbg.__wbg_get_97b561fb56f034b5=function(){return handleError((function(e,t){return addHeapObject(Reflect.get(getObject(e),getObject(t)))}),arguments)},e.wbg.__wbg_call_cb65541d95d71282=function(){return handleError((function(e,t){return addHeapObject(getObject(e).call(getObject(t)))}),arguments)},e.wbg.__wbg_new_b51585de1b234aff=function(){return addHeapObject(new Object)},e.wbg.__wbg_self_1ff1d729e9aae938=function(){return handleError((function(){return addHeapObject(self.self)}),arguments)},e.wbg.__wbg_window_5f4faef6c12b79ec=function(){return handleError((function(){return addHeapObject(window.window)}),arguments)},e.wbg.__wbg_globalThis_1d39714405582d3c=function(){return handleError((function(){return addHeapObject(globalThis.globalThis)}),arguments)},e.wbg.__wbg_global_651f05c6a0944d1c=function(){return handleError((function(){return addHeapObject(global.global)}),arguments)},e.wbg.__wbg_push_ca1c26067ef907ac=function(e,t){return getObject(e).push(getObject(t))},e.wbg.__wbg_instanceof_ArrayBuffer_39ac22089b74fddb=function(e){let t;try{t=getObject(e)instanceof ArrayBuffer}catch{t=!1}return t},e.wbg.__wbg_apply_64be369596a02ae0=function(){return handleError((function(e,t,n){return addHeapObject(getObject(e).apply(getObject(t),getObject(n)))}),arguments)},e.wbg.__wbg_call_01734de55d61e11d=function(){return handleError((function(e,t,n){return addHeapObject(getObject(e).call(getObject(t),getObject(n)))}),arguments)},e.wbg.__wbg_valueOf_7d8df3cd4f3f583b=function(e){return getObject(e).valueOf()},e.wbg.__wbg_getTime_5e2054f832d82ec9=function(e){return getObject(e).getTime()},e.wbg.__wbg_new0_c0be7df4b6bd481f=function(){return addHeapObject(new Date)},e.wbg.__wbg_now_9c5990bda04c7e53=function(){return Date.now()},e.wbg.__wbg_instanceof_Object_3daa8298c86298be=function(e){let t;try{t=getObject(e)instanceof Object}catch{t=!1}return t},e.wbg.__wbg_new_43f1b47c28813cbd=function(e,t){try{var n={a:e,b:t};const r=new Promise(((e,t)=>{const r=n.a;n.a=0;try{return __wbg_adapter_393(r,n.b,e,t)}finally{n.a=r}}));return addHeapObject(r)}finally{n.a=n.b=0}},e.wbg.__wbg_resolve_53698b95aaf7fcf8=function(e){return addHeapObject(Promise.resolve(getObject(e)))},e.wbg.__wbg_then_f7e06ee3c11698eb=function(e,t){return addHeapObject(getObject(e).then(getObject(t)))},e.wbg.__wbg_then_b2267541e2a73865=function(e,t,n){return addHeapObject(getObject(e).then(getObject(t),getObject(n)))},e.wbg.__wbg_buffer_085ec1f694018c4f=function(e){return addHeapObject(getObject(e).buffer)},e.wbg.__wbg_newwithbyteoffsetandlength_6da8e527659b86aa=function(e,t,n){return addHeapObject(new Uint8Array(getObject(e),t>>>0,n>>>0))},e.wbg.__wbg_new_8125e318e6245eed=function(e){return addHeapObject(new Uint8Array(getObject(e)))},e.wbg.__wbg_set_5cf90238115182c3=function(e,t,n){getObject(e).set(getObject(t),n>>>0)},e.wbg.__wbg_length_72e2208bbc0efc61=function(e){return getObject(e).length},e.wbg.__wbg_instanceof_Uint8Array_d8d9cb2b8e8ac1d4=function(e){let t;try{t=getObject(e)instanceof Uint8Array}catch{t=!1}return t},e.wbg.__wbg_newwithlength_e5d69174d6984cd7=function(e){return addHeapObject(new Uint8Array(e>>>0))},e.wbg.__wbg_subarray_13db269f57aa838d=function(e,t,n){return addHeapObject(getObject(e).subarray(t>>>0,n>>>0))},e.wbg.__wbg_stringify_e25465938f3f611f=function(){return handleError((function(e){return addHeapObject(JSON.stringify(getObject(e)))}),arguments)},e.wbg.__wbg_has_c5fcd020291e56b8=function(){return handleError((function(e,t){return Reflect.has(getObject(e),getObject(t))}),arguments)},e.wbg.__wbg_set_092e06b0f9d71865=function(){return handleError((function(e,t,n){return Reflect.set(getObject(e),getObject(t),getObject(n))}),arguments)},e.wbg.__wbindgen_debug_string=function(e,t){const n=passStringToWasm0(debugString(getObject(t)),wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[e/4+1]=r,getInt32Memory0()[e/4+0]=n},e.wbg.__wbindgen_throw=function(e,t){throw new Error(getStringFromWasm0(e,t))},e.wbg.__wbindgen_memory=function(){return addHeapObject(wasm.memory)},e.wbg.__wbindgen_closure_wrapper9906=function(e,t,n){return addHeapObject(makeMutClosure(e,t,2679,__wbg_adapter_32))},e.wbg.__wbindgen_closure_wrapper9908=function(e,t,n){return addHeapObject(makeMutClosure(e,t,2679,__wbg_adapter_35))},e.wbg.__wbindgen_closure_wrapper18686=function(e,t,n){return addHeapObject(makeMutClosure(e,t,5116,__wbg_adapter_38))},e.wbg.__wbindgen_closure_wrapper24385=function(e,t,n){return addHeapObject(makeMutClosure(e,t,7123,__wbg_adapter_41))},e.wbg.__wbindgen_closure_wrapper26027=function(e,t,n){return addHeapObject(makeMutClosure(e,t,7609,__wbg_adapter_44))},e}function __wbg_finalize_init(e,t){return wasm=e.exports,init$2.__wbindgen_wasm_module=t,cachedInt32Memory0=null,cachedUint8Memory0=null,wasm}async function init$2(e){if(void 0!==wasm)return wasm;if(void 0===e)throw new Error("Can't load ditto.wasm, expected module to be provided at initialization time but got nothing.");const t=__wbg_get_imports();("string"==typeof e||"function"==typeof Request&&e instanceof Request||"function"==typeof URL&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await __wbg_load(await e,t);return __wbg_finalize_init(n,r)}const isWebBuild=!0,PREFIX_REGEX=new RegExp(/^<.*?>\s*/);class DittoFFIError extends Error{constructor(e,t,n){const r=ffiErrorMessage();super(t||r||n),this.code=e}}function throwOnErrorResult(e,t){if(null!==e){let n,r;try{n=dittoffi_error_code(e),r=boxCStringIntoString(dittoffi_error_description(e)),dittoffi_error_free(e)}catch(e){throw new DittoFFIError(-1,`Failed to retrieve Ditto core error message: ${e.message}`)}throw r=null==r?`${t}() failed with error code: ${n}`:r.replace(PREFIX_REGEX,""),new DittoFFIError(n,r)}}function ffiErrorMessage(){return boxCStringIntoString(ditto_error_message())}const DittoCRDTTypeKey="_ditto_internal_type_jkb12973t4b",DittoCRDTValueKey="_value";var DittoCRDTType;function documentSetCBORWithTimestamp(e,t,n,r){ensureInitialized();const i=ditto_document_set_cbor_with_timestamp(e,bytesFromString(t),n,r);if(0!==i)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${i}`)}function documentSetCBOR(e,t,n){ensureInitialized();const r=ditto_document_set_cbor(e,bytesFromString(t),n);if(0!==r)throw new Error(errorMessage()||`ditto_document_set_cbor() failed with error code: ${r}`)}function documentID(e){ensureInitialized();return boxCBytesIntoBuffer(ditto_document_id(e))}function documentGetCBORWithPathType(e,t,n){ensureInitialized();const r=ditto_document_get_cbor_with_path_type(e,bytesFromString(t),n);return{statusCode:r.status_code,cbor:boxCBytesIntoBuffer(r.cbor)}}function documentRemove(e,t){ensureInitialized();const n=ditto_document_remove(e,bytesFromString(t));if(0!==n)throw new Error(errorMessage()||`ditto_document_remove() failed with error code: ${n}`)}function documentIncrementCounter(e,t,n){ensureInitialized();const r=ditto_document_increment_counter(e,bytesFromString(t),n);if(0!==r)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${r}`)}function documentFree(e){ensureInitialized(),ditto_document_free(e)}function documentIDQueryCompatible(e,t){ensureInitialized();return boxCStringIntoString(ditto_document_id_query_compatible(e,t))}function validateDocumentID(e){ensureInitialized();return boxCBytesIntoBuffer(withOutBoxCBytes((t=>{const n=ditto_validate_document_id(e,t);if(0!==n)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${n}`);return t})))}async function collectionGet(e,t,n,r){ensureInitialized();const i=bytesFromString(t),{status_code:o,document:a}=await ditto_collection_get(e,i,n,r);if(o===NOT_FOUND_ERROR_CODE)return null;if(0!==o)throw new Error(errorMessage()||`ditto_collection_get() failed with error code: ${o}`);return a}async function collectionInsertValue(e,t,n,r,i){ensureInitialized();const o=bytesFromString(t);let a;switch(r){case"merge":a="Merge";break;case"insertIfAbsent":a="InsertIfAbsent";break;case"insertDefaultIfAbsent":a="InsertDefaultIfAbsent";break;case"updateDifferentValues":a="UpdateDifferentValues";break;default:throw new Error(`Unsupported write strategy '${r}' provided.`)}const{status_code:s,id:c}=await ditto_collection_insert_value(e,o,n,a,null,null!=i?i:null);if(0!==s)throw new Error(errorMessage()||`ditto_collection_insert_value() failed with error code: ${s}`);return boxCBytesIntoBuffer(c)}async function collectionRemove(e,t,n,r){ensureInitialized();const i=bytesFromString(t),{status_code:o,bool_value:a}=await ditto_collection_remove(e,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${o}`);return a}async function collectionEvict(e,t,n,r){ensureInitialized();const i=bytesFromString(t),{status_code:o,bool_value:a}=await ditto_collection_evict(e,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${o}`);return a}async function collectionUpdate(e,t,n,r){ensureInitialized();const i=bytesFromString(t),o=await ditto_collection_update(e,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${o}`)}async function collectionUpdateMultiple(e,t,n,r){ensureInitialized();const i=bytesFromString(t),o=jsDocsToCDocs(r),a=await ditto_collection_update_multiple(e,i,n,o);if(0!==a)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${a}`)}async function collectionExecQueryStr(e,t,n,r,i,o,a,s){ensureInitialized();const c=bytesFromString(t),d=bytesFromString(r);return await ditto_collection_exec_query_str(e,c,n,d,i,o,a,s)}async function collectionRemoveQueryStr(e,t,n,r,i,o,a,s){ensureInitialized();const c=bytesFromString(t),d=bytesFromString(r);return await ditto_collection_remove_query_str(e,c,n,d,i,o,a,s)}async function collectionEvictQueryStr(e,t,n,r,i,o,a,s){ensureInitialized();const c=bytesFromString(t),d=bytesFromString(r);return await ditto_collection_evict_query_str(e,c,n,d,i,o,a,s)}async function tryExecStatement(e,t,n,r){ensureInitialized();const i=bytesFromString(n),o=await dittoffi_try_exec_statement(e,t,i,r);return throwOnErrorResult(o.error,"dittoffi_try_exec_statement"),o.success}function addSubscription(e,t,n,r,i,o,a){ensureInitialized();const s=ditto_add_subscription(e,bytesFromString(t),bytesFromString(n),r,i,o,a);if(0!==s)throw new Error(errorMessage()||`ditto_add_subscription() failed with error code: ${s}`)}function removeSubscription(e,t,n,r,i,o,a){ensureInitialized();const s=ditto_remove_subscription(e,bytesFromString(t),bytesFromString(n),r,i,o,a);if(0!==s)throw new Error(errorMessage()||`ditto_remove_subscription() failed with error code: ${s}`)}function tryAddSyncSubscription(e,t,n){ensureInitialized();throwOnErrorResult(dittoffi_try_add_sync_subscription(e,bytesFromString(t),n).error,"dittoffi_try_add_sync_subscription")}function tryRemoveSyncSubscription(e,t,n){ensureInitialized();throwOnErrorResult(dittoffi_try_remove_sync_subscription(e,bytesFromString(t),n).error,"dittoffi_try_remove_sync_subscription")}function queryResultFree(e){ensureInitialized(),dittoffi_query_result_free(e)}function queryResultItemFree(e){ensureInitialized(),dittoffi_query_result_item_free(e)}function queryResultItems(e){ensureInitialized();const t=[],n=dittoffi_query_result_item_count(e);for(let r=0;r<n;r++)t.push(dittoffi_query_result_item_at(e,r));return t}function queryResultMutatedDocumentIDs(e){ensureInitialized();const t=[],n=dittoffi_query_result_mutated_document_id_count(e);for(let r=0;r<n;r++){const n=dittoffi_query_result_mutated_document_id_at(e,r);t.push(boxCBytesIntoBuffer(n))}return t}function queryResultItemCBOR(e){ensureInitialized();return boxCBytesIntoBuffer(dittoffi_query_result_item_cbor(e))}function queryResultItemJSON(e){ensureInitialized();return boxCStringIntoString(dittoffi_query_result_item_json(e))}function liveQueryRegister(e,t,n,r,i,o,a,s,c){ensureInitialized();const d=bytesFromString(t),l=bytesFromString(n),{status_code:u,i64:_}=ditto_live_query_register_str_detached(e,d,l,r,i,o,a,wrapBackgroundCbForFFI(c,s));if(0!==u)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${u}`);return _}function tryExperimentalRegisterChangeObserver(e,t,n,r){ensureInitialized();const i=wrapBackgroundCbForFFI((e=>log("Error",`The registered store observer callback failed with ${e}`)),r),o=dittoffi_try_experimental_register_change_observer_str_detached(e,bytesFromString(t),n,i);return throwOnErrorResult(o.error,"dittoffi_try_experimental_register_change_observer_str_detached"),o.success}async function liveQueryStart(e,t){ensureInitialized();const n=await ditto_live_query_start(e,t);if(0!==n)throw new Error(errorMessage()||`\`ditto_live_query_start()\` failed with error code: ${n}`)}function liveQueryStop(e,t){ensureInitialized(),ditto_live_query_stop(e,t)}async function liveQuerySignalAvailableNext(e,t){ensureInitialized(),await ditto_live_query_signal_available_next(e,t)}async function liveQueryWebhookRegister(e,t,n,r,i,o,a){ensureInitialized();const s=bytesFromString(t),c=bytesFromString(n),d=bytesFromString(a),{status_code:l,id:u}=await ditto_live_query_webhook_register_str(e,s,c,r,i,o,d);if(0!==l)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${l}`);return boxCBytesIntoBuffer(u)}async function tryRegisterStoreObserverWebhook(e,t,n,r){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(r),a=await dittoffi_try_register_store_observer_webhook(e,i,n,o);throwOnErrorResult(a.error,"dittoffi_try_register_store_observer_webhook");return boxCBytesIntoBuffer(a.success)}async function readTransaction(e){ensureInitialized();const{status_code:t,txn:n}=await ditto_read_transaction(e);if(0!==t)throw new Error(errorMessage()||`\`ditto_read_transaction()\` failed with error code: ${t}`);return n}function readTransactionFree(e){return ensureInitialized(),ditto_read_transaction_free(e)}async function writeTransaction(e){ensureInitialized();const{status_code:t,txn:n}=await ditto_write_transaction(e,null);if(0!==t)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${t}`);return n}async function writeTransactionCommit(e,t){ensureInitialized();const n=await ditto_write_transaction_commit(e,t);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_commit() failed with error code: ${n}`)}async function writeTransactionRollback(e,t){ensureInitialized();const n=await ditto_write_transaction_rollback(e,t);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_rollback() failed with error code: ${n}`)}function staticTCPClientFreeHandle(e){(void 0)(e)}function websocketClientFreeHandle(e){ensureInitialized(),websocket_client_free_handle(e)}function loggerInit(){ensureInitialized(),ditto_logger_init()}async function loggerSetCustomLogCb(e){if(ensureInitialized(),null===e)await ditto_logger_set_custom_log_cb(null);else{const t=wrapBackgroundCbForFFI(null,((t,n)=>{try{const r=boxCStringIntoString(n);e(t,r)}catch(e){log("Error",`The registered cb in \`ditto_logger_set_custom_log_cb()\` failed with: ${e}`)}}));await ditto_logger_set_custom_log_cb(t)}}function loggerEnabled(e){ensureInitialized(),ditto_logger_enabled(!!e)}function loggerEnabledGet(){return ensureInitialized(),!!ditto_logger_enabled_get()}function loggerEmojiHeadingsEnabled(e){ensureInitialized(),ditto_logger_emoji_headings_enabled(e)}function loggerEmojiHeadingsEnabledGet(){return ensureInitialized(),ditto_logger_emoji_headings_enabled_get()}function loggerMinimumLogLevel(e){ensureInitialized(),ditto_logger_minimum_log_level(e)}function loggerMinimumLogLevelGet(){return ensureInitialized(),ditto_logger_minimum_log_level_get()}function loggerSetLogFile(e){ensureInitialized();if(0!==ditto_logger_set_log_file(e?bytesFromString(e):null))throw errorMessage(),new Error(`Can't set log file, due to error: ${errorMessage}`)}function log(e,t){ensureInitialized();ditto_log(e,bytesFromString(t))}function dittoIdentityConfigMakeOnlinePlayground(e,t,n){ensureInitialized();const r=bytesFromString(e),i=bytesFromString(t),o=bytesFromString(n),{status_code:a,identity_config:s}=ditto_identity_config_make_online_playground(r,i,o);if(0!==a)throw new Error(errorMessage()||`ditto_identity_config_make_online_playground() failed with error code: ${a}`);return s}function dittoIdentityConfigMakeOnlineWithAuthentication(e,t){ensureInitialized();const n=bytesFromString(e),r=bytesFromString(t),{status_code:i,identity_config:o}=ditto_identity_config_make_online_with_authentication(n,r);if(0!==i)throw new Error(errorMessage()||`ditto_identity_config_make_online_with_authentication() failed with error code: ${i}`);return o}function dittoIdentityConfigMakeOfflinePlayground(e,t){ensureInitialized();const n=bytesFromString(e),r=Number(t),{status_code:i,identity_config:o}=ditto_identity_config_make_offline_playground(n,r);if(0!==i)throw new Error(errorMessage()||`ditto_identity_config_make_offline_playground() failed with error code: ${i}`);return o}function dittoIdentityConfigMakeSharedKey(e,t,n){ensureInitialized();const r=bytesFromString(e),i=bytesFromString(t),o=Number(n),{status_code:a,identity_config:s}=ditto_identity_config_make_shared_key(r,i,o);if(0!==a)throw new Error(errorMessage()||`ditto_identity_config_make_shared_key() failed with error code: ${a}`);return s}function dittoIdentityConfigMakeManual(e){ensureInitialized();const t=bytesFromString(e),{status_code:n,identity_config:r}=ditto_identity_config_make_manual_v0(t);if(0!==n)throw new Error(errorMessage()||`ditto_identity_config_make_manual_v0() failed with error code: ${n}`);return r}function dittoAuthClientGetSiteID(e){return ensureInitialized(),ditto_auth_client_get_site_id(e)}function dittoAuthClientGetAppID(e){ensureInitialized();return boxCStringIntoString(ditto_auth_client_get_app_id(e))}function dittoAuthClientUserID(e){ensureInitialized();return boxCStringIntoString(ditto_auth_client_user_id(e))}function dittoAuthClientIsWebValid(e){return ensureInitialized(),0!==ditto_auth_client_is_web_valid(e)}function dittoAuthClientIsX509Valid(e){return ensureInitialized(),0!==ditto_auth_client_is_x509_valid(e)}async function dittoAuthClientLoginWithToken(e,t,n){ensureInitialized();const r=bytesFromString(t),i=bytesFromString(n),o=await ditto_auth_client_login_with_token(e,r,i);if(0!==o)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${o}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(e,t,n,r){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(n),a=bytesFromString(r),s=await ditto_auth_client_login_with_credentials(e,i,o,a);if(0!==s)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${s}).`)}async function dittoAuthClientLogout(e){ensureInitialized();const t=await ditto_auth_client_logout(e);if(0!==t)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${t}).`)}function dittoMake(e,t,n){ensureInitialized();return ditto_make(bytesFromString(e),t,n)}async function dittoGetCollectionNames(e){ensureInitialized();const t=await ditto_get_collection_names(e),n=t.status_code,r=t.names;if(0!==n)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${n}`);return cStringVecToStringArray(r)}function dittoFree(e){return ensureInitialized(),ditto_free(e)}function dittoRegisterPresenceV1Callback(e,t){ensureInitialized(),ditto_register_presence_v1_callback(e,wrapBackgroundCbForFFI((e=>log("Error",`The registered presence callback v1 errored with ${e}`)),(e=>{const n=refCStringToString(e);t(n)})))}async function dittoClearPresenceCallback(e){return ensureInitialized(),ditto_clear_presence_callback(e)}function dittoRegisterPresenceV3Callback(e,t){ensureInitialized(),ditto_register_presence_v3_callback(e,wrapBackgroundCbForFFI((e=>log("Error",`The registered presence callback v3 errored with ${e}`)),(e=>{const n=refCStringToString(e);t(n)})))}async function dittoClearPresenceV3Callback(e){return ensureInitialized(),ditto_clear_presence_v3_callback(e)}function presencePeerMetadataJSON(e){ensureInitialized();const t=boxCBytesIntoBuffer(dittoffi_presence_peer_metadata_json(e));return(new TextDecoder).decode(t)}async function presenceTrySetPeerMetadataJSON(e,t){ensureInitialized();const n=bytesFromString(t);throwOnErrorResult((await dittoffi_presence_try_set_peer_metadata_json(e,n)).error,"dittoffi_presence_try_set_peer_metadata_json")}function connectionRequestPeerKeyString(e){ensureInitialized();return boxCStringIntoString(dittoffi_connection_request_peer_key_string(e))}function connectionRequestPeerMetadataJSON(e){ensureInitialized();const t=refCBytesIntoBuffer(dittoffi_connection_request_peer_metadata_json(e));return(new TextDecoder).decode(t)}function connectionRequestIdentityServiceMetadataJSON(e){ensureInitialized();const t=refCBytesIntoBuffer(dittoffi_connection_request_identity_service_metadata_json(e));return(new TextDecoder).decode(t)}function connectionRequestConnectionType(e){return ensureInitialized(),dittoffi_connection_request_connection_type(e)}function connectionRequestAuthorize(e,t){ensureInitialized(),dittoffi_connection_request_authorize(e,t)}function connectionRequestFree(e){ensureInitialized(),dittoffi_connection_request_free(e)}function presenceSetConnectionRequestHandler(e,t,n){if(ensureInitialized(),null==t)dittoffi_presence_set_connection_request_handler(e,null);else{dittoffi_presence_set_connection_request_handler(e,wrapAsyncBackgroundCbForFFI(n,t))}}function dittoSmallPeerInfoGetIsEnabled(e){return ensureInitialized(),ditto_small_peer_info_get_is_enabled(e)}async function dittoSmallPeerInfoSetEnabled(e,t){ensureInitialized(),ditto_small_peer_info_set_enabled(e,t)}async function dittoSmallPeerInfoGetSyncScope(e){return ensureInitialized(),ditto_small_peer_info_get_sync_scope(e)}async function dittoSmallPeerInfoSetSyncScope(e,t){return ensureInitialized(),ditto_small_peer_info_set_sync_scope(e,t)}function dittoSmallPeerInfoGetMetadata(e){ensureInitialized();return boxCStringIntoString(ditto_small_peer_info_get_metadata(e))}function dittoSmallPeerInfoSetMetadata(e,t){ensureInitialized();const n=ditto_small_peer_info_set_metadata(e,bytesFromString(t));switch(n){case 0:return;case-1:throw new Error("Internal inconsistency, the observability subsystem is unavailable.");case 1:throw new Error(`Validation error, size limit exceeded: ${errorMessage()||"metadata is too big"}`);case 2:throw new Error(`Validation error, ${errorMessage()||"depth limit for metadata object exceeded"}`);case 3:throw new Error(`Validation error, ${errorMessage()||`'${t}' is not a valid JSON object`}`);default:throw new Error(errorMessage()||`Internal inconsistency, ditto_small_peer_info_set_metadata() returned an unknown error code: ${n}`)}}function dittoSmallPeerInfoCollectionSetTransportConfigData(e,t){ensureInitialized(),ditto_small_peer_info_set_transport_config_data(e,t)}function dittoRegisterTransportConditionChangedCallback(e,t){ensureInitialized(),ditto_register_transport_condition_changed_callback(e,t?wrapBackgroundCbForFFI((e=>log("Error",`The registered "transport condition changed" callback errored with ${e}`)),t):null)}function dittoSetDeviceName(e,t){ensureInitialized();return boxCStringIntoString(ditto_set_device_name(e,bytesFromString(t)))}function dittoSetConnectRetryInterval(e,t){ensureInitialized();return ditto_set_connect_retry_interval(e,Math.min(Math.max(0,t),4294967295))}function dittoSetSyncGroup(e,t){return ensureInitialized(),ditto_set_sync_group(e,t)}async function dittoNewAttachmentFromBytes(e,t){ensureInitialized();const n={},r=await ditto_new_attachment_from_bytes(e,t,n);if(0!==r)throw new DittoFFIError(r,null,`ditto_new_attachment_from_bytes() failed with error code: ${r}`);return n}async function dittoResolveAttachment(e,t,n,r){ensureInitialized();const{onComplete:i,onProgress:o,onDelete:a}=n,s=wrapBackgroundCbForFFI(r,i),c=wrapBackgroundCbForFFI(r,o),d=wrapBackgroundCbForFFI(r,a),{status_code:l,cancel_token:u}=await ditto_resolve_attachment(e,t,s,c,d);if(0!==l)throw new DittoFFIError(l,null,`ditto_resolve_attachment() failed with error code: ${l}`);return u}function dittoCancelResolveAttachment(e,t,n){ensureInitialized();const r=ditto_cancel_resolve_attachment(e,t,n);if(0!==r)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${r}`)}function freeAttachmentHandle(e){ensureInitialized(),ditto_free_attachment_handle(e)}async function dittoGetCompleteAttachmentData(e,t){ensureInitialized();const{status:n,data:r}=await ditto_get_complete_attachment_data(e,t);if(0!==n)throw new Error(errorMessage()||`\`ditto_get_complete_attachment_data()\` failed with error code: ${n}`);return boxCBytesIntoBuffer(r)}function dittoGetSDKVersion(e){ensureInitialized();return boxCStringIntoString(ditto_get_sdk_version())}function dittoGetSDKSemver(){ensureInitialized();return boxCStringIntoString(dittoffi_get_sdk_semver())}function dittoPresenceV1(e){ensureInitialized();return boxCStringIntoString(ditto_presence_v1(e))}function dittoPresenceV3(e){ensureInitialized();return boxCStringIntoString(ditto_presence_v3(e))}function dittoStartTCPServer(e,t){ensureInitialized();return(void 0)(e,bytesFromString(t))}function dittoStopTCPServer(e){return ensureInitialized(),(void 0)(e)}async function dittoShutdown(e){return ensureInitialized(),await ditto_shutdown(e)}function dittoStartHTTPServer(e,t,n,r,i,o){ensureInitialized();return(void 0)(e,bytesFromString(t),bytesFromString(n),r,bytesFromString(i),bytesFromString(o))}function dittoStopHTTPServer(e){return ensureInitialized(),(void 0)(e)}function dittoRunGarbageCollection(e){return ensureInitialized(),ditto_run_garbage_collection(e)}async function dittoDisableSyncWithV3(e){ensureInitialized();const t=await ditto_disable_sync_with_v3(e);if(0!==t)throw new Error(errorMessage()||`ditto_disable_sync_with_v3() failed with error code: ${t}`)}function dittoSetStaticTCPClients(e,t){if(ensureInitialized(),t.length>0)throw new Error(`Web variant of Ditto does not support connecting to TCP servers: ${t.join(", ")}`)}function dittoSetStaticWebsocketClients(e,t,n){ensureInitialized();ditto_set_static_websocket_clients(e,t.map((e=>bytesFromString(e))),n)}function documentsHash(e){ensureInitialized();const{status_code:t,u64:n}=ditto_documents_hash(e);if(0!==t)throw new Error(errorMessage()||`\`ditto_documents_hash()\` failed with error code: ${t}`);return BigInt(n)}function documentsHashMnemonic(e){ensureInitialized();const{status_code:t,c_string:n}=ditto_documents_hash_mnemonic(e);if(0!==t)throw new Error(errorMessage()||`\`ditto_documents_hash_mnemonic()\` failed with error code: ${t}`);return boxCStringIntoString(n)}function base64encode(e,t){return boxCStringIntoString(dittoffi_base64_encode(e,t))}function tryBase64Decode(e,t){const n=dittoffi_try_base64_decode(bytesFromString(e),t||null);return throwOnErrorResult(n.error,"dittoffi_try_base64_decode"),boxCBytesIntoBuffer(n.success)}async function dittoAuthSetLoginProvider(e,t){return ensureInitialized(),await ditto_auth_set_login_provider(e,t)}function dittoAuthClientMakeLoginProvider(e,t){return ensureInitialized(),ditto_auth_client_make_login_provider(wrapBackgroundCbForFFI(t,e))}function dittoAuthClientSetValidityListener(e,t,n){ensureInitialized();return ditto_auth_client_set_validity_listener(e,wrapBackgroundCbForFFI(n,(function(e,n){return t(1===e,1===n)})))}function transportsInit(){ensureInitialized()}function transportsBLEIsAvailable(e){return ensureInitialized(),!1}function transportsLANIsAvailable(e){return ensureInitialized(),!1}function transportsAWDLIsAvailable(e){return ensureInitialized(),!1}!function(e){e[e.counter=0]="counter",e[e.register=1]="register",e[e.attachment=2]="attachment",e[e.rga=3]="rga",e[e.rwMap=4]="rwMap"}(DittoCRDTType||(DittoCRDTType={}));let isInitialized$1=!1;async function init$1(e){e?await init$2(e):await init$2(),isInitialized$1=!0}function initSDKVersion(e,t,n){ensureInitialized(),bytesFromString(e),bytesFromString(t);const r=ditto_init_sdk_version(e,t,bytesFromString(n));if(void 0!==r&&0!==r)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${r}`)}function tryVerifyLicense(e){ensureInitialized();throwOnErrorResult(dittoffi_try_verify_license(bytesFromString(e)).error,"dittoffi_try_verify_license")}const NOT_FOUND_ERROR_CODE=-30798;function wrapBackgroundCbForFFI(e,t){const n=null!=e?e:e=>log("Error",`The registered callback failed with ${e}`);return(e,...r)=>{let i;try{i=t(...r)}catch(e){try{n(e)}catch(e){log("Error",`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${e}`)}}return e(i)}}function wrapAsyncBackgroundCbForFFI(e,t){const n=null!=e?e:e=>log("Error",`The registered callback failed with ${e}`);return async(e,...r)=>{let i;try{i=await t(...r)}catch(e){try{n(e)}catch(e){log("Error",`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${e}`)}}return e(i)}}function bytesFromString(e){if(void 0===e)return;if(null===e)return null;if("string"!=typeof e)throw new Error(`Can't convert string to Uint8Array, not a string: ${e}`);return(new TextEncoder).encode(`${e}\0`)}function errorMessage(){ensureInitialized();return boxCStringIntoString(ditto_error_message())}function ensureInitialized(){if(!isInitialized$1)throw new Error("Ditto needs to be initialized before using any of its API, please make sure to call `await init()` first.")}const ERROR_CODES={internal:"An unexpected internal error occurred. Please get in touch with Ditto customer service to report this incident.","internal/unknown-error":"An unexpected internal error occurred. Please get in touch with Ditto customer service to report this incident.","sdk/unsupported":"The feature is not supported by the current environment.","query/arguments-invalid":"The query arguments were invalid.","query/execution":"The query could not be executed.","query/invalid":"The query was invalid.","query/unsupported":"The query contains unsupported features.","query/parameter":"The query to update system parameters failed.","store/backend":"An error occurred with the storage backend.","store/crdt":"An error occurred processing a CRDT.","store/document-not-found":"The document with the provided ID could not be found.","store/attachment-file-permission-denied":"Permission has been denied for a file operation when working with attachments.","store/attachment-file-not-found":"The source file for the attachment does not exist.","store/attachment-not-found":"The attachment could not be found.","store/attachment-token-invalid":"The attachment token is invalid.","store/failed-to-create-attachment":"The attachment could not be created.","store/failed-to-fetch-attachment":"The attachment could not be fetched.","activation/license-token-verification-failed":"Please provide a valid license token.","activation/license-token-expired":"The license token expired. Please renew it.","activation/license-token-unsupported-future-version":"The provided license token is in an unsupported future format.","activation/not-activated":"The operation failed because the Ditto instance has not yet been activated.","validation/depth-limit-exceeded":"The maximum depth limit has been exceeded.","validation/invalid-cbor":"The value provided is not valid CBOR.","validation/invalid-json":"The value provided is not valid JSON.","validation/not-an-object":"The value provided is not of type object.","validation/not-json-compatible":"Value is not serializable as JSON.","validation/size-limit-exceeded":"The size limit has been exceeded."},DEFAULT_STATUS_CODE_MAPPING={ActivationLicenseTokenExpired:["activation/license-token-expired"],ActivationLicenseTokenInvalid:["activation/license-token-verification-failed"],ActivationLicenseUnsupportedFutureVersion:["activation/license-token-unsupported-future-version"],ActivationNotActivated:["activation/not-activated"],JsFloatingStoreOperation:["internal","Internal inconsistency, an outstanding store operation was not awaited."],DqlQueryCompilation:["query/invalid"],DqlInvalidQueryArgs:["query/arguments-invalid"],DqlUnsupported:["query/unsupported"],StoreQuery:["query/execution"],ParameterQuery:["query/parameter"],StoreDocumentNotFound:["store/document-not-found"],StoreDatabase:["store/backend"],Crdt:["store/crdt"],Base64Invalid:["internal","Invalid base64 encoding."],ValidationDepthLimitExceeded:["validation/depth-limit-exceeded"],ValidationInvalidCbor:["validation/invalid-cbor"],ValidationInvalidJson:["validation/invalid-json"],ValidationNotAMap:["validation/not-an-object"],ValidationSizeLimitExceeded:["validation/size-limit-exceeded"],default:["internal/unknown-error"]};class DittoError extends Error{constructor(e,t,n={}){if(null==ERROR_CODES[e])throw new DittoError("internal",`Invalid error code: ${e}`);super(t||ERROR_CODES[e]),this.code="internal",this.code=e,this.context=Object.freeze({...n})}static fromFFIError(e,t,n,r){const i=n||e.message,o={coreError:e.code,coreErrorMessage:e.message,...r},a=new DittoError(t,i,o);return null!=e.stack&&(a.stack=e.stack),a}}function mapFFIErrors(e,t,n){try{return e()}catch(e){if(e instanceof DittoFFIError)throw translateFFIError(e,t,n);throw e}}async function mapFFIErrorsAsync(e,t,n){try{return await e()}catch(e){if(e instanceof DittoFFIError)throw translateFFIError(e,t,n);throw e}}const translateFFIError=(e,t,n)=>{var r;const i=e.code.toString();let o,a;return null!=t&&null!=t[i]?[o,a]=t[i]:[o,a]=null!==(r=DEFAULT_STATUS_CODE_MAPPING[i])&&void 0!==r?r:DEFAULT_STATUS_CODE_MAPPING.default,DittoError.fromFFIError(e,o,a,n)};class AttachmentToken{constructor(e){let t,n,r;null!=e[DittoCRDTTypeKey]?({id:t,len:n,meta:r}=AttachmentToken.validateTypedInput(e)):({id:t,len:n,meta:r}=AttachmentToken.validateUntypedInput(e)),this.id=mapFFIErrors((()=>base64encode(t,"Unpadded"))),this.idBytes=t,this.len=n,this.metadata=r}static validateTypedInput(e){if(e[DittoCRDTTypeKey]!==DittoCRDTType.attachment)throw new Error("Invalid attachment token");const t=e._id;if(!(t instanceof Uint8Array))throw new Error("Invalid attachment token id");const n=e._len;if("number"!=typeof n&&"bigint"!=typeof n||n<0)throw new Error("Invalid attachment token length, must be a non-negative number or bigint");const r=e._meta;if("object"!=typeof r)throw new Error("Invalid attachment token meta");return{id:t,len:n,meta:r}}static validateUntypedInput(e){const t=e.id;if("string"!=typeof t)throw new Error("Invalid attachment token id");const n=mapFFIErrors((()=>tryBase64Decode(t,"Unpadded")),{Base64Invalid:["store/attachment-token-invalid","Failed to decode attachment token id from base64 input"]},{attachmentTokenID:t}),r=e.len;if("number"!=typeof r&&"bigint"!=typeof r||r<0)throw new Error("Invalid attachment token length, must be a non-negative number or bigint");const i=e.metadata;if("object"!=typeof i)throw new Error("Invalid attachment token meta");return{id:n,len:r,meta:i}}}const fullBuildVersionString="4.7.3",defaultDittoWasmFileURL="https://software.ditto.live/js/Ditto/4.7.3/ditto.wasm";let isInitialized=!1;async function init(e={}){if(!isInitialized){{const t=e.webAssemblyModule||defaultDittoWasmFileURL;await init$1(t),initSDKVersion("Web","JavaScript","4.7.3"),loggerInit()}isInitialized=!0}}class Logger{static get logFile(){return this._logFile}static setLogFile(e){e?(loggerSetLogFile(e),this._logFile=e):(loggerSetLogFile(void 0),delete this._logFile)}static setLogFileURL(e){var t;this.setLogFile(null!==(t=null==e?void 0:e.pathname)&&void 0!==t?t:null)}static get enabled(){return loggerEnabledGet()}static set enabled(e){loggerEnabled(e)}static get emojiLogLevelHeadingsEnabled(){return loggerEmojiHeadingsEnabledGet()}static set emojiLogLevelHeadingsEnabled(e){loggerEmojiHeadingsEnabled(e)}static get minimumLogLevel(){return loggerMinimumLogLevelGet()}static set minimumLogLevel(e){loggerMinimumLogLevel(e)}static get customLogCallback(){return this._customLogCallback}static async setCustomLogCallback(e){e?(await loggerSetCustomLogCb(e),this._customLogCallback=e):(await loggerSetCustomLogCb(null),delete this._customLogCallback)}static log(e,t){log(e,t)}static error(e){this.log("Error",e)}static warning(e){this.log("Warning",e)}static info(e){this.log("Info",e)}static debug(e){this.log("Debug",e)}static verbose(e){this.log("Verbose",e)}constructor(){throw new Error("Logger can't be instantiated, use its static properties & methods directly instead.")}}const CBOR_OPTIONS=Object.freeze({dictionary:"object",mode:"strict"}),EMPTY_KEY=Symbol("EMPTY_KEY"),OMIT_VALUE=Symbol("OMIT_VALUE"),POW_2_24=5.960464477539063e-8,POW_2_32=4294967296,POW_2_53=9007199254740992,MAX_SAFE_INTEGER=18446744073709551616n,DECODE_CHUNK_SIZE=8192,kCborTag=6,kCborTagUint8=64,kCborTagUint16=69,kCborTagUint32=70,kCborTagInt8=72,kCborTagInt16=77,kCborTagInt32=78,kCborTagFloat32=85,kCborTagFloat64=86;function objectIs(e,t){return"function"==typeof Object.is?Object.is(e,t):e===t?0!==e||1/e==1/t:e!=e&&t!=t}function options(e){const t={...CBOR_OPTIONS};return"object"==typeof e&&(t.dictionary=function isDictionary(e){return"string"==typeof e&&["object","map"].includes(e)}(e.dictionary)?e.dictionary:CBOR_OPTIONS.dictionary,t.mode=function isMode(e){return"string"==typeof e&&["loose","strict","sequence"].includes(e)}(e.mode)?e.mode:CBOR_OPTIONS.mode),Object.freeze(t)}function lexicographicalCompare(e,t){const n=Math.min(e.byteLength,t.byteLength);for(let r=0;r<n;r++){const n=e[r]-t[r];if(0!==n)return n}return e.byteLength-t.byteLength}var _Sequence_instances,_Sequence_toInspectString,__classPrivateFieldGet=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)};class Sequence{static from(e){return new Sequence(Array.from(e))}constructor(e){_Sequence_instances.add(this),Object.defineProperty(this,"_data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._data=e||[]}add(e){return this._data.push(e)-1}remove(e){return this._data.splice(e,1)[0]}get(e){return this._data[e]}clone(){return new Sequence(this.data)}get data(){return Array.from(this._data)}get size(){return this._data.length}[(_Sequence_instances=new WeakSet,Symbol.toStringTag)](){return"Sequence"}[(_Sequence_toInspectString=function _Sequence_toInspectString(e){return`${this[Symbol.toStringTag]()}(${this.size}) ${e(this._data)}`},Symbol.for("Deno.customInspect"))](e){return __classPrivateFieldGet(this,_Sequence_instances,"m",_Sequence_toInspectString).call(this,e)}[Symbol.for("nodejs.util.inspect.custom")](e,t,n){return __classPrivateFieldGet(this,_Sequence_instances,"m",_Sequence_toInspectString).call(this,n)}}class SimpleValue{static create(e){if(void 0===e)return new SimpleValue(23);if(null===e)return new SimpleValue(22);if(!0===e)return new SimpleValue(21);if(!1===e)return new SimpleValue(20);if("number"==typeof e&&e>=0&&e<=255)return new SimpleValue(e);throw new Error("CBORError: Value out of range or not a simple value.")}constructor(e){switch(Object.defineProperty(this,"semantic",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!0){case 20===e:this.semantic="false";break;case 21===e:this.semantic="true";break;case 22===e:this.semantic="null";break;case 23===e:this.semantic="undefined";break;case e>23&&e<32:this.semantic="reserved";break;default:this.semantic="unassigned"}this.value=e}toPrimitive(){switch(this.semantic){case"false":return!1;case"true":return!0;case"null":return null;default:return}}}class TaggedValue{constructor(e,t){Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e,this.tag=t}}function decode(e,t,n={}){const{dictionary:r,mode:i}=options(n),o="sequence"===i||"strict"===i,a=new DataView(e),s=new Uint8Array(e);let c=0,reviverFunction=function(e,t){return t};function commitRead(e,t){return c+=e,t}function readArrayBuffer(t){return commitRead(t,new Uint8Array(e,c,t))}function readUint8(){return commitRead(1,s[c])}function readUint16(){return commitRead(2,a.getUint16(c))}function readBreak(){return 255===s[c]&&(c+=1,!0)}function readLength(e){if(e<24)return e;if(24===e)return readUint8();if(25===e)return readUint16();if(26===e)return function readUint32(){return commitRead(4,a.getUint32(c))}();if(27===e){const e=function readUint64(){return commitRead(8,a.getBigUint64(c))}();return e<POW_2_53?Number(e):e}if(31===e)return-1;throw new Error("CBORError: Invalid length encoding")}function readIndefiniteStringLength(e){const t=readUint8();if(255===t)return-1;const n=readLength(31&t);if(n<0||t>>5!==e)throw new Error("CBORError: Invalid indefinite length element");return Number(n)}function appendUtf16Data(e,t){for(let n=0;n<t;++n){let n=readUint8();128&n&&(n<224?(n=(31&n)<<6|63&readUint8(),t-=1):n<240?(n=(15&n)<<12|(63&readUint8())<<6|63&readUint8(),t-=2):(n=(15&n)<<18|(63&readUint8())<<12|(63&readUint8())<<6|63&readUint8(),t-=3)),n<65536?e.push(n):(n-=65536,e.push(55296|n>>10),e.push(56320|1023&n))}}function decodeItem(){const e=readUint8(),t=e>>5,n=31&e;let i,s;if(7===t)switch(n){case 25:return function readFloat16(){const e=new ArrayBuffer(4),t=new DataView(e),n=readUint16(),r=32768&n;let i=31744&n;const o=1023&n;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==o)return(r?-1:1)*o*POW_2_24;return t.setUint32(0,r<<16|i<<13|o<<13),t.getFloat32(0)}();case 26:return function readFloat32(){return commitRead(4,a.getFloat32(c))}();case 27:return function readFloat64(){return commitRead(8,a.getFloat64(c))}()}if(s=readLength(n),s<0&&(t<2||6<t))throw new Error("CBORError: Invalid length");switch(t){case 0:return reviverFunction(EMPTY_KEY,s);case 1:return reviverFunction(EMPTY_KEY,"number"==typeof s?-1-s:-1n-s);case 2:if(s<0){const e=[];let n=0;for(;(s=readIndefiniteStringLength(t))>=0;)n+=s,e.push(readArrayBuffer(s));const r=new Uint8Array(n);let o=0;for(i=0;i<e.length;++i)r.set(e[i],o),o+=e[i].length;return reviverFunction(EMPTY_KEY,r)}return reviverFunction(EMPTY_KEY,readArrayBuffer(s));case 3:{const e=[];if(s<0)for(;(s=readIndefiniteStringLength(t))>=0;)appendUtf16Data(e,s);else appendUtf16Data(e,s);let n="";for(i=0;i<e.length;i+=DECODE_CHUNK_SIZE)n+=String.fromCharCode.apply(null,e.slice(i,i+DECODE_CHUNK_SIZE));return reviverFunction(EMPTY_KEY,n)}case 4:{let e;if(s<0){e=[];let t=0;for(;!readBreak();)e.push(reviverFunction(t++,decodeItem()))}else for(e=new Array(s),i=0;i<s;++i)e[i]=reviverFunction(i,decodeItem());return reviverFunction(EMPTY_KEY,e)}case 5:{if("map"===r){const e=new Map;for(i=0;i<s||s<0&&!readBreak();++i){const t=decodeItem();if(o&&e.has(t))throw new Error("CBORError: Duplicate key encountered");e.set(t,reviverFunction(t,decodeItem()))}return reviverFunction(EMPTY_KEY,e)}const e={};for(i=0;i<s||s<0&&!readBreak();++i){const t=decodeItem();if(o&&Object.prototype.hasOwnProperty.call(e,t))throw new Error("CBORError: Duplicate key encountered");e[t]=reviverFunction(t,decodeItem())}return reviverFunction(EMPTY_KEY,e)}case 6:{const e=decodeItem(),t=s;if(e instanceof Uint8Array){const n=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);switch(t){case kCborTagUint8:return reviverFunction(EMPTY_KEY,new Uint8Array(n));case kCborTagInt8:return reviverFunction(EMPTY_KEY,new Int8Array(n));case kCborTagUint16:return reviverFunction(EMPTY_KEY,new Uint16Array(n));case kCborTagInt16:return reviverFunction(EMPTY_KEY,new Int16Array(n));case kCborTagUint32:return reviverFunction(EMPTY_KEY,new Uint32Array(n));case kCborTagInt32:return reviverFunction(EMPTY_KEY,new Int32Array(n));case kCborTagFloat32:return reviverFunction(EMPTY_KEY,new Float32Array(n));case kCborTagFloat64:return reviverFunction(EMPTY_KEY,new Float64Array(n))}}return reviverFunction(EMPTY_KEY,new TaggedValue(e,t))}case 7:switch(s){case 20:return reviverFunction(EMPTY_KEY,!1);case 21:return reviverFunction(EMPTY_KEY,!0);case 22:return reviverFunction(EMPTY_KEY,null);case 23:return reviverFunction(EMPTY_KEY,void 0);default:return reviverFunction(EMPTY_KEY,new SimpleValue(s))}}}"function"==typeof t&&(reviverFunction=t);const d=decodeItem();if(c!==e.byteLength){if("sequence"!==i)throw new Error("CBORError: Remaining bytes");const t=new Sequence([d]);for(;c<e.byteLength;)t.add(reviverFunction(EMPTY_KEY,decodeItem()));return t}return"sequence"===i?new Sequence([d]):d}function parse(e,t,n){return decode(e,t,n)}function encode(e,t){let n,r=new ArrayBuffer(256),i=new DataView(r),o=new Uint8Array(r),a=0,replacerFunction=(e,t)=>t;if("function"==typeof t&&(replacerFunction=t),Array.isArray(t)){const e=t.slice();replacerFunction=(t,n)=>t===EMPTY_KEY||e.includes(t)?n:OMIT_VALUE}function prepareWrite(e){let t=r.byteLength;const s=a+e;for(;t<s;)t<<=1;if(t!==r.byteLength){const e=i;r=new ArrayBuffer(t),i=new DataView(r),o=new Uint8Array(r);const n=a+3>>2;for(let t=0;t<n;++t)i.setUint32(t<<2,e.getUint32(t<<2))}return n=e,i}function commitWrite(...e){a+=n}function writeUint8(e){commitWrite(prepareWrite(1).setUint8(a,e))}function writeUint8Array(e){prepareWrite(e.length),o.set(e,a),commitWrite()}function writeUint16(e){commitWrite(prepareWrite(2).setUint16(a,e))}function writeUint32(e){commitWrite(prepareWrite(4).setUint32(a,e))}function writeUint64(e){const t=e%POW_2_32,n=(e-t)/POW_2_32,r=prepareWrite(8);r.setUint32(a,n),r.setUint32(a+4,t),commitWrite()}function writeBigUint64(e){commitWrite(prepareWrite(8).setBigUint64(a,e))}function writeVarUint(e,t){e<=255?e<24?writeUint8(Number(e)|t):(writeUint8(24|t),writeUint8(Number(e))):e<=65535?(writeUint8(25|t),writeUint16(Number(e))):e<=4294967295?(writeUint8(26|t),writeUint32(Number(e))):(writeUint8(27|t),"number"==typeof e?writeUint64(e):writeBigUint64(e))}function writeTypeAndLength(e,t){t<24?writeUint8(e<<5|t):t<256?(writeUint8(e<<5|24),writeUint8(t)):t<65536?(writeUint8(e<<5|25),writeUint16(t)):t<4294967296?(writeUint8(e<<5|26),writeUint32(t)):(writeUint8(e<<5|27),writeUint64(t))}function encodeItem(e){if(e!==OMIT_VALUE){if(!1===e)return writeUint8(244);if(!0===e)return writeUint8(245);if(null===e)return writeUint8(246);if(void 0===e)return writeUint8(247);if(objectIs(e,-0))return writeUint8Array([249,128,0]);switch(typeof e){case"bigint":return function writeBigInteger(e){let t=0;if(0<=e&&e<=MAX_SAFE_INTEGER)t=0;else{if(!(-MAX_SAFE_INTEGER<=e&&e<0))throw new Error("CBORError: Encountered unsafe integer outside of valid CBOR range.");t=1,e=-(e+1n)}if(e<0x100000000n)return writeTypeAndLength(t,Number(e));writeUint8(t<<5|27),writeBigUint64(e)}(e);case"number":if(Math.floor(e)===e){if(0<=e&&e<=POW_2_53)return writeTypeAndLength(0,e);if(-POW_2_53<=e&&e<0)return writeTypeAndLength(1,-(e+1))}return writeUint8(251),function writeFloat64(e){commitWrite(prepareWrite(8).setFloat64(a,e))}(e);case"string":{const t=[],n=e.length;for(let r=0;r<n;++r){let n=e.charCodeAt(r);n<128?t.push(n):n<2048?(t.push(192|n>>6),t.push(128|63&n)):n<55296||n>=57344?(t.push(224|n>>12),t.push(128|n>>6&63),t.push(128|63&n)):(n=(1023&n)<<10,n|=1023&e.charCodeAt(++r),n+=65536,t.push(240|n>>18),t.push(128|n>>12&63),t.push(128|n>>6&63),t.push(128|63&n))}return writeTypeAndLength(3,t.length),writeUint8Array(t)}default:{let t;if(Array.isArray(e))!function writeArray(e){const t=a,n=e.length;let r=0;writeTypeAndLength(4,n);const i=a;for(let t=0;t<n;t+=1){const n=replacerFunction(t,e[t]);n!==OMIT_VALUE&&(encodeItem(n),r+=1)}if(n>r){const e=o.slice(i,a);a=t,writeTypeAndLength(4,r),writeUint8Array(e)}}(e);else if(e instanceof Uint8Array)writeVarUint(kCborTagUint8,kCborTag<<5),writeTypeAndLength(2,e.length),writeUint8Array(e);else if(e instanceof Int8Array)writeVarUint(kCborTagInt8,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(e instanceof Uint16Array)writeVarUint(kCborTagUint16,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(e instanceof Int16Array)writeVarUint(kCborTagInt16,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(e instanceof Uint32Array)writeVarUint(kCborTagUint32,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(e instanceof Int32Array)writeVarUint(kCborTagInt32,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(e instanceof Float32Array)writeVarUint(kCborTagFloat32,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(e instanceof Float64Array)writeVarUint(kCborTagFloat64,kCborTag<<5),writeTypeAndLength(2,e.byteLength),writeUint8Array(new Uint8Array(e.buffer));else if(ArrayBuffer.isView(e))t=new Uint8Array(e.buffer),writeTypeAndLength(2,t.length),writeUint8Array(t);else if(e instanceof ArrayBuffer||"function"==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)t=new Uint8Array(e),writeTypeAndLength(2,t.length),writeUint8Array(t);else if(e instanceof TaggedValue)writeVarUint(e.tag,192),encodeItem(e.value);else if(e instanceof SimpleValue)writeTypeAndLength(7,e.value);else if(e instanceof Sequence){if(0!==a)throw new Error("CBORError: A CBOR Sequence may not be nested.");const t=e.size;for(let n=0;n<t;n+=1)encodeItem(e.get(n))}else!function writeDictionary(e){const t=[],n=a;let r=a,i=0,s=0;if(e instanceof Map){i=e.size,writeTypeAndLength(5,i),r=a;for(const[n,r]of e.entries()){const e=replacerFunction(n,r);if(e===OMIT_VALUE)continue;let i=a;encodeItem(n);const c=o.slice(i,a);i=a,encodeItem(e);const d=o.slice(i,a);s+=1,t.push([c,d])}}else{const n=Object.keys(e);i=n.length,writeTypeAndLength(5,i),r=a;for(let r=0;r<i;r+=1){const i=n[r],c=replacerFunction(i,e[i]);if(c===OMIT_VALUE)continue;let d=a;encodeItem(i);const l=o.slice(d,a);d=a,encodeItem(c);const u=o.slice(d,a);s+=1,t.push([l,u])}}function sortEncodedKeys(e){a=n,writeTypeAndLength(5,s),t.sort((([e],[t])=>lexicographicalCompare(e,t)));for(let n=0;n<e;n+=1){const[e,r]=t[n];writeUint8Array(e),writeUint8Array(r)}}if(i>s){const e=t.length;if(e>1)sortEncodedKeys(e);else{const e=o.slice(r,a);a=n,writeTypeAndLength(5,s),writeUint8Array(e)}}else{const e=t.length;e>1&&sortEncodedKeys(e)}}(e)}}}}if(encodeItem(replacerFunction(EMPTY_KEY,e)),"slice"in r)return r.slice(0,a);const s=new ArrayBuffer(a),c=new DataView(s);for(let e=0;e<a;++e)c.setUint8(e,i.getUint8(e));return s}function binarify(e,t){return encode(e,t)}const CBOR$1={binarify:binarify,decode:decode,encode:encode,parse:parse};class CBOR{static encode(e,t){const n=CBOR$1.encode(e,t);return new Uint8Array(n)}static decode(e,t){const n=e.buffer;return CBOR$1.decode(n,t)}}class DocumentID{get value(){let e=this["@ditto.value"];return void 0===e&&(e=CBOR.decode(this["@ditto.cbor"]),this["@ditto.value"]=e),e}constructor(e,t=!1,n=!1){const r=t?e:CBOR.encode(e),i=n?r:validateDocumentIDCBOR(r);if(!i)throw new Error(`Can't create DocumentID, passed in value is not valid: ${e}`);this.isValidated=!n,this["@ditto.cbor"]=i}equals(e){const t=this["@ditto.cbor"],n=e["@ditto.cbor"];if(t===n)return!0;if(!(t instanceof Uint8Array))return!1;if(!(n instanceof Uint8Array))return!1;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e+=1)if(t[e]!==n[e])return!1;return!0}toString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithoutQuotes")}toBase64String(){return mapFFIErrors((()=>base64encode(this["@ditto.cbor"],"Padded")))}toQueryCompatibleString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithQuotes")}toCBOR(){return this["@ditto.cbor"]}}function validateDocumentIDValue(e){if(void 0===e)throw new Error(`Invalid document ID: ${e}`);return e}function validateDocumentIDCBOR(e){const t=validateDocumentID(e);return null!=t?t:e}var _a;const DEBUG_TYPE_NAMES=[],DEBUG_ALL_TYPES=!1;class Handle{constructor(e,t,n){this.isClosed=!1,this.isFinalized=!1,this.isUnregistered=!1,this.bridge=e,this.objectWeakRef=new WeakRef(t),this.pointer=n}get type(){return this.bridge.type}deref(){if(this.isClosed)throw new Error("Bridging error: can't get pointer for an object that has been closed.");if(this.isFinalized)throw new Error("Bridging error: can't get pointer for an object that has been finalized.");if(this.isUnregistered)throw new Error("Bridging error: can't get pointer for an object that has been unregistered.");return this.pointer}derefOrNull(){var e;return this.isClosed||this.isFinalized||this.isUnregistered?null:null!==(e=this.pointer)&&void 0!==e?e:null}object(){const e=this.objectWeakRef.deref();if(null==e)throw new Error(`Bridging error: ${this.bridge.type.name} object has been garbage collected.`);if(this.isClosed)throw new Error(`Bridging error: ${this.bridge.type.name} object has been closed.`);if(this.isUnregistered)throw new Error(`Bridging error: ${this.bridge.type.name} object has been unregistered.`);return e}objectOrNull(){var e;return null!==(e=this.objectWeakRef.deref())&&void 0!==e?e:null}toString(){const e=this.derefOrNull();return`{ Handle | type: ${this.bridge.type}, object: ${this.objectWeakRef.deref()}, FFI address: ${null==e?void 0:e.addr}, FFI type: ${null==e?void 0:e.type} }`}bridgeWillClose(){this.isClosed=!0}bridgeDidClose(){this.pointer=null}bridgeWillFinalize(){this.isFinalized=!0}bridgeDidFinalize(){this.pointer=null}bridgeWillUnregister(){this.isUnregistered=!0}bridgeDidUnregister(){this.pointer=null}}class Handles{constructor(e,t){this.handles=t.map((t=>e.handleFor(t)))}deref(){return this.handles.map((e=>e.deref()))}}class Bridge{constructor(e){this.internalType=null,this.release=e,this.handlesByAddress={},this.handlesByObject=new WeakMap,this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this)),_a.all.push(new WeakRef(this))}get type(){if(null==this.internalType)throw new Error("Bridge type has not been registered yet.");return this.internalType}registerType(e){if(this.internalType!==e){if(this.internalType)throw new Error(`Can't register bridged type '${e.name}', another type was already registered: ${this.internalType}`);this.internalType=e}}handleFor(e){const t=this.handlesByObject.get(e);if(null==t)throw new Error(`Bridging error: ${this.type.name} object is not currently registered in this bridge.`);return t}handlesFor(e){return new Handles(this,e)}objectFor(e){const t=this.handlesByAddress[e.addr];if(t){if(t.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${t.type} but this bridge is configured for ${this.type}`);return t.object()}}bridge(e,t){const n=this.objectFor(e);if(n)return n;let r;if(t||(t=()=>Reflect.construct(this.type,[])),"function"==typeof t){if(r=t(),!(r instanceof this.type))throw new Error(`Can't bridge, expected passed in create function to return a ${this.type.name} object but got: ${r}`)}else r=t;return this.register(r,e),r}register(e,t){const n=e.constructor;if(n!==this.type)throw new Error(`Can't register, bridge is configured for type ${this.type.name} but passed in object is of type ${n.name}`);const r=this.handlesByObject.get(e),i=r?r.pointer:null;if(null!=i&&null!=r)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${r.object()}`);if(null!=i&&null==r)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no handle entry: ${n.name} at ${i.type} ${i.addr}`);if(null==i&&null!=r)throw new Error(`Internal inconsistency, trying to register an object which has a handle entry but no associated pointer: ${n.name} ${e}`);const o=new Handle(this,e,t);this.handlesByAddress[t.addr]=o,this.handlesByObject.set(e,o),this.finalizationRegistry.register(e,o,e),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge REGISTERED a new instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}unregister(e){const t=e.constructor,n=this.type;if(t!==n)throw new Error(`Can't unregister, bridge is configured for type ${n.name} but passed in object is of type ${t.name}`);const r=this.handlesByObject.get(e);if(null==r)throw new Error(`Can't unregister, object has not been registered before: ${e}`);if(r.type!==n)throw new Error(`Internal inconsistency, trying to unregister an object that has a handle with a different type than that of the bridge: ${r}`);if(r.objectOrNull()!==e)throw new Error(`Internal inconsistency, trying to unregister an object whose associated handle holds a different object: ${r}`);if(r.isClosed)throw new Error(`Can't unregister, object has been closed before: ${e}`);if(r.isFinalized)throw new Error(`Can't unregister, object has been finalized before: ${e}`);if(r.isUnregistered)throw new Error(`Can't unregister, object has been unregistered already: ${e}`);r.bridgeWillUnregister(),this.finalizationRegistry.unregister(e),delete this.handlesByAddress[r.pointer.addr],this.handlesByObject.delete(e),r.bridgeDidUnregister(),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge UNREGISTERED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}unregisterAll(){DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Unregistering ALL bridged instances of type ${this.type.name}.`);for(const e of Object.values(this.handlesByAddress)){const t=e.object();t&&this.unregister(t)}}async close(e){const t=e.constructor,n=this.type;if(t!==n)throw new Error(`Can't close, bridge is configured for type ${n.name} but passed in object is of type ${t.name}`);const r=this.handlesByObject.get(e);if(null==r)throw new Error(`Can't close an object that has not been registered before: ${e}`);if(r.type!==n)throw new Error(`Internal inconsistency, trying to close an object that has a handle with a different type than that of the bridge: ${r}`);if(r.isUnregistered)throw new Error("Can't close object, object has been unregistered.");if(r.isFinalized)throw new Error("Internal inconsistency, trying to close an object that has already been finalized.");if(r.isClosed)return;const i=r.pointer;if(!i)throw new Error("Internal inconsistency, trying to close an object whose pointer is null.");r.bridgeWillClose(),delete this.handlesByAddress[i.addr],await this.release(i),r.bridgeDidClose(),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge CLOSED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}get count(){return Object.keys(this.handlesByAddress).length}async finalize(e){if(e.isFinalized)throw new Error("Internal inconsistency, trying to finalize an object that has already been finalized.");if(e.isUnregistered)throw new Error("Internal inconsistency, trying to finalize an object that has been unregistered before.");if(e.bridgeWillFinalize(),!e.isClosed){const t=e.pointer;if(!t)throw new Error("Internal inconsistency, trying to finalize an object whose pointer is null.");delete this.handlesByAddress[t.addr],await this.release(t)}e.bridgeDidFinalize(),DEBUG_TYPE_NAMES.includes(this.type.name)&&Logger.debug(`[VERBOSE] Bridge FINALIZED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}}_a=Bridge,Bridge.all=[],Bridge.attachment=new _a(freeAttachmentHandle),Bridge.connectionRequest=new _a(connectionRequestFree),Bridge.document=new _a(documentFree),Bridge.mutableDocument=new _a(documentFree),Bridge.queryResult=new _a(queryResultFree),Bridge.queryResultItem=new _a(queryResultItemFree),Bridge.staticTCPClient=new _a(staticTCPClientFreeHandle),Bridge.websocketClient=new _a(websocketClientFreeHandle),Bridge.ditto=new _a((async e=>{await dittoClearPresenceCallback(e),await dittoShutdown(e),dittoFree(e)}));class Attachment{get id(){return this.token.id}get len(){return this.token.len}get metadata(){return this.token.metadata}data(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return this.ditto.deferCloseAsync((async()=>{{const e=Bridge.attachment.handleFor(this);return await dittoGetCompleteAttachmentData(t.deref(),e.deref())}}))}getData(){return this.data()}copyToPath(e){const t=this.ditto;return Bridge.ditto.handleFor(t),this.ditto.deferCloseAsync((async()=>{throw new Error("Can't copy attachment to path, not available when running in the browser.")}))}constructor(e,t){this.ditto=e,this.token=t}}function validateAttachmentMetadata(e){if("object"!=typeof e)throw new DittoError("store/failed-to-create-attachment",`Invalid attachment metadata: expected a value of type object but got ${typeof e}.`);for(const t in e)if("string"!=typeof e[t])throw new DittoError("store/failed-to-create-attachment",`Invalid attachment metadata: metadata values must be strings but key '${t}' has a value of type ${typeof e[t]}.`)}function augmentJSONValue(e,t,n){if(e&&"object"==typeof e){if(Array.isArray(e))return e.map(((e,r)=>augmentJSONValue(e,t,`${n}[${r}]`)));if(e[DittoCRDTTypeKey]===DittoCRDTType.counter)return Counter["@ditto.create"](t,n,e._value);if(e[DittoCRDTTypeKey]===DittoCRDTType.register)return Register["@ditto.create"](t,n,e._value);if(e[DittoCRDTTypeKey]===DittoCRDTType.attachment)return new AttachmentToken(e);for(const[r,i]of Object.entries(e))e[r]=augmentJSONValue(i,t,`${n}['${r}']`);return e}return e}function desugarJSObject(e){if(e&&"object"==typeof e){if(Array.isArray(e))return e.map(((e,t)=>desugarJSObject(e)));if(e instanceof DocumentID)return e.value;if(e instanceof Counter){const t={};return t[DittoCRDTTypeKey]=DittoCRDTType.counter,t._value=e.value,t}if(e instanceof Register){const t={};return t[DittoCRDTTypeKey]=DittoCRDTType.register,t._value=e.value,t}if(e instanceof Attachment){const t={_id:e.token.idBytes,_len:e.token.len,_meta:e.token.metadata};return t[DittoCRDTTypeKey]=DittoCRDTType.attachment,t}{const t={};for(const[n,r]of Object.entries(e))t[n]=desugarJSObject(r);return t}}return checkForUnsupportedValues(e),e}function checkForUnsupportedValues(e){if(Number.isNaN(e)||e===1/0||e===-1/0)throw new Error("Non-finite float values are not supported")}class UpdateResult{static set(e,t,n){return new UpdateResult("set",e,t,n,void 0)}static incremented(e,t,n){return new UpdateResult("incremented",e,t,void 0,n)}static removed(e,t){return new UpdateResult("removed",e,t,void 0,void 0)}constructor(e,t,n,r,i){this.type=e,this.docID=t,this.path=n,void 0!==r&&(this.value=r),void 0!==i&&(this.amount=i)}}const defaultDittoCloudDomain="cloud.ditto.live";function defaultAuthURL(e){return`https://${e}.${defaultDittoCloudDomain}`}function defaultDittoCloudURL(e){return`wss://${e}.${defaultDittoCloudDomain}`}function validateNumber(e,t={}){var n;const r=null!==(n=t.errorMessagePrefix)&&void 0!==n?n:"Number validation failed:",i=!!t.integer,o=t.min,a=t.max,s=t.minX,c=t.maxX;if("number"!=typeof e)throw new Error(`${r} '${e}' is not a number.`);if(i&&Math.floor(e)!==e)throw new Error(`${r} '${e}' is not an integer.`);if(void 0!==o&&e<o)throw new Error(`${r} '${e}' must be >= ${o}.`);if(void 0!==a&&e>a)throw new Error(`${r} '${e}' must be <= ${a}.`);if(void 0!==s&&e<=s)throw new Error(`${r} '${e}' must be > ${s}.`);if(void 0!==c&&e>=c)throw new Error(`${r} '${e}' must be < ${c}.`);return e}function validateQuery(e,t={}){var n;const r=null!==(n=t.errorMessagePrefix)&&void 0!==n?n:"Query validation failed,";if("string"!=typeof e)throw new Error(`${r} query is not a string: ${e}`);if(""===e)throw new Error(`${r} query is an empty string.`);const i=e.trim();if(""===i)throw new Error(`${r} query contains only whitespace characters.`);return i}function generateEphemeralToken(){let e,t=new Uint16Array(16);e=crypto,e.getRandomValues(t);return Array.from(t).map((e=>e.toString(16))).join("")}function customInspectRepresentation(e,t){return void 0===t?`${e.constructor.name} ${JSON.stringify({value:e.value},null,2)}`:`${e.constructor.name} ${t({value:e.value})}`}function sleep(e){return new Promise(((t,n)=>{setTimeout(t,e)}))}async function step(e){return await sleep(0),e()}const performAsyncToWorkaroundNonAsyncFFIAPI=step,regularKeyPattern=/\.([A-Za-z_]\w*)/.source,subscriptIndexPattern=/\[(\d+)\]/.source,subscriptSingleQuoteKeyPattern=/\[\'(.+?)\'\]/.source,subscriptDoubleQuoteKeyPattern=/\[\"(.+?)\"\]/.source,validKeyPathPattern=`((${regularKeyPattern})|(${subscriptIndexPattern})|(${subscriptSingleQuoteKeyPattern})|(${subscriptDoubleQuoteKeyPattern}))*`,regularKeyRegExp=new RegExp(`^${regularKeyPattern}`),subscriptIndexRegExp=new RegExp(`^${subscriptIndexPattern}`),subscriptSingleQuoteKeyRegExp=new RegExp(`^${subscriptSingleQuoteKeyPattern}`),subscriptDoubleQuoteKeyRegExp=new RegExp(`^${subscriptDoubleQuoteKeyPattern}`),validKeyPathRegExp=new RegExp(`^${validKeyPathPattern}$`);class KeyPath{static withLeadingDot(e){if("number"==typeof e)return e;if("string"!=typeof e)throw new Error(`Key-path must be a string or a number but is ${typeof e}: ${e}`);return"string"==typeof e&&!!e.match(/^[A-Za-z_]/)?`.${e}`:e}static withoutLeadingDot(e){if("number"==typeof e)return e;if("string"!=typeof e)throw new Error(`Key-path must be a string or a number but is ${typeof e}: ${e}`);return"string"==typeof e&&!!e.match(/^\./)?e.slice(1):e}static validate(e,t={}){var n;const r=null!==(n=t.isInitial)&&void 0!==n&&n;if("number"==typeof e)return Math.floor(Math.abs(e));if("string"!=typeof e)throw new Error(`Key-path must be a string or a number but is ${typeof e}: ${e}`);const i=this.withLeadingDot(e);if(!validKeyPathRegExp.test(i))throw new Error(`Key-path is not valid: ${e}`);return r?e:i}static evaluate(e,t,n={}){var r;const i=null!==(r=n.stopAtLastContainer)&&void 0!==r&&r,o={keyPath:e,object:t,options:{...n},coveredPath:null,nextPathComponent:null,remainingPath:e,value:t};return function recurse(e,t){if(""===t)return o.value=e,o;const{nextPathComponentRaw:n,nextPathComponent:r,remainingPath:a}=function advance(e){if("number"==typeof e)return{nextPathComponentRaw:e,nextPathComponent:e,remainingPath:""};if("string"!=typeof e)throw new Error(`Can't return value at given keyPath, expected keyPath to be a string or a number but got ${typeof e}: ${e}`);const t=e.match(regularKeyRegExp);if(null!==t){const n=t[0],r=t[1];return{nextPathComponentRaw:n,nextPathComponent:r,remainingPath:e.slice(r.length+1)}}const n=e.match(subscriptIndexRegExp);if(null!==n){const t=n[0],r=n[1];return{nextPathComponentRaw:t,nextPathComponent:parseInt(r),remainingPath:e.slice(r.length+2)}}const r=e.match(subscriptSingleQuoteKeyRegExp);if(null!==r){const t=r[0],n=r[1];return{nextPathComponentRaw:t,nextPathComponent:n,remainingPath:e.slice(n.length+4)}}const i=e.match(subscriptDoubleQuoteKeyRegExp);if(null!==i){const t=i[0],n=i[1];return{nextPathComponentRaw:t,nextPathComponent:n,remainingPath:e.slice(n.length+4)}}throw new Error(`Can't return value at keyPath because the following part of the keyPath is invalid: ${e}`)}(t);return o.nextPathComponent=r,o.remainingPath=a,null===o.coveredPath||"number"==typeof n?o.coveredPath=n:o.coveredPath+=n,""===a&&i?(o.value=e,o):recurse(e[r],a)}(t,this.withLeadingDot(e))}constructor(){}}class DocumentPath{at(e){if("string"==typeof e){const t=e,n=KeyPath.validate(t),r=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new DocumentPath(this.document,r,!1)}if("number"==typeof e){const t=validateNumber(e,{integer:!0,min:0,errorMessagePrefix:"DocumentPath.at() validation failed index:"});return new DocumentPath(this.document,`${this.path}[${t.toString()}]`,!1)}throw new Error(`Can't return document path at key-path or index, string or number expected but got ${typeof e}: ${e}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const e=this.underlyingValueForPathType("Counter");return void 0!==e?Counter["@ditto.create"](null,this.path,e):null}get register(){const e=this.underlyingValueForPathType("Register");return void 0!==e?Register["@ditto.create"](null,this.path,e):null}get attachmentToken(){const e=this.underlyingValueForPathType("Attachment");return void 0!==e?new AttachmentToken(e):null}constructor(e,t,n){this.document=e,this.path=n?KeyPath.validate(t,{isInitial:!0}):t}underlyingValueForPathType(e){const t=this.path,n=this.document,r=documentGetCBORWithPathType(Bridge.document.handleFor(n).deref(),t,e);return null!==r.cbor?CBOR.decode(r.cbor):void 0}}class MutableDocumentPath{at(e){if("string"==typeof e){const t=e,n=KeyPath.validate(t),r=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new MutableDocumentPath(this.mutableDocument,r,!1)}if("number"==typeof e){const t=validateNumber(e,{integer:!0,min:0,errorMessagePrefix:"MutableDocumentPath.at() validation failed index:"});return new MutableDocumentPath(this.mutableDocument,`${this.path}[${t.toString()}]`,!1)}throw new Error(`Can't return mutable document path at key-path or index, string or number expected but got ${typeof e}: ${e}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const e=this.underlyingValueForPathType("Counter");return void 0!==e?Counter["@ditto.create"](this.mutableDocument,this.path,e):null}get register(){const e=this.underlyingValueForPathType("Register");return void 0!==e?Register["@ditto.create"](this.mutableDocument,this.path,e):null}get attachmentToken(){const e=this.underlyingValueForPathType("Attachment");return void 0!==e?new AttachmentToken(e):null}set(e,t){return this["@ditto.set"](e,t)}remove(){return this["@ditto.remove"]()}constructor(e,t,n){this.mutableDocument=e,this.path=n?KeyPath.validate(t,{isInitial:!0}):t}underlyingValueForPathType(e){const t=this.path,n=this.mutableDocument,r=documentGetCBORWithPathType(Bridge.mutableDocument.handleFor(n).deref(),t,e);return null!==r.cbor?CBOR.decode(r.cbor):void 0}"@ditto.increment"(e){documentIncrementCounter(Bridge.mutableDocument.handleFor(this.mutableDocument).deref(),this.path,e);const t=UpdateResult.incremented(this.mutableDocument.id,this.path,e);this.recordUpdateResult(t)}"@ditto.set"(e,t){const n=Bridge.mutableDocument.handleFor(this.mutableDocument),r=desugarJSObject(e),i=CBOR.encode(r);t?documentSetCBORWithTimestamp(n.deref(),this.path,i,0):documentSetCBOR(n.deref(),this.path,i);const o=augmentJSONValue(CBOR.decode(i),this.mutableDocument,this.path),a=UpdateResult.set(this.mutableDocument.id,this.path,o);this.recordUpdateResult(a)}"@ditto.remove"(){documentRemove(Bridge.mutableDocument.handleFor(this.mutableDocument).deref(),this.path),this.updateInMemory(((e,t)=>{Array.isArray(e)&&"number"==typeof t?e.splice(t,1):delete e[t]}));const e=UpdateResult.removed(this.mutableDocument.id,this.path);this.recordUpdateResult(e)}updateInMemory(e){const t=this.mutableDocument.value,n=KeyPath.evaluate(this.path,t,{stopAtLastContainer:!0});e(n.value,n.nextPathComponent)}recordUpdateResult(e){const t=this.mutableDocument["@ditto.updateResults"].slice();t.push(e),Object.freeze(t),this.mutableDocument["@ditto.updateResults"]=t}}const CUSTOM_INSPECT_SYMBOL$1=Symbol.for("nodejs.util.inspect.custom");class Document{static hash(e){return documentsHash(documentsFrom(e).map((e=>Bridge.document.handleFor(e))).map((e=>e.deref())))}static hashMnemonic(e){const t=documentsFrom(e);return documentsHashMnemonic(Bridge.document.handlesFor(t).deref())}get id(){let e=this["@ditto.id"];if(void 0===e){const t=documentID(Bridge.document.handleFor(this).deref());e=new DocumentID(t,!0),this["@ditto.id"]=e}return e}get path(){return new DocumentPath(this,"",!1)}get value(){let e=this["@ditto.value"];return void 0===e&&(e=this.path.value,this["@ditto.value"]=e),e}at(e){return this.path.at(e)}constructor(){}static idCBOR(e){return documentID(Bridge.document.handleFor(e).deref())}static canonicalizedIDCBOR(e){return validateDocumentIDCBOR(e)}static isIDCBORCanonical(e){return e===this.canonicalizedIDCBOR(e)}toString(){return`${this.constructor.name}(${this.id})`}[CUSTOM_INSPECT_SYMBOL$1](e,t,n){return customInspectRepresentation(this,n)}}class MutableDocument{get id(){let e=this["@ditto.id"];if(void 0===e){const t=documentID(Bridge.mutableDocument.handleFor(this).deref());e=new DocumentID(t,!0),this["@ditto.id"]=e}return e}get path(){return new MutableDocumentPath(this,"",!1)}get value(){return this.path.value}at(e){return this.path.at(e)}constructor(){this["@ditto.updateResults"]=[]}static idCBOR(e){return documentID(Bridge.mutableDocument.handleFor(e).deref())}toString(){return`${this.constructor.name}(${this.id})`}[CUSTOM_INSPECT_SYMBOL$1](e,t,n){return customInspectRepresentation(this,n)}}function documentsFrom(e){if(!e)return[];if(e instanceof Document)return[e];if(e instanceof Array)return e;throw new Error(`Expected null, a single document, or an array of documents but got value of type ${typeof e}: ${e}`)}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR,MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;class UpdateResultsMap{get(e){const t=(e instanceof DocumentID?e:new DocumentID(e)).toString();return this.updateResultsByDocumentIDString[t]}keys(){return this.documentIDs.slice()}constructor(e,t){const n=e.map((e=>e.toString())).sort().join(", ");if(n!==Object.keys(t).sort().join(", "))throw new Error("Internal inconsistency, can't construct update results map, documentIDs must all be keys in update results (by document ID string)");this.documentIDs=e.slice(),this.updateResultsByDocumentIDString={...t}}}class BasePendingCursorOperation{sort(e,t="ascending"){return this.orderBys.push({query:e,direction:"ascending"===t?"Ascending":"Descending"}),this}offset(e){if(e<0)throw new Error(`Can't offset by '${e}', offset must be >= 0`);if(!Number.isFinite(e))throw new Error(`Can't offset by '${e}', offset must be a finite number`);if(Number.isNaN(e))throw new Error(`Can't offset by '${e}', offset must be a valid number`);if(e!==Math.round(e))throw new Error(`Can't offset by '${e}', offset must be an integer number`);return this.currentOffset=e,this}limit(e){if(e<-1)throw new Error(`Can't limit to '${e}', limit must be >= -1 (where -1 means unlimited)`);if(!Number.isFinite(e))throw new Error(`Can't limit to '${e}', limit must be a finite number`);if(Number.isNaN(e))throw new Error(`Can't limit to '${e}', limit must be a valid number`);if(e!==Math.round(e))throw new Error(`Can't limit to '${e}', limit must be an integer number`);return this.currentLimit=e,this}async exec(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.query;return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionExecQueryStr(t.deref(),this.collection.name,null,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((e=>Bridge.document.bridge(e)))}))}async updateWithTransaction(e,t){const n=this.collection.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const n=this.query,i=await collectionExecQueryStr(r.deref(),this.collection.name,t,n,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset),o=i.map((e=>Bridge.mutableDocument.bridge(e,(()=>new MutableDocument))));e(o);const a=[],s={};for(const e of o){const t=e.id,n=t.toString(),r=e["@ditto.updateResults"];if(s[n])throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${n}`);a.push(t),s[n]=r,Bridge.mutableDocument.unregister(e)}return await collectionUpdateMultiple(r.deref(),this.collection.name,t,i),new UpdateResultsMap(a,s)}))))}constructor(e,t,n){if(this.currentLimit=-1,this.currentOffset=0,this.orderBys=[],this.query=validateQuery(e),this.queryArgs=t?Object.freeze({...t}):null,this.collection=n,null==t)this.queryArgsCBOR=null;else{const e=desugarJSObject(t);this.queryArgsCBOR=CBOR.encode(e)}}then(e,t){return this.exec().then(e,t)}}class BasePendingIDSpecificOperation{async exec(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await readTransaction(t.deref()),n=await collectionGet(t.deref(),this.collection.name,this.documentIDCBOR,e);let r;return n&&(r=Bridge.document.bridge(n)),readTransactionFree(e),r}))))}constructor(e,t){this.documentID=e,this.collection=t,this.documentIDCBOR=e.toCBOR()}then(e,t){return this.exec().then(e,t)}get query(){return`_id == ${this.documentID.toQueryCompatibleString()}`}}class ConnectionRequest{get peerKeyString(){return connectionRequestPeerKeyString(this.deref())}get peerMetadata(){return JSON.parse(this.peerMetadataJSONString)}get peerMetadataJSONString(){return connectionRequestPeerMetadataJSON(this.deref())}get identityServiceMetadata(){return JSON.parse(this.identityServiceMetadataJSONString)}get identityServiceMetadataJSONString(){return connectionRequestIdentityServiceMetadataJSON(this.deref())}get connectionType(){return connectionRequestConnectionType(this.deref())}toString(){return`ConnectionRequest(${this.peerKeyString} via ${this.connectionType})`}[Symbol.for("nodejs.util.inspect.custom")](e,t,n){return this.toString()}deref(){return Bridge.connectionRequest.handleFor(this).deref()}}class ObserverManager{constructor(e,t={}){var n,r,i,o;const a=null!==(n=t.keepAlive)&&void 0!==n?n:null,s=null!==(r=t.register)&&void 0!==r?r:null,c=null!==(i=t.unregister)&&void 0!==i?i:null,d=null!==(o=t.process)&&void 0!==o?o:null;this.id=e,this.keepAlive=a,this.isClosed=!1,this.isRegistered=!1,this.callbacksByToken={},null!==s&&(this.register=s),null!==c&&(this.unregister=c),null!==d&&(this.process=d)}addObserver(e){var t;if(this.isClosed)throw new Error(`Internal inconsistency, can't add '${this.id}' observer, observer mananger close()-ed.`);this.registerIfNeeded();const n=generateEphemeralToken();return this.callbacksByToken[n]=e,null===(t=this.keepAlive)||void 0===t||t.retain(`${this.id}.${n}`),n}removeObserver(e){var t;const n=this.callbacksByToken[e];if(void 0===n)throw new Error(`Can't remove '${this.id}' observer, token '${e}' has never been registered before.`);null!==n&&(this.callbacksByToken[e]=null,null===(t=this.keepAlive)||void 0===t||t.release(`${this.id}.${e}`),this.unregisterIfNeeded())}hasObserver(e){return void 0!==this.callbacksByToken[e]}notify(...e){if(this.isClosed)return;const t=this.process(...e);for(const e in this.callbacksByToken){const n=this.callbacksByToken[e];n&&n(...t)}}close(){this.isClosed=!0;for(const e in this.callbacksByToken)this.removeObserver(e)}register(e){}unregister(){}process(...e){return e}hasObservers(){return Object.keys(this.callbacksByToken).length>0}registerIfNeeded(){if(!this.isRegistered){const e=new WeakRef(this);this.isRegistered=!0,this.register((function(...t){const n=e.deref();n&&n.notify(...t)}))}}unregisterIfNeeded(){!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,this.unregister())}}class Authenticator{get status(){return this._status}loginWithToken(e,t){throw new Error("Authenticator.loginWithToken() is abstract and must be implemented by subclasses.")}loginWithUsernameAndPassword(e,t,n){throw new Error("Authenticator.loginWithUsernameAndPassword() is abstract and must be implemented by subclasses.")}logout(e){throw new Error("Authenticator.logout() is abstract and must be implemented by subclasses.")}observeStatus(e){const t=this.observerManager.addObserver(e);return new Observer(this.observerManager,t,{stopsWhenFinalized:!0})}constructor(e){this.keepAlive=e,this._status={isAuthenticated:!1,userID:null},this.loginSupported=!1,this.observerManager=new ObserverManager("AuthenticationStatusObservation",{keepAlive:e})}"@ditto.authenticationExpiring"(e){throw new Error("Authenticator['@ditto.authenticationExpiring']() is abstract and must be implemented by subclasses.")}"@ditto.authClientValidityChanged"(e,t){throw new Error("Authenticator['@ditto.authClientValidityChanged']() is abstract and must be implemented by subclasses.")}close(){this.observerManager.close()}}class OnlineAuthenticator extends Authenticator{async loginWithToken(e,t){const n=this.ditto.deref();if(!n)return;const r=Bridge.ditto.handleFor(n).derefOrNull();return r?n.deferCloseAsync((async()=>{await dittoAuthClientLoginWithToken(r,e,t)})):void 0}async loginWithUsernameAndPassword(e,t,n){const r=this.ditto.deref();if(!r)return;const i=Bridge.ditto.handleFor(r).derefOrNull();return i?r.deferCloseAsync((async()=>{await dittoAuthClientLoginWithUsernameAndPassword(i,e,t,n)})):void 0}async logout(e){const t=this.ditto.deref();if(!t)return;const n=Bridge.ditto.handleFor(t).derefOrNull();return n?t.deferCloseAsync((async()=>{await dittoAuthClientLogout(n),t.stopSync(),null==e||e(t)})):void 0}constructor(e,t,n){super(e),this.loginSupported=!0,this._status={isAuthenticated:!1,userID:null},this.ditto=new WeakRef(t),this.authenticationHandler=n,this.updateAndNotify(!1)}"@ditto.authenticationExpiring"(e){const t=this.authenticationHandler;e>0?t.authenticationExpiringSoon(this,e):t.authenticationRequired(this)}"@ditto.authClientValidityChanged"(e,t){this.updateAndNotify(!0)}updateAndNotify(e){var t;const n=this.ditto.deref();if(!n)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const r=Bridge.ditto.handleFor(n).derefOrNull();if(!r)return void Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");const i=this.status.isAuthenticated,o=this.status.userID,a=dittoAuthClientIsWebValid(r),s=dittoAuthClientUserID(r),c={isAuthenticated:a,userID:s};if(this._status=c,e){!!i==!!a&&o===s||(null===(t=this.authenticationHandler.authenticationStatusDidChange)||void 0===t||t.call(this.authenticationHandler,this),this.observerManager.notify(c))}}}class NotAvailableAuthenticator extends Authenticator{async loginWithToken(e,t){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}async loginWithUsernameAndPassword(e,t,n){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}logout(e){throw new Error("Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}"@ditto.authenticationExpiring"(e){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${this}`)}"@ditto.authClientValidityChanged"(e,t){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authClientValidityChanged() was called on authenticator: ${this}`)}}const IdentityTypesRequiringOfflineLicenseToken=["manual","sharedKey","offlinePlayground"];function transportConfigFromDeserializable(e){const t=e.peer_to_peer,n=t.bluetooth_le.enabled,r=t.awdl.enabled,i=t.lan,o=i.enabled,a=i.mdns_enabled,s=i.multicast_enabled,c=e.connect,d=c.tcp_servers,l=c.websocket_urls,u=c.retry_interval,_=e.listen,g=_.tcp,h=g.enabled,f=g.interface_ip,b=g.port,m=_.http,y=m.enabled,w=m.interface_ip,p=m.port,v=m.static_content_path,I=m.websocket_sync,O=m.tls_key_path,k=m.tls_certificate_path,j=e.global,C=j.sync_group,M=j.routing_hint,E=new TransportConfig;return E.peerToPeer.bluetoothLE.isEnabled=n,E.peerToPeer.awdl.isEnabled=r,E.peerToPeer.lan.isEnabled=o,E.peerToPeer.lan.isMdnsEnabled=a,E.peerToPeer.lan.isMulticastEnabled=s,E.connect.tcpServers=d,E.connect.websocketURLs=l,E.connect.retryInterval=u,E.listen.tcp.isEnabled=h,E.listen.tcp.interfaceIP=f,E.listen.tcp.port=b,E.listen.http.isEnabled=y,E.listen.http.interfaceIP=w,E.listen.http.port=p,E.listen.http.staticContentPath=v,E.listen.http.websocketSync=I,E.listen.http.tlsKeyPath=O,E.listen.http.tlsCertificatePath=k,E.global.syncGroup=C,E.global.routingHint=M,E}function transportConfigToSerializable(e){const t=e.peerToPeer,n=e.connect,r=e.listen,i=e.global,o={peer_to_peer:{bluetooth_le:{enabled:t.bluetoothLE.isEnabled},awdl:{enabled:t.awdl.isEnabled},lan:{enabled:t.lan.isEnabled,mdns_enabled:t.lan.isMdnsEnabled,multicast_enabled:t.lan.isMulticastEnabled}},connect:{tcp_servers:n.tcpServers,websocket_urls:n.websocketURLs,retry_interval:n.retryInterval},listen:{tcp:{enabled:r.tcp.isEnabled,interface_ip:r.tcp.interfaceIP,port:r.tcp.port},http:{enabled:r.http.isEnabled,interface_ip:r.http.interfaceIP,port:r.http.port,websocket_sync:r.http.websocketSync}},global:{sync_group:i.syncGroup,routing_hint:i.routingHint}};return r.http.staticContentPath&&(o.listen.http.static_content_path=r.http.staticContentPath),r.http.tlsKeyPath&&(o.listen.http.tls_key_path=r.http.tlsKeyPath),r.http.tlsCertificatePath&&(o.listen.http.tls_certificate_path=r.http.tlsCertificatePath),o}const NO_PREFERRED_ROUTE_HINT=0;class TransportConfig{constructor(){this._isFrozen=!1,this.peerToPeer={bluetoothLE:{isEnabled:!1},awdl:{isEnabled:!1},lan:{isEnabled:!1,isMdnsEnabled:!0,isMulticastEnabled:!0}},this.connect={tcpServers:[],websocketURLs:[],retryInterval:5e3},this.listen={tcp:{isEnabled:!1,interfaceIP:"[::]",port:4040},http:{isEnabled:!1,interfaceIP:"[::]",port:80,websocketSync:!0}},this.global={syncGroup:0,routingHint:0}}setAllPeerToPeerEnabled(e){this.peerToPeer.bluetoothLE.isEnabled=e,this.peerToPeer.lan.isEnabled=e,this.peerToPeer.awdl.isEnabled=e}get isFrozen(){return this._isFrozen}freeze(){return this.isFrozen||(this._isFrozen=!0,Object.freeze(this.peerToPeer.bluetoothLE),Object.freeze(this.peerToPeer.awdl),Object.freeze(this.peerToPeer.lan),Object.freeze(this.peerToPeer),Object.freeze(this.connect.tcpServers),Object.freeze(this.connect.websocketURLs),Object.freeze(this.connect),Object.freeze(this.listen.tcp),Object.freeze(this.listen.http),Object.freeze(this.listen),Object.freeze(this.global)),this}copy(){const e=new TransportConfig;return e.peerToPeer.bluetoothLE.isEnabled=this.peerToPeer.bluetoothLE.isEnabled,e.peerToPeer.awdl.isEnabled=this.peerToPeer.awdl.isEnabled,e.peerToPeer.lan.isEnabled=this.peerToPeer.lan.isEnabled,e.peerToPeer.lan.isMdnsEnabled=this.peerToPeer.lan.isMdnsEnabled,e.peerToPeer.lan.isMulticastEnabled=this.peerToPeer.lan.isMulticastEnabled,e.connect.tcpServers=this.connect.tcpServers.slice(),e.connect.websocketURLs=this.connect.websocketURLs.slice(),e.connect.retryInterval=this.connect.retryInterval,e.listen.tcp={...this.listen.tcp},e.listen.http={...this.listen.http},e.global.syncGroup=this.global.syncGroup,e.global.routingHint=this.global.routingHint,e}static areListenTCPsEqual(e,t){return e.isEnabled===t.isEnabled&&e.interfaceIP===t.interfaceIP&&e.port===t.port}static areListenHTTPsEqual(e,t){return e.isEnabled===t.isEnabled&&e.interfaceIP===t.interfaceIP&&e.port===t.port&&e.staticContentPath===t.staticContentPath&&e.websocketSync===t.websocketSync&&e.tlsKeyPath===t.tlsKeyPath&&e.tlsCertificatePath===t.tlsCertificatePath}}class AttachmentFetcher{stop(){if(null==this.manager){this.isStopped||(this.rejectPendingFetch(),this.rejectPendingFetch=null),this.ditto.store.removeAttachmentFetcher(this);const e=Bridge.ditto.handleFor(this.ditto);this.ditto.deferCloseAsync((async()=>{const t=await this.cancelTokenPromise;t&&dittoCancelResolveAttachment(e.deref(),this.token.idBytes,t)}))}else step((async()=>{await this.manager.stopAttachmentFetcher(this),null!=this.rejectPendingFetch&&(this.rejectPendingFetch(),this.rejectPendingFetch=null)}))}then(e,t){return this.attachment.then(e,t)}constructor(e,t,n,r){this.cancelTokenPromise=null,this.rejectPendingFetch=null,this.ditto=e,this.token=t,this.manager=n,this.id=generateEphemeralToken();const i=r||function(){},o=Bridge.ditto.handleFor(e);this.attachment=new Promise(((e,n)=>{const onComplete=t=>{const n=new Attachment(this.ditto,this.token);Bridge.attachment.bridge(t,(()=>n)),i({type:"Completed",attachment:n}),this.rejectPendingFetch=null,e(n)},onProgress=(e,t)=>{i({type:"Progress",totalBytes:t,downloadedBytes:e})},onDelete=()=>{i({type:"Deleted"}),null!=this.manager?(this.rejectPendingFetch=null,e(null)):(this.rejectPendingFetch=null,n(new DittoError("store/attachment-not-found","The attachment was deleted while being fetched.")))},onError=()=>{};this.rejectPendingFetch=()=>{const e=null!=this.manager?new Error("Attachment fetch was canceled"):new DittoError("store/failed-to-fetch-attachment","Attachment fetch was canceled");n(e)};const r=new WeakRef(this);this.cancelTokenPromise=(async()=>{try{return await mapFFIErrorsAsync((async()=>dittoResolveAttachment(o.deref(),t.idBytes,{onComplete:onComplete,onProgress:onProgress,onDelete:onDelete},onError)),{1:["store/failed-to-fetch-attachment","Failed to fetch the attachment."],2:["store/attachment-token-invalid","The attachment token was invalid."],3:["store/attachment-not-found","The attachment was not found."]})}catch(t){let o=!1;t instanceof DittoError&&"store/attachment-not-found"===t.code&&(o=!0,i({type:"Deleted"})),Logger.error(t.message);const a=r.deref();return null==a||(null!=a.manager&&t instanceof DittoError&&(t=new Error(t.message)),a.rejectPendingFetch=null,null!=a.manager&&o?e(null):n(t)),null}})()})),null==n&&this.attachment.then((()=>{this.rejectPendingFetch=null,this.ditto.store.removeAttachmentFetcher(this)})).catch((()=>{this.rejectPendingFetch=null,this.ditto.store.removeAttachmentFetcher(this)}))}get isStopped(){return null==this.rejectPendingFetch}}class Subscription{get isCancelled(){return this._isCancelled}get collectionName(){return this.collection.name}cancel(){this.isCancelled||(this._isCancelled=!0,this.manager.remove(this))}constructor(e,t,n,r,i,o){this._isCancelled=!1,this.query=t,this.queryArgsCBOR=n,this.collection=e,this.contextInfo={id:generateEphemeralToken(),collectionName:e.name,query:t,queryArgsCBOR:n,orderBys:r,limit:i,offset:o},this.manager=e.store.ditto.subscriptionManager,this.manager.add(this)}}class LiveQueryEventInitial{constructor(){this.isInitial=!0}hash(e){Logger.warning("LiveQueryEventInitial.hash() is deprecated, use Document.hash() instead");return documentsHash(Bridge.document.handlesFor(e).deref())}hashMnemonic(e){Logger.warning("LiveQueryEventInitial.hashMnemonic() is deprecated, use Document.hashMnemonic() instead");return documentsHashMnemonic(Bridge.document.handlesFor(e).deref())}}class LiveQueryEventUpdate{hash(e){Logger.warning("LiveQueryEventUpdate.hash() is deprecated, use Document.hash() instead");return documentsHash(Bridge.document.handlesFor(e).deref())}hashMnemonic(e){Logger.warning("LiveQueryEventUpdate.hashMnemonic() is deprecated, use Document.hashMnemonic() instead");return documentsHashMnemonic(Bridge.document.handlesFor(e).deref())}constructor(e){this.isInitial=!1,this.oldDocuments=e.oldDocuments,this.insertions=e.insertions,this.deletions=e.deletions,this.updates=e.updates,this.moves=e.moves}}class SingleDocumentLiveQueryEvent{hash(e){Logger.warning("SingleDocumentLiveQueryEvent.hash() is deprecated, use Document.hash() instead");return documentsHash(Bridge.document.handlesFor(null==e?[]:[e]).deref())}hashMnemonic(e){Logger.warning("SingleDocumentLiveQueryEvent.hashMnemonic() is deprecated, use Document.hashMnemonic() instead");return documentsHashMnemonic(Bridge.document.handlesFor(null==e?[]:[e]).deref())}constructor(e,t){this.isInitial=e,this.oldDocument=t}}class LiveQuery{get collectionName(){return this.collection.name}get isStopped(){return!this.liveQueryManager}stop(){this.isStopped||this.liveQueryManager.stopLiveQuery(this)}get liveQueryID(){return this._liveQueryID}constructor(e,t,n,r,i,o,a,s){this.query=e,this.queryArgs=t?Object.freeze({...t}):null,this.queryArgsCBOR=n,this.orderBys=r,this.limit=i,this.offset=o,this.collection=a,this.handler=s,this.liveQueryManager=null;const c=a.name,d=new WeakRef(a.store.ditto);let l;const signalNext=async()=>{const e=d.deref();if(!e)return;const t=Bridge.ditto.handleFor(e).derefOrNull();return t?e.deferCloseAsync((async()=>{await liveQuerySignalAvailableNext(t,l)})):void 0},u=a.store.ditto,_=Bridge.ditto.handleFor(u);if(u.deferClose((()=>{l=liveQueryRegister(_.deref(),c,e,n,this.orderBys,i,o,(e=>{const t=e.documents.map((e=>Bridge.document.bridge(e)));let n;n=e.is_initial?new LiveQueryEventInitial:new LiveQueryEventUpdate({oldDocuments:e.old_documents.map((e=>Bridge.document.bridge(e))),insertions:e.insertions,deletions:e.deletions,updates:e.updates,moves:e.moves.map((e=>({from:e[0],to:e[1]})))}),s(t,n,signalNext)}))})),!l)throw new Error("Internal inconsistency, couldn't create a valid live query ID.");this._liveQueryID=l}async signalNext(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);if(t.derefOrNull())return e.deferCloseAsync((async()=>{await liveQuerySignalAvailableNext(t.deref(),this.liveQueryID)}))}}class PendingCursorOperation extends BasePendingCursorOperation{sort(e,t="ascending"){return super.sort(e,t)}offset(e){return super.offset(e)}limit(e){return super.limit(e)}async remove(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.query;return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const n=await writeTransaction(t.deref()),r=await collectionRemoveQueryStr(t.deref(),this.collection.name,n,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(t.deref(),n),r}))).map((e=>new DocumentID(e,!0)))}))}async evict(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.query;return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const n=await writeTransaction(t.deref()),r=await collectionEvictQueryStr(t.deref(),this.collection.name,n,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(t.deref(),n),r}))).map((e=>new DocumentID(e,!0)))}))}async update(e){const t=this.collection.store.ditto,n=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const t=await writeTransaction(n.deref()),r=await super.updateWithTransaction(e,t);return await writeTransactionCommit(n.deref(),t),r}))))}subscribe(){const e=new Subscription(this.collection,this.query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return this.collection.store.ditto.subscriptionManager.add(e),e}observeLocal(e){return this._observe(e,!1)}observeLocalWithNextSignal(e){return this._observe(e,!0)}constructor(e,t,n){super(e,t,n)}_observe(e,t){const n=t?e:async function wrappedHandler(t,n,r){try{return await e.call(this,t,n)}finally{r()}},r=new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,n);return this.collection.store.ditto.liveQueryManager.startLiveQuery(r),r}}class PendingIDSpecificOperation extends BasePendingIDSpecificOperation{async remove(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await writeTransaction(t.deref()),n=await collectionRemove(t.deref(),this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t.deref(),e),n}))))}async evict(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await writeTransaction(t.deref()),n=await collectionEvict(t.deref(),this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t.deref(),e),n}))))}async update(e){const t=this.collection.store.ditto,n=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=await readTransaction(n.deref()),r=await collectionGet(n.deref(),this.collection.name,this.documentIDCBOR,t);if(readTransactionFree(t),!r)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const i=Bridge.mutableDocument.bridge(r,(()=>new MutableDocument));e(i),Bridge.mutableDocument.unregister(i);const o=await writeTransaction(n.deref());return await collectionUpdate(n.deref(),this.collection.name,o,r),await writeTransactionCommit(n.deref(),o),i["@ditto.updateResults"].slice()}))}subscribe(){const e=new Subscription(this.collection,this.query,null,[],-1,0);return this.collection.store.ditto.subscriptionManager.add(e),e}observeLocal(e){return this._observe(e,!1)}observeLocalWithNextSignal(e){return this._observe(e,!0)}constructor(e,t){super(e,t)}_observe(e,t){const n=new LiveQuery(this.query,null,null,[],-1,0,this.collection,(async(n,r,i)=>{if(n.length>1)throw new Error(`Internal inconsistency, single document live query returned more than one document. Query: ${this.query}}.`);if(!1===r.isInitial&&r.oldDocuments.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one old documents. Query ${this.query}.`);if(!1===r.isInitial&&r.insertions.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one insertion, which doesn't make sense for single document observations. Query ${this.query}.`);if(!1===r.isInitial&&r.deletions.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one deletion, which doesn't make sense for single document observations. Query ${this.query}.`);if(!1===r.isInitial&&r.updates.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one update, which doesn't make sense for single document observations. Query ${this.query}.`);if(!1===r.isInitial&&r.moves.length>0)throw new Error(`Internal inconsistency, single document live query returned an update event with moves, which doesn't make sense for single document observations. Query ${this.query}.`);if((!0===r.isInitial?0:r.insertions.length+r.deletions.length+r.updates.length)>1)throw new Error(`Internal inconsistency, single document live query returned a combination of inserts, updates, and/or deletes, which doesn't make sense for single document observation. Query ${this.query}.`);const o=n[0]||null,a=!0===r.isInitial?void 0:r.oldDocuments[0],s=new SingleDocumentLiveQueryEvent(r.isInitial,a);if(t)e(o,s,i);else try{await e(o,s)}finally{i()}}));return this.collection.store.ditto.liveQueryManager.startLiveQuery(n),n}}class Collection{find(e,t){return new PendingCursorOperation(e,null!=t?t:null,this)}findAll(){return this.find("true")}findByID(e){const t=e instanceof DocumentID?e:new DocumentID(e);return new PendingIDSpecificOperation(t,this)}async upsert(e,t={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{var n;const i=null!==(n=t.writeStrategy)&&void 0!==n?n:"merge",o=desugarJSObject(e),a=CBOR.encode(o),s=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionInsertValue(r.deref(),this.name,a,i,void 0)));return new DocumentID(s,!0)}))}async newAttachment(e,t={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{const{id:i,len:o,handle:a}=await(async()=>{if("string"==typeof e)throw new Error("Can't create attachment from file when running in the browser. Please pass the raw data (as a Uint8Array) instead.");if(e instanceof Uint8Array)return await dittoNewAttachmentFromBytes(r.deref(),e);throw new Error(`Can't create new attachment, only file path as string or raw data as Uint8Array are supported, but got: ${typeof e}, ${e}`)})(),s={_id:i,_len:o,_meta:{...t}};s[DittoCRDTTypeKey]=DittoCRDTType.attachment;const c=new AttachmentToken(s),d=new Attachment(n,c);return Bridge.attachment.bridge(a,(()=>d))}))}fetchAttachment(e,t){if(null==e||!(e instanceof AttachmentToken))throw new Error(`Invalid attachment token: ${e}`);const n=this.store.ditto;return n.deferClose((()=>n.attachmentFetcherManager.startAttachmentFetcher(e,t)))}constructor(e,t){this.name=e,this.store=t}findByIDCBOR(e){const t=new DocumentID(e,!0,!0);return new PendingIDSpecificOperation(t,this)}}class QueryResult{mutatedDocumentIDs(){return queryResultMutatedDocumentIDs(Bridge.queryResult.handleFor(this).deref()).map((e=>new DocumentID(e,!0)))}constructor(e){if(null==e)throw new Error("Internal inconsistency, failed to initialize query result without a response pointer");const t=queryResultItems(e);this.items=t.map((e=>Bridge.queryResultItem.bridge(e)))}}class StoreObserver{get isCancelled(){return this._isCancelled}cancel(){this._isCancelled||(this._isCancelled=!0,this.ditto.store.unregisterObserver(this))}constructor(e,t,n,r){this._isCancelled=!1,this.queryString=t,this.queryArguments=n?Object.freeze({...n}):void 0,this.ditto=e;let i,o=null;if(null!=n)try{const e=desugarJSObject(n);o=CBOR.encode(e)}catch(e){throw new DittoError("query/arguments-invalid")}const a=Bridge.ditto.handleFor(e);if(this.ditto.deferClose((()=>{const e=new WeakRef(this);function wrappedObservationHandler(t){const n=e.deref();if(null==n)return void Logger.debug(`Ignoring change event received by store observer ${i} after it was cancelled`);const o=Bridge.queryResult.bridge(t.query_result,(()=>new QueryResult(t.query_result)));Logger.debug(`Invoking user event handler with new event for store observer ${i}`),r(o,(()=>n.signalNext()))}mapFFIErrors((()=>{i=tryExperimentalRegisterChangeObserver(a.deref(),t,o,wrappedObservationHandler)}))})),null==i)throw new DittoError("internal","Internal inconsistency, store observer ID is undefined after registering");this.liveQueryID=i}signalNext(){const e=this.ditto;if(!e||e.isClosed)return;const t=Bridge.ditto.handleFor(e).derefOrNull();if(t){if(null==this.liveQueryID)throw new Error("live query ID is null while signaling ready for next event");return e.deferCloseAsync((async()=>{Logger.debug(`Signaling availability for live query ${this.liveQueryID}`),await liveQuerySignalAvailableNext(t,this.liveQueryID)}))}}}class CollectionsEvent{static initial(e){return new CollectionsEvent({isInitial:!0,collections:e,oldCollections:[],insertions:[],deletions:[],updates:[],moves:[]})}constructor(e){this.isInitial=e.isInitial,this.collections=e.collections,this.oldCollections=e.oldCollections,this.insertions=e.insertions,this.deletions=e.deletions,this.updates=e.updates,this.moves=e.moves}}class PendingCollectionsOperation{sort(e,t="ascending"){return this.pendingCursorOperation.sort(e,t),this}offset(e){return this.pendingCursorOperation.offset(e),this}limit(e){return this.pendingCursorOperation.limit(e),this}subscribe(){return this.pendingCursorOperation.subscribe()}observeLocal(e){return this._observe(e,!1)}observeLocalWithNextSignal(e){return this._observe(e,!0)}async exec(){return collectionsFromDocuments(await this.pendingCursorOperation.exec(),this.store)}constructor(e){this.store=e,this.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",e))}then(e,t){return this.exec().then(e,t)}_observe(e,t){const n=new WeakRef(this.store);return this.pendingCursorOperation._observe((function(r,i,o){const a=n.deref();if(!a)return;const s=collectionsFromDocuments(r,a);let c;if(!0===i.isInitial)c=CollectionsEvent.initial(s);else{const e=collectionsFromDocuments(i.oldDocuments,a);c=new CollectionsEvent({isInitial:!1,collections:s,oldCollections:e,insertions:i.insertions,deletions:i.deletions,updates:i.updates,moves:i.moves})}t?e(c,o):e(c)}),t)}}function collectionsFromDocuments(e,t){const n=[];for(const r of e){const e=r.at("name").value;void 0!==e&&"string"==typeof e&&n.push(new Collection(e,t))}return n}class WriteTransactionPendingCursorOperation extends BasePendingCursorOperation{sort(e,t="ascending"){return super.sort(e,t)}offset(e){return super.offset(e)}limit(e){return super.limit(e)}async remove(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.query,n=this.collection.writeTransaction,r=(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>collectionRemoveQueryStr(t.deref(),this.collection.name,n.writeTransactionPointer,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((e=>new DocumentID(e,!0)));return r.forEach((e=>{n.addResult("removed",e,this.collection.name)})),r}))}async evict(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.query,n=this.collection.writeTransaction,r=(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>collectionEvictQueryStr(t.deref(),this.collection.name,n.writeTransactionPointer,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((e=>new DocumentID(e,!0)));return r.forEach((e=>{n.addResult("evicted",e,this.collection.name)})),r}))}async update(e){const t=this.collection.writeTransaction,n=await super.updateWithTransaction(e,t.writeTransactionPointer);return n.keys().forEach((e=>{t.addResult("updated",e,this.collection.name)})),n}constructor(e,t,n){super(e,t,n)}}class WriteTransactionPendingIDSpecificOperation extends BasePendingIDSpecificOperation{async remove(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.collection.writeTransaction,n=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>collectionRemove(t.deref(),this.collection.name,e.writeTransactionPointer,this.documentIDCBOR)));return e.addResult("removed",this.documentID,this.collection.name),n}))}async evict(){const e=this.collection.store.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=this.collection.writeTransaction,n=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionEvict(t.deref(),this.collection.name,e.writeTransactionPointer,this.documentIDCBOR)));return e.addResult("evicted",this.documentID,this.collection.name),n}))}async update(e){const t=this.collection.store.ditto,n=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.collection.writeTransaction,r=await readTransaction(n.deref()),i=await collectionGet(n.deref(),this.collection.name,this.documentIDCBOR,r);if(readTransactionFree(r),!i)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const o=Bridge.mutableDocument.bridge(i,(()=>new MutableDocument));return e(o),Bridge.mutableDocument.unregister(o),await collectionUpdate(n.deref(),this.collection.name,t.writeTransactionPointer,i),t.addResult("updated",this.documentID,this.collection.name),o["@ditto.updateResults"].slice()}))}constructor(e,t){super(e,t)}}class WriteTransactionCollection{find(e,t){return new WriteTransactionPendingCursorOperation(e,null!=t?t:null,this)}findAll(){return this.find("true")}findByID(e){const t=e instanceof DocumentID?e:new DocumentID(e);return new WriteTransactionPendingIDSpecificOperation(t,this)}async upsert(e,t={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{var n;const i=null!==(n=t.writeStrategy)&&void 0!==n?n:"merge",o=desugarJSObject(e),a=CBOR.encode(o),s=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionInsertValue(r.deref(),this.name,a,i,this.writeTransaction.writeTransactionPointer))),c=new DocumentID(s,!0);return this.writeTransaction.addResult("inserted",c,this.name),new DocumentID(s,!0)}))}findByIDCBOR(e){const t=new DocumentID(e,!0,!0);return new WriteTransactionPendingIDSpecificOperation(t,this)}constructor(e,t,n){this.name=e,this.store=t,this.writeTransaction=n}}class WriteTransaction{static async init(e){return e.deferCloseAsync((async()=>{const t=Bridge.ditto.handleFor(e),n=await writeTransaction(t.deref());return new WriteTransaction(e,n)}))}scoped(e){if("string"!=typeof e)throw new Error("Collection name must be a string");return new WriteTransactionCollection(e,this.ditto.store,this)}async commit(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>writeTransactionCommit(t.deref(),this.writeTransactionPointer)))}async rollback(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>writeTransactionRollback(t.deref(),this.writeTransactionPointer)))}addResult(e,t,n){this.results.push({type:e,docID:t,collectionName:n})}constructor(e,t){this.writeTransactionPointer=t,this.ditto=e,this.results=[]}}class Store{registerObserver(e,t,n){return this.registerObserverWithSignalNext(e,((e,n)=>{try{t(e)}finally{n()}}),n)}registerObserverWithSignalNext(e,t,n){if("string"!=typeof e)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof e);const r=new StoreObserver(this.ditto,e,null!=n?n:null,t);this.observers=Object.freeze([...this.observers,r]);const i=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>new Promise((e=>{step((async()=>{try{await mapFFIErrorsAsync((async()=>await liveQueryStart(i.deref(),r.liveQueryID)))}catch(e){Logger.error(`Failed to start live query: ${e.message}`)}e()}))})))),r}collection(e){return new Collection(e,this)}collections(){return new PendingCollectionsOperation(this)}collectionNames(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return e.deferClose((()=>mapFFIErrors((()=>dittoGetCollectionNames(t.deref())))))}async execute(e,t){if("string"!=typeof e)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof e);const n=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{let r=null;if(null!=t)try{const e=desugarJSObject(t);r=CBOR.encode(e)}catch(e){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${e.message}`)}const i=await mapFFIErrorsAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((()=>tryExecStatement(n.deref(),null,e,r)))));return Bridge.queryResult.bridge(i,(()=>new QueryResult(i)))}))}async write(e){return this.ditto.deferCloseAsync((async()=>{const t=await WriteTransaction.init(this.ditto);try{await e(t)}catch(e){throw await t.rollback(),Logger.warning(`Transaction rolled back due to an error: ${null==e?void 0:e.message}`),e}return await t.commit(),t.results}))}async newAttachment(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);return null!=t&&validateAttachmentMetadata(t),n.deferCloseAsync((async()=>{const{id:i,len:o,handle:a}=await(async()=>{if("string"==typeof e)throw new DittoError("sdk/unsupported","Can't create attachment from file when running in the browser. Please pass the raw data (as a Uint8Array) instead.");if(e instanceof Uint8Array)return mapFFIErrorsAsync((async()=>await dittoNewAttachmentFromBytes(r.deref(),e)),{1:["store/failed-to-create-attachment"]});throw new Error(`Can't create new attachment, only file path as string or raw data as Uint8Array are supported, but got: ${typeof e}, ${e}`)})(),s={_id:i,_len:o,_meta:{...t},[DittoCRDTTypeKey]:DittoCRDTType.attachment},c=new AttachmentToken(s),d=new Attachment(n,c);return Bridge.attachment.bridge(a,(()=>d))}))}fetchAttachment(e,t){if(null==e)throw new Error("Missing required parameter 'token'");let n;n=e instanceof AttachmentToken?e:new AttachmentToken(e);const r=this.ditto;return r.deferClose((()=>{const e=new AttachmentFetcher(r,n,null,t);return this.attachmentFetchers=Object.freeze([...this.attachmentFetchers,e]),e}))}constructor(e){this.observers=Object.freeze([]),this.attachmentFetchers=Object.freeze([]),this.ditto=e}async registerObserverWebhook(e,t,n){let r=null;if(null!=n)try{const e=desugarJSObject(n);r=CBOR.encode(e)}catch(e){throw new DittoError("query/arguments-invalid",`Invalid query arguments: ${e.message}`)}const i=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{const n=await mapFFIErrorsAsync((async()=>await tryRegisterStoreObserverWebhook(i.deref(),e,r,t)));return new DocumentID(n,!0)}))}unregisterObserver(e){if(e.ditto!==this.ditto)throw new DittoError("internal","Internal inconsistency, can't remove store observer that does not belong to this store");if(!e.isCancelled)throw new DittoError("internal","Internal inconsistency, can't remove store observer that has not been cancelled");const t=this.observers.findIndex((t=>t===e));if(-1===t)return!1;const n=[...this.observers];n.splice(t,1),this.observers=Object.freeze(n);const r=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>{mapFFIErrors((()=>liveQueryStop(r.deref(),e.liveQueryID)))})),!0}removeAttachmentFetcher(e){if(e.ditto!==this.ditto)throw new DittoError("internal","Internal inconsistency, can't finalize attachment fetcher that does not belong to this store");if(null!=e.manager)throw new DittoError("internal","Internal inconsistency, store can't remove attachment fetcher that is owned by the attachment fetcher manager");if(!e.isStopped)throw new DittoError("internal","Internal inconsistency, can't remove attachment fetcher that has not stopped");const t=this.attachmentFetchers.findIndex((t=>t===e));if(-1===t)return!1;const n=[...this.attachmentFetchers];return n.splice(t,1),this.attachmentFetchers=Object.freeze(n),!0}close(){for(const e of this.observers)e.cancel();for(const e of this.attachmentFetchers)e.stop()}async registerLiveQueryWebhook(e,t,n){const r=this.ditto,i=Bridge.ditto.handleFor(r);return r.deferCloseAsync((async()=>{const r=validateQuery(t),o=await liveQueryWebhookRegister(i.deref(),e,r,[],0,0,n);return new DocumentID(o,!0)}))}}function addressToString(e){return`${e.siteId}-${e.pubkey}`}class Presence{get connectionRequestHandler(){return this._connectionRequestHandler}set connectionRequestHandler(e){let t=null;if(null!=e){if("function"!=typeof e)throw new TypeError(`Expected parameter 'handler' to be a function but got ${typeof e} instead`);t=async t=>{const n=Bridge.connectionRequest.bridge(t),r=await e(n);if("allow"!==r&&"deny"!==r)return Logger.error(`The connection request handler must return "allow" or "deny" but returned "${r}" instead. The connection request will be denied.`),"Deny";connectionRequestAuthorize(t,"allow"===r?"Allow":"Deny")}}this._connectionRequestHandler=e;const handleError=e=>{Logger.error(`The connection request handler threw an error while handling a connection request, the connection request will be denied. ${e}`)},n=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{presenceSetConnectionRequestHandler(n.deref(),t,handleError)}))}get graph(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return e.deferClose((()=>{const e=dittoPresenceV3(t.deref());return JSON.parse(e)}))}get peerMetadataJSONString(){const e=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>mapFFIErrors((()=>presencePeerMetadataJSON(e.deref())))))}async setPeerMetadataJSONString(e){const t=Bridge.ditto.handleFor(this.ditto);await this.ditto.deferCloseAsync((async()=>mapFFIErrorsAsync((async()=>presenceTrySetPeerMetadataJSON(t.deref(),e)))))}get peerMetadata(){return JSON.parse(this.peerMetadataJSONString)}async setPeerMetadata(e){let t;try{t=JSON.stringify(e)}catch(e){throw new DittoError("validation/not-json-compatible",`Failed encoding peer metadata to JSON. ${e}`)}await this.setPeerMetadataJSONString(t)}observe(e){const t=this.observerManager.addObserver(e),n=new Observer(this.observerManager,t,{stopsWhenFinalized:!0});return e(this.graph),n}constructor(e){this._connectionRequestHandler=null,this.ditto=e,this.observerManager=new ObserverManager("PresenceObservation",{keepAlive:e.keepAlive,register:e=>{const t=this.ditto,n=Bridge.ditto.handleFor(t);t.deferClose((()=>{dittoRegisterPresenceV3Callback(n.deref(),e)}))},unregister:()=>{const e=this.ditto,t=Bridge.ditto.handleFor(e);e.deferCloseAsync((async()=>dittoClearPresenceV3Callback(t.deref())))},process:e=>[JSON.parse(e)]})}close(){this.observerManager.close()}}class LiveQueryManager{constructor(e,t){this.finalizationRegistry=new FinalizationRegistry(this.finalize),this.ditto=e,this.keepAlive=t,this.liveQueriesByID={}}startLiveQuery(e){const t=this.ditto,n=Bridge.ditto.handleFor(t);this.ditto.deferCloseAsync((async()=>{const r=e.liveQueryID;if(!r)throw new Error("Internal inconsistency, tried to add a live query that doesn't have a live query ID (probably stopped).");if(this.liveQueriesByID[r])throw new Error("Internal inconsistency, tried to add a live query with an ID that has already been added.");const i=new WeakRef(e);return this.liveQueriesByID[r]=i,this.finalizationRegistry.register(e,r,this.finalize),e.liveQueryManager=this,t.keepAlive.retain(`LiveQuery.${r}`),new Promise(((e,t)=>{step((async()=>{await liveQueryStart(n.deref(),r),e()}))}))}))}stopLiveQuery(e){this.finalizationRegistry.unregister(e);const t=e.liveQueryID;if(!t)throw new Error("Internal inconsistency, tried to remove a live query that doesn't have a live query ID (probably stopped).");e.liveQueryManager=null,this.stopLiveQueryWithID(t)}close(){for(const e in this.liveQueriesByID){const t=this.liveQueriesByID[e].deref();t&&this.stopLiveQuery(t)}}stopLiveQueryWithID(e){const t=this.ditto,n=Bridge.ditto.handleFor(t);t.deferClose((()=>{liveQueryStop(n.deref(),e),this.keepAlive.release(`LiveQuery.${e}`),delete this.liveQueriesByID[e]}))}finalize(e){this.stopLiveQueryWithID(e)}}class PresenceManager{constructor(e){this.ditto=e,this.isClosed=!1,this.isRegistered=!1,this.currentRemotePeers=[],this.callbacksByPresenceToken={}}addObserver(e){if(this.isClosed)throw new Error("Internal inconsistency, can't add presence observer, observer mananger close()-ed.");this.registerIfNeeded();const t=generateEphemeralToken();return this.callbacksByPresenceToken[t]=e,this.ditto.keepAlive.retain(`PresenceObservation.${t}`),e(this.currentRemotePeers),t}async removeObserver(e){const t=this.callbacksByPresenceToken[e];if(void 0===t)throw new Error(`Can't remove presence observer, token '${e}' has never been registered before.`);if(null!==t)return void 0!==this.callbacksByPresenceToken[e]?(this.ditto.keepAlive.release(`PresenceObservation.${e}`),this.callbacksByPresenceToken[e]=null,this.unregisterIfNeeded()):void 0}hasObserver(e){return void 0!==this.callbacksByPresenceToken[e]}async close(){this.isClosed=!0;const e=Object.keys(this.callbacksByPresenceToken);return Promise.all(e.map((e=>this.removeObserver(e))))}hasObservers(){return Object.keys(this.callbacksByPresenceToken).length>0}registerIfNeeded(){const e=this.ditto,t=Bridge.ditto.handleFor(this.ditto);e.deferClose((()=>{if(!this.isRegistered){this.isRegistered=!0;const e=dittoPresenceV1(t.deref());this.currentRemotePeers=this.decode(e).sort(this.compareRemotePeers),dittoRegisterPresenceV1Callback(t.deref(),this.handlePresenceV1Callback.bind(this))}}))}unregisterIfNeeded(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return this.ditto.deferCloseAsync((async()=>{!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,await dittoClearPresenceCallback(t.deref()),this.currentRemotePeers=[])}))}handlePresenceV1Callback(e){const t=this.decode(e).sort(this.compareRemotePeers);this.currentRemotePeers=t,this.notify()}notify(){if(!this.isClosed)for(const e in this.callbacksByPresenceToken){const t=this.callbacksByPresenceToken[e];t&&t(this.currentRemotePeers)}}decode(e){return JSON.parse(e).map((e=>{var t,n;return{networkID:e.network_id,deviceName:e.device_name,rssi:null!==(t=e.rssi)&&void 0!==t?t:void 0,approximateDistanceInMeters:null!==(n=e.approximate_distance_in_meters)&&void 0!==n?n:void 0,connections:e.connections}}))}compareRemotePeers(e,t){return 0===e.connections.length&&t.connections.length>0?1:e.connections.length>0&&0===t.connections.length||e.deviceName<t.deviceName?-1:e.deviceName>t.deviceName?1:0}}class TransportConditionsManager extends ObserverManager{constructor(e){super("TransportConditionsObservation",{keepAlive:e.keepAlive}),this.ditto=e}register(e){const t=this.ditto,n=Bridge.ditto.handleFor(t);return t.deferClose((()=>dittoRegisterTransportConditionChangedCallback(n.deref(),e)))}unregister(){const e=this.ditto,t=Bridge.ditto.handleFor(e);return e.deferClose((()=>dittoRegisterTransportConditionChangedCallback(t.deref(),null)))}process(e,t){let n,r;switch(e){case"Bluetooth":n="BLE";break;case"Tcp":n="TCP";break;case"Awdl":n="AWDL";break;case"Mdns":n="MDNS"}switch(t){case"Unknown":r="Unknown";break;case"Ok":r="OK";break;case"GenericFailure":r="GenericFailure";break;case"AppInBackground":r="AppInBackground";break;case"MdnsFailure":r="MDNSFailure";break;case"TcpListenFailure":r="TCPListenFailure";break;case"NoBleCentralPermission":r="NoBLECentralPermission";break;case"NoBlePeripheralPermission":r="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":r="CannotEstablishConnection";break;case"BleDisabled":r="BLEDisabled";break;case"NoBleHardware":r="NoBLEHardware";break;case"WifiDisabled":r="WiFiDisabled";break;case"TemporarilyUnavailable":r="TemporarilyUnavailable"}return[r,n]}}class SyncSubscription{get isCancelled(){return this._isCancelled}cancel(){this._isCancelled||(this._isCancelled=!0,this.ditto.sync.unregisterSubscription(this))}constructor(e,t,n,r){if(this._isCancelled=!1,null==n!=(null==r))throw new DittoError("internal","Internal inconsistency, query arguments and query arguments CBOR must be both null or both non-null",{queryArguments:n,queryArgumentsCBOR:r});this.ditto=e,this.queryString=t,this.queryArguments=n?Object.freeze({...n}):void 0,this.queryArgumentsCBOR=r}}class Sync{registerSubscription(e,t){if("string"!=typeof e)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof e);let n=null;if(null!=t)try{const e=desugarJSObject(t);n=CBOR.encode(e)}catch(e){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${e.message}`)}const r=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{mapFFIErrors((()=>tryAddSyncSubscription(r.deref(),e,n)))}));const i=new SyncSubscription(this.ditto,e,t||null,n);return this.subscriptions=Object.freeze([...this.subscriptions,i]),i}get parameters(){return this.state.underlyingSyncParameters}constructor(e){this.subscriptions=Object.freeze([]),this.bluetoothLETransportPointer=null,this.awdlTransportPointer=null,this.lanTransportPointer=null,this.mdnsClientTransportPointer=null,this.mdnsServerAdvertiserPointer=null;const t={identity:e.identity,transportConfig:new TransportConfig,ditto:e,isWebValid:!1,isX509Valid:!1,isSyncActive:!1};this.ditto=e,this.state=stateFrom(t),transportsInit()}unregisterSubscription(e){if(e.ditto!==this.ditto)throw new DittoError("internal","Can't remove replication subscription that does not belong to this store");if(!e.isCancelled)throw new DittoError("internal","Internal inconsistency, can't remove replication subscription that has not been cancelled");const t=this.subscriptions.findIndex((t=>t===e));if(-1===t)return!1;const n=[...this.subscriptions];n.splice(t,1),this.subscriptions=Object.freeze(n);const r=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>{mapFFIErrors((()=>tryRemoveSyncSubscription(r.deref(),e.queryString,e.queryArgumentsCBOR)))})),!0}update(e){const t=this.state,n=stateFrom(e);this.updatePeerToPeerBluetoothLE(t,n),this.updatePeerToPeerAWDL(t,n),this.updatePeerToPeerLAN(t,n),this.updateListenTCP(t,n),this.updateListenHTTP(t,n),this.updateConnectTCPServers(t,n),this.updateConnectWebsocketURLs(t,n),this.updateGlobal(t,n),this.updateConnectRetryInterval(t,n),this.state=n}close(){if(this.parameters.isSyncActive)throw new Error("Internal inconsistency, can't close sync object while sync is active, please 'stopSync()' first.");for(const e of this.subscriptions)e.cancel()}updatePeerToPeerBluetoothLE(e,t){}updatePeerToPeerAWDL(e,t){}updatePeerToPeerLAN(e,t){}updateListenTCP(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=e.effectiveTransportConfig.listen.tcp,i=t.effectiveTransportConfig.listen.tcp;TransportConfig.areListenTCPsEqual(i,n)||(n.isEnabled&&dittoStopTCPServer(r.deref()),i.isEnabled&&dittoStartTCPServer(r.deref(),`${i.interfaceIP}:${i.port}`))}))}updateListenHTTP(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=e.effectiveTransportConfig.listen.http,i=t.effectiveTransportConfig.listen.http;TransportConfig.areListenHTTPsEqual(n,i)||(n.isEnabled&&dittoStopHTTPServer(r.deref()),i.isEnabled&&dittoStartHTTPServer(r.deref(),`${i.interfaceIP}:${i.port}`,i.staticContentPath||null,i.websocketSync?"Enabled":"Disabled",i.tlsCertificatePath||null,i.tlsKeyPath||null))}))}updateConnectTCPServers(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const e=t.effectiveTransportConfig.connect.tcpServers;dittoSetStaticTCPClients(r.deref(),e)}))}updateConnectWebsocketURLs(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const e=t.effectiveTransportConfig.connect.websocketURLs,n=t.effectiveTransportConfig.global.routingHint;dittoSetStaticWebsocketClients(r.deref(),e,n)}))}updateGlobal(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{e.effectiveTransportConfig.global.syncGroup!==t.effectiveTransportConfig.global.syncGroup&&dittoSetSyncGroup(r.deref(),t.effectiveTransportConfig.global.syncGroup)}))}updateConnectRetryInterval(e,t){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{dittoSetConnectRetryInterval(r.deref(),t.effectiveTransportConfig.connect.retryInterval)}))}}function stateFrom(e){var t,n;const r=e.identity,i=e.isSyncActive,o=e.isX509Valid,a=e.isWebValid;let s,c,d=!1;"onlinePlayground"!==r.type&&"onlineWithAuthentication"!==r.type||(s=r.appID,c=null!==(t=r.customDittoCloudURL)&&void 0!==t?t:null,d=null===(n=r.enableDittoCloudSync)||void 0===n||n),validateEnabledTransportsAvailable(e.ditto,e.transportConfig);const l=e.transportConfig.copy();if(i&&o||(l.peerToPeer.bluetoothLE.isEnabled=!1,l.peerToPeer.awdl.isEnabled=!1,l.peerToPeer.lan.isEnabled=!1,l.listen.tcp.isEnabled=!1,l.connect.tcpServers=[]),i&&a||(l.connect.websocketURLs=[]),i||(l.listen.http.isEnabled=!1),i&&a&&d){const e=null!=c?c:defaultDittoCloudURL(s);l.connect.websocketURLs.push(e)}return{underlyingSyncParameters:e,effectiveTransportConfig:l.freeze()}}function validateEnabledTransportsAvailable(e,t){const n=Bridge.ditto.handleFor(e);return e.deferClose((()=>{const e=[],r=transportsBLEIsAvailable(n.deref()),i=transportsAWDLIsAvailable(n.deref()),o=transportsLANIsAvailable(n.deref());if(t.peerToPeer.bluetoothLE.isEnabled&&!r&&e.push("BluetoothLE"),t.peerToPeer.awdl.isEnabled&&!i&&e.push("AWDL"),t.peerToPeer.lan.isEnabled&&!o&&e.push("LAN"),e.length>0)throw new Error(`The following P2P transports are enabled in the transport config but are not supported in the current environment: ${e.join(", ")}`);if(t.connect.tcpServers.length>0&&isWebBuild)throw new Error("The transport config contains TCP servers, but this transport is not supported in web environments");if(t.listen.http.isEnabled&&isWebBuild)throw new Error("The transport config contains an HTTP listener, which is not supported in web environments");if(t.listen.tcp.isEnabled&&isWebBuild)throw new Error("The transport config contains a TCP listener, which is not supported in web environments")}))}class SubscriptionManager{constructor(e){this.ditto=e,this.subscriptions={},this.finalizationRegistry=new FinalizationRegistry(this.removeWithContextInfo.bind(this))}add(e){const t=this.ditto,n=Bridge.ditto.handleFor(t),r=e.contextInfo;t.deferClose((()=>{this.subscriptions[r.id]=new WeakRef(e),this.finalizationRegistry.register(e,e.contextInfo,e),addSubscription(n.deref(),r.collectionName,r.query,r.queryArgsCBOR,r.orderBys,r.limit,r.offset)}))}remove(e){if(null==this.subscriptions[e.contextInfo.id])throw new Error(`Internal inconsistency, tried to remove a subscription that is not tracked: ${e.contextInfo.id}`);this.finalizationRegistry.unregister(e),this.removeWithContextInfo(e.contextInfo)}close(){this.ditto.deferClose((()=>{for(const e in this.subscriptions){const t=this.subscriptions[e].deref();null==t||t.cancel()}}))}removeWithContextInfo(e){const t=this.ditto,n=Bridge.ditto.handleFor(t);t.deferClose((()=>{delete this.subscriptions[e.id],removeSubscription(n.deref(),e.collectionName,e.query,e.queryArgsCBOR,e.orderBys,e.limit,e.offset)}))}}class AttachmentFetcherManager{constructor(e){this.contextInfoByID={},this.finalizationRegistry=new FinalizationRegistry(this.stopWithContextInfo),this.ditto=e}startAttachmentFetcher(e,t){return this.ditto.deferClose((()=>{const n=new AttachmentFetcher(this.ditto,e,this,t),r={id:n.id,attachmentTokenID:e.idBytes,cancelTokenPromise:n.cancelTokenPromise,attachmentFetcher:new WeakRef(n)};this.finalizationRegistry.register(n,r,n),this.contextInfoByID[n.id]=r;const resetCancelToken=()=>{null!=this.contextInfoByID[n.id]&&(this.contextInfoByID[n.id].cancelTokenPromise=null)};return n.attachment.then((e=>(resetCancelToken(),e)),(e=>(resetCancelToken(),e))),this.ditto.keepAlive.retain(`AttachmentFetcher.${n.id})`),n}))}async stopAttachmentFetcher(e){this.finalizationRegistry.unregister(e);const t=this.contextInfoByID[e.id];if(null==t)throw new Error(`Internal inconsistency: cannot stop attachment fetcher ${e.id}, which is not registered.`);await this.stopWithContextInfo(t)}close(){this.ditto.deferCloseAsync((async()=>{const e=Object.values(this.contextInfoByID).map((async e=>{const t=e.attachmentFetcher.deref();null!=t&&await this.stopAttachmentFetcher(t)}));await Promise.all(e)}))}stopWithContextInfo(e){const t=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{if(null==this.contextInfoByID[e.id])throw new Error(`Internal inconsistency: attachment fetcher ${e.id} not found in active attachment fetchers.`);delete this.contextInfoByID[e.id],this.ditto.keepAlive.release(`AttachmentFetcher.${e.id})`);const n=await e.cancelTokenPromise;n&&dittoCancelResolveAttachment(t.deref(),e.attachmentTokenID,n)}))}}class SmallPeerInfo{get isEnabled(){const e=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>dittoSmallPeerInfoGetIsEnabled(e.deref())))}set isEnabled(e){if("boolean"!=typeof e)throw new TypeError("Expected boolean, got "+typeof e);const t=Bridge.ditto.handleFor(this.ditto);this.ditto.deferCloseAsync((async()=>dittoSmallPeerInfoSetEnabled(t.deref(),e)))}get metadata(){return JSON.parse(this.metadataJSONString)}set metadata(e){this.metadataJSONString=JSON.stringify(e)}get metadataJSONString(){const e=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>dittoSmallPeerInfoGetMetadata(e.deref())))}set metadataJSONString(e){if("string"!=typeof e)throw new TypeError("Expected string, got "+typeof e);const t=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{dittoSmallPeerInfoSetMetadata(t.deref(),e)}))}async getSyncScope(){const e=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>dittoSmallPeerInfoGetSyncScope(e.deref())))}async setSyncScope(e){const t=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>dittoSmallPeerInfoSetSyncScope(t.deref(),e)))}constructor(e){this.ditto=e}}const DEFAULT_PERSISTENCE_DIRECTORY="ditto";class Ditto{static get VERSION(){return dittoGetSDKSemver()}get deviceName(){return this._deviceName}set deviceName(e){this.isSyncActive&&Logger.warning("Changes to the device name take effect when sync is restarted."),this._deviceName=e}get sdkVersion(){const e=Bridge.ditto.handleFor(this);return this.deferClose((()=>dittoGetSDKVersion(e.deref())))}get path(){return Logger.warning("⚠️ Deprecation Warning: The 'Ditto.path' property is deprecated. Please update your code to use the new 'Ditto.persistenceDirectory' property instead."),this.persistenceDirectory}get isActivated(){var e;return null!==(e=this._isActivated)&&void 0!==e&&e}get isClosed(){var e;return null!==(e=this._isClosed)&&void 0!==e&&e}get isSyncActive(){var e;return null!==(e=this._isSyncActive)&&void 0!==e&&e}constructor(e,t){if(this.deferCloseAllowed=!0,this.isWebValid=!1,this.isX509Valid=!1,this._isSyncActive=!1,this._isClosed=!1,this.pendingOperations=new Set,!Ditto.isEnvironmentSupported())throw new Error("Ditto does not support this JavaScript environment. Please consult the Ditto JavaScript documentation for a list of supported environments and browsers. You can use `Ditto.isEnvironmentSupported()` to run this check anytime.");this.persistenceDirectory=Ditto.initPersistenceDirectory(t);const n=null!=e?e:{type:"offlinePlayground",appID:""},r=Object.freeze(this.validateIdentity(n));this.identity=Object.freeze(r),this._deviceName=navigator.userAgent,this.keepAlive=new KeepAlive;let i=null;const o=new WeakRef(this),a=(()=>{var e,t,n;if("offlinePlayground"===r.type)return dittoIdentityConfigMakeOfflinePlayground(r.appID,null!==(e=r.siteID)&&void 0!==e?e:0);if("manual"===r.type)return dittoIdentityConfigMakeManual(r.certificate);if("sharedKey"===r.type)return dittoIdentityConfigMakeSharedKey(r.appID,r.sharedKey,r.siteID);if("onlinePlayground"===r.type){const e=null!==(t=r.customAuthURL)&&void 0!==t?t:defaultAuthURL(r.appID);return dittoIdentityConfigMakeOnlinePlayground(r.appID,r.token,e)}if("onlineWithAuthentication"===r.type){const e=null!==(n=r.customAuthURL)&&void 0!==n?n:defaultAuthURL(r.appID);return dittoIdentityConfigMakeOnlineWithAuthentication(r.appID,e)}throw new Error(`Can't create Ditto, unsupported identity type: ${r}`)})(),s=dittoMake(this.persistenceDirectory,a,"Disabled");dittoAuthClientSetValidityListener(s,(function(...e){const t=o.deref();null==t||t.isClosed?Logger.info("Ditto is closed, ignoring auth client validity change"):t.authClientValidityChanged(...e)}));const c=dittoAuthClientIsWebValid(s),d=dittoAuthClientIsX509Valid(s),l=dittoAuthClientGetAppID(s),u=dittoAuthClientGetSiteID(s);if(Bridge.ditto.bridge(s,this),"onlineWithAuthentication"===r.type){this.auth=new OnlineAuthenticator(this.keepAlive,this,r.authHandler);dittoAuthSetLoginProvider(s,dittoAuthClientMakeLoginProvider((function(e){const t=o.deref();t?t.auth?t.auth["@ditto.authenticationExpiring"](e):i=e:Logger.warning("Internal inconsistency, LoginProvider callback fired after the corresponding Ditto instance has been deallocated.")})))}else"onlinePlayground"===r.type?this.auth=new OnlineAuthenticator(this.keepAlive,this,{authenticationRequired:function(e){},authenticationExpiringSoon:function(e,t){}}):this.auth=new NotAvailableAuthenticator(this.keepAlive);const _=this.makeDefaultTransportConfig().freeze();this.appID=l,this.siteID=u,this.isX509Valid=d,this.isWebValid=c,this.sync=new Sync(this),this.sync.update({isSyncActive:!1,isX509Valid:d,isWebValid:c,identity:r,ditto:this,transportConfig:_}),this._isActivated=isWebBuild,this.store=new Store(this),this.smallPeerInfo=new SmallPeerInfo(this),this.presence=new Presence(this),this.presenceManager=new PresenceManager(this),this.liveQueryManager=new LiveQueryManager(this,this.keepAlive),this.attachmentFetcherManager=new AttachmentFetcherManager(this),this.transportConditionsManager=new TransportConditionsManager(this),this.subscriptionManager=new SubscriptionManager(this),null!=i&&this.auth["@ditto.authenticationExpiring"](i)}static disableDeadlockDetection(){}static hasDeadlockDetection(){return!1}static isEnvironmentSupported(){let e,t=!1;"undefined"!=typeof window&&window.navigator&&window.navigator.userAgent&&window.navigator.appVersion&&(t=-1!==window.navigator.userAgent.indexOf("MSIE")||window.navigator.appVersion.indexOf("Trident/")>-1);try{e=checkAPIs()}catch(e){throw new Error(`Error checking environment support: ${e}`)}return!t&&e}static initPersistenceDirectory(e){let t;if(null==e)t="ditto";else{if(0===e.trim().length)throw new Error(`Invalid argument for path parameter: '${e}'`);t=e}return t}setOfflineOnlyLicenseToken(e){Logger.info("Offline license token are ignored on web builds. Token validation will be skipped."),IdentityTypesRequiringOfflineLicenseToken.includes(this.identity.type)?(this._isActivated=!1,mapFFIErrors((()=>tryVerifyLicense(e))),this._isActivated=!0):Logger.error(`The identity type '${this.identity.type}' does not require an offline license token.`)}get transportConfig(){return this.sync.parameters.transportConfig}setTransportConfig(e){const t=e.copy().freeze(),n=this.identity,r=this.isWebValid,i=this.isX509Valid;this.sync.update({transportConfig:t,identity:n,isWebValid:r,isX509Valid:i,isSyncActive:this.isSyncActive,ditto:this});const o=transportConfigToSerializable(t),a=CBOR.encode(o),s=Bridge.ditto.handleFor(this);this.deferClose((()=>{dittoSmallPeerInfoCollectionSetTransportConfigData(s.deref(),a)}))}updateTransportConfig(e){const t=this.transportConfig.copy();return e(t),this.setTransportConfig(t),this}startSync(){this.setSyncActive(!0)}stopSync(){this.setSyncActive(!1)}observePeers(e){Logger.warning("`ditto.observePeers()` is deprecated, please use `ditto.presence.observe()` instead.");const t=this.presenceManager.addObserver(e);return new Observer(this.presenceManager,t,{stopsWhenFinalized:!0})}observeTransportConditions(e){const t=this.transportConditionsManager.addObserver(e);return new Observer(this.transportConditionsManager,t,{stopsWhenFinalized:!0})}runGarbageCollection(){const e=Bridge.ditto.handleFor(this);return this.deferClose((()=>{dittoRunGarbageCollection(e.deref())}))}async disableSyncWithV3(){const e=Bridge.ditto.handleFor(this);return this.deferCloseAsync((async()=>{await dittoDisableSyncWithV3(e.deref())}))}async close(){if(!this.isClosed){if(this._isClosed=!0,this.stopSync(),this.store.close(),this.presence.close(),this.auth.close(),this.sync.close(),await this.presenceManager.close(),this.liveQueryManager.close(),this.attachmentFetcherManager.close(),this.transportConditionsManager.close(),this.subscriptionManager.close(),this.keepAlive.isActive)throw new Error("Internal inconsistency, still kept alive after the Ditto object has been close()-ed. ");do{await Promise.allSettled(this.pendingOperations)}while(this.pendingOperations.size>0);this.deferCloseAllowed=!1,await Bridge.ditto.close(this)}}get numPendingOperations(){return this.pendingOperations.size}deferClose(e){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");return e()}async deferCloseAsync(e){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");const t=e();let n;this.pendingOperations.add(t);try{n=await t}finally{this.pendingOperations.delete(t)}return n}authClientValidityChanged(e,t){const n=this.transportConfig,r=this.identity,i=this.isSyncActive;this.isX509Valid,this.isWebValid,this.isX509Valid=t,this.isWebValid=e,this.auth["@ditto.authClientValidityChanged"](e,t),this.sync.update({transportConfig:n,identity:r,isWebValid:e,isX509Valid:t,isSyncActive:i,ditto:this})}validateIdentity(e){const t={...e},n=e.appID;if(!["offlinePlayground","sharedKey","manual","onlinePlayground","onlineWithAuthentication"].includes(e.type))throw new Error(`Can't create Ditto instance, unknown identity type: ${e.type}`);if(("offlinePlayground"===e.type||"sharedKey"===e.type||"onlinePlayground"===e.type||"onlineWithAuthentication"===e.type)&&void 0===n)throw new Error("Property .appID must be given for identity, but isn't.");if(void 0!==n&&"string"!=typeof n)throw new Error(`Property .appID must be be of type string, but is of type '${typeof n}': ${n}`);if(("offlinePlayground"===e.type||"sharedKey"===e.type)&&void 0!==e.siteID){const t=e.siteID;if(!("number"==typeof t||"bigint"==typeof t))throw new Error("Can't create Ditto instance, siteID must be a number or BigInt");if(t<0)throw new Error("Can't create Ditto instance, siteID must be >= 0");if(t>BigInt("0xffffffffffffffff"))throw new Error("Can't create Ditto instance, siteID must be < 2^64")}if(e.type,e.type,"onlinePlayground"===e.type){const t=e.token;if(void 0===t)throw new Error("Property .token must be given for identity but isn't. You can find the corresponding token on the Ditto Portal.");if(void 0!==t&&"string"!=typeof t)throw new Error(`Property .token of identity must be be of type string, but is of type '${typeof t}': ${t}`)}return e.type,t}setSyncActive(e){const t=Bridge.ditto.handleFor(this);this.deferClose((()=>{if(e&&IdentityTypesRequiringOfflineLicenseToken.includes(this.identity.type)&&!this.isActivated)throw new Error("Sync could not be started because Ditto has not yet been activated. This can be achieved with a successful call to `setOfflineOnlyLicenseToken`. If you need to obtain a license token then please visit https://portal.ditto.live.");!this.isSyncActive&&e&&this.keepAlive.retain("sync"),this.isSyncActive&&!e&&this.keepAlive.release("sync"),this._isSyncActive=e;const n=this.isWebValid,r=this.isX509Valid,i=this.identity,o=this.transportConfig;this._deviceName=dittoSetDeviceName(t.deref(),this.deviceName),this.sync.update({identity:i,transportConfig:o,isWebValid:n,isX509Valid:r,isSyncActive:!!e,ditto:this})}))}makeDefaultTransportConfig(){const e=Bridge.ditto.handleFor(this);return this.deferClose((()=>{const t=new TransportConfig;return transportsBLEIsAvailable(e.deref())&&(t.peerToPeer.bluetoothLE.isEnabled=!0),transportsAWDLIsAvailable(e.deref())&&(t.peerToPeer.awdl.isEnabled=!0),transportsLANIsAvailable(e.deref())&&(t.peerToPeer.lan.isEnabled=!0),t.freeze()}))}}const checkAPIs=e=>{const t=e||globalThis||global||window;return["BigInt","WeakRef","FinalizationRegistry"].every((e=>!!t[e]))},disableDeadlockTimeoutWhenDebugging=()=>{},CUSTOM_INSPECT_SYMBOL=Symbol.for("nodejs.util.inspect.custom");class QueryResultItem{get value(){if(this.materialize(),void 0===this.materializedValue)throw new Error("Internal Error: Materialized value is undefined");return this.materializedValue}get isMaterialized(){return void 0!==this.materializedValue}materialize(){if(!this.isMaterialized){const e=this.cborData();let t;try{t=CBOR.decode(e)}catch(e){throw new Error(`Internal inconsistency: CBOR decoding error while materializing result item: ${e.message}`)}if(void 0===t)throw new Error("Internal inconsistency: Materialized value is undefined");this.materializedValue=t}}dematerialize(){this.materializedValue=void 0}cborData(){return queryResultItemCBOR(Bridge.queryResultItem.handleFor(this).deref())}jsonString(){return queryResultItemJSON(Bridge.queryResultItem.handleFor(this).deref())}[CUSTOM_INSPECT_SYMBOL](e,t,n){return customInspectRepresentation(this,n)}constructor(){}}function getBridgeLoad(){const e={};return Bridge.all.map((t=>{const n=t.deref();return n?0===n.count?null:void(e[n.type.name]=n.count):null})),e}class StaticTCPClient{}class WebsocketClient{}Bridge.attachment.registerType(Attachment),Bridge.connectionRequest.registerType(ConnectionRequest),Bridge.document.registerType(Document),Bridge.queryResultItem.registerType(QueryResultItem),Bridge.queryResult.registerType(QueryResult),Bridge.mutableDocument.registerType(MutableDocument),Bridge.staticTCPClient.registerType(StaticTCPClient),Bridge.websocketClient.registerType(WebsocketClient),Bridge.ditto.registerType(Ditto);export{Attachment,AttachmentFetcher,AttachmentToken,Authenticator,BasePendingCursorOperation,BasePendingIDSpecificOperation,CBOR,Collection,CollectionsEvent,ConnectionRequest,Counter,Ditto,DittoError,Document,DocumentID,DocumentPath,ERROR_CODES,IdentityTypesRequiringOfflineLicenseToken,KeepAlive,LiveQuery,LiveQueryEventInitial,LiveQueryEventUpdate,Logger,MutableCounter,MutableDocument,MutableDocumentPath,MutableRegister,NotAvailableAuthenticator,Observer,OnlineAuthenticator,PendingCollectionsOperation,PendingCursorOperation,PendingIDSpecificOperation,Presence,QueryResult,QueryResultItem,Register,SingleDocumentLiveQueryEvent,SmallPeerInfo,Store,StoreObserver,Subscription,Sync,SyncSubscription,TransportConfig,UpdateResult,UpdateResultsMap,WriteTransaction,WriteTransactionCollection,WriteTransactionPendingCursorOperation,WriteTransactionPendingIDSpecificOperation,addressToString,checkAPIs,disableDeadlockTimeoutWhenDebugging,getBridgeLoad,init,mapFFIErrors,mapFFIErrorsAsync,transportConfigFromDeserializable,transportConfigToSerializable,validateAttachmentMetadata,validateDocumentIDCBOR,validateDocumentIDValue};
|
|
2
2
|
//# sourceMappingURL=ditto.es6.js.map
|