@dittolive/ditto 4.5.3 → 4.5.4-alpha.1
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/DittoReactNative.podspec +1 -1
- 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-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 +8 -1
- package/react-native/android/.project +34 -0
- package/react-native/android/build.gradle +2 -2
- package/web/ditto.es6.js +1 -1
- package/web/ditto.umd.js +1 -1
- package/web/ditto.wasm +0 -0
- package/node/ditto.cjs.js.map +0 -1
- package/node/ditto.cjs.pretty.js +0 -9657
- package/node/ditto.cjs.pretty.js.map +0 -1
- package/types/ditto.d.ts.map +0 -1
- package/web/ditto.es6.js.map +0 -1
- package/web/ditto.es6.pretty.js +0 -12600
- package/web/ditto.es6.pretty.js.map +0 -1
- package/web/ditto.umd.js.map +0 -1
- package/web/ditto.umd.pretty.js +0 -12669
- package/web/ditto.umd.pretty.js.map +0 -1
package/web/ditto.es6.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
class KeepAlive{get isActive(){return this.intervalID!==null}constructor(){this.countsByID={};this.intervalID=null}retain(id){if(typeof this.countsByID[id]==="undefined"){this.countsByID[id]=0}this.countsByID[id]+=1;if(this.intervalID===null){const maxDelay=2147483647;this.intervalID=setInterval((()=>{}),maxDelay);KeepAlive.finalizationRegistry.register(this,this.intervalID,this)}}release(id){if(typeof this.countsByID[id]==="undefined"){throw new Error(`Internal inconsistency, trying to release a keep-alive ID that hasn't been retained before or isn't tracked anymore: ${id}`)}this.countsByID[id]-=1;if(this.countsByID[id]===0){delete this.countsByID[id]}if(Object.keys(this.countsByID).length===0){KeepAlive.finalizationRegistry.unregister(this);clearInterval(this.intervalID);this.intervalID=null}}currentIDs(){return Object.keys(this.countsByID)}countForID(id){var _a;return(_a=this.countsByID[id])!==null&&_a!==void 0?_a:null}}KeepAlive.finalizationRegistry=new FinalizationRegistry(clearInterval);class Observer{get token(){return this._token}constructor(observerManager,token,options={}){this.observerManager=observerManager;this._token=token;this.options=options;if(options.stopsWhenFinalized){Observer.finalizationRegistry.register(this,{observerManager:observerManager,token:token},this)}}get isStopped(){return this.token!==undefined&&this.observerManager.hasObserver(this.token)}stop(){const token=this.token;if(token){delete this._token;Observer.finalizationRegistry.unregister(this);this.observerManager.removeObserver(token)}}static finalize(observerManagerAndToken){const{observerManager:observerManager,token:token}=observerManagerAndToken;observerManager.removeObserver(token)}}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"(mutDoc,path,value){const counter=mutDoc?new MutableCounter(privateToken$1):new Counter;counter.mutDoc=mutDoc;counter.path=path;counter._value=value;return counter}}class MutableCounter extends Counter{increment(amount){const mutDoc=this.mutDoc;const path=this.path;if(!mutDoc){throw new Error(`Can't increment counter, only possible within the closure of a collection's update() method.`)}mutDoc.at(path)["@ditto.increment"](amount);this._value+=amount}constructor(){if(arguments[0]===privateToken$1){super()}else{throw new Error(`MutableCounter constructor is for internal use only.`)}}}const privateToken="@ditto.ff82dae89821c5ab822a8b539056bce4";class Register{get value(){return this["@ditto.value"]}constructor(value){this["@ditto.value"]=value}static"@ditto.create"(mutableDocument,path,value){const register=mutableDocument?new MutableRegister(value,privateToken):new Register(value);register["@ditto.mutableDocument"]=mutableDocument;register["@ditto.path"]=path;register["@ditto.value"]=value;return register}}class MutableRegister extends Register{get value(){return super.value}set value(value){this.set(value)}set(value){const mutableDocument=this["@ditto.mutableDocument"];const path=this["@ditto.path"];mutableDocument.at(path)["@ditto.set"](value);this["@ditto.value"]=value}constructor(value){if(arguments[1]===privateToken){super(value)}else{throw new Error(`MutableRegister constructor is for internal use only.`)}}}function to_string(value){return value.toString()}function is_number(value){return typeof value==="number"}function try_downsize(value){switch(typeof value){case"bigint":if(-Number.MAX_SAFE_INTEGER<=value&&value<=Number.MAX_SAFE_INTEGER){return Number(value)}case"number":return value;default:throw new Error(`number or bigint expected, got \`${value}\``)}}function from_string(repr){return BigInt(repr)}function get_element(arr,idx){return arr[idx]}function typeof_(x){return typeof x}function mk_send_ret(){return function send_ret(arg){return arg}}let wasm;const heap=new Array(128).fill(undefined);heap.push(undefined,null,true,false);function getObject(idx){return heap[idx]}let heap_next=heap.length;function dropObject(idx){if(idx<132)return;heap[idx]=heap_next;heap_next=idx}function takeObject(idx){const ret=getObject(idx);dropObject(idx);return ret}function _assertBoolean(n){if(typeof n!=="boolean"){throw new Error("expected a boolean argument")}}const cachedTextDecoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf-8",{ignoreBOM:true,fatal:true}):{decode:()=>{throw Error("TextDecoder not available")}};if(typeof TextDecoder!=="undefined"){cachedTextDecoder.decode()}let cachedUint8Memory0=null;function getUint8Memory0(){if(cachedUint8Memory0===null||cachedUint8Memory0.byteLength===0){cachedUint8Memory0=new Uint8Array(wasm.memory.buffer)}return cachedUint8Memory0}function getStringFromWasm0(ptr,len){ptr=ptr>>>0;return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr,ptr+len))}function addHeapObject(obj){if(heap_next===heap.length)heap.push(heap.length+1);const idx=heap_next;heap_next=heap[idx];if(typeof heap_next!=="number")throw new Error("corrupt heap");heap[idx]=obj;return idx}let WASM_VECTOR_LEN=0;const cachedTextEncoder=typeof TextEncoder!=="undefined"?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}};const encodeString=typeof cachedTextEncoder.encodeInto==="function"?function(arg,view){return cachedTextEncoder.encodeInto(arg,view)}:function(arg,view){const buf=cachedTextEncoder.encode(arg);view.set(buf);return{read:arg.length,written:buf.length}};function passStringToWasm0(arg,malloc,realloc){if(typeof arg!=="string")throw new Error("expected a string argument");if(realloc===undefined){const buf=cachedTextEncoder.encode(arg);const ptr=malloc(buf.length,1)>>>0;getUint8Memory0().subarray(ptr,ptr+buf.length).set(buf);WASM_VECTOR_LEN=buf.length;return ptr}let len=arg.length;let ptr=malloc(len,1)>>>0;const mem=getUint8Memory0();let offset=0;for(;offset<len;offset++){const code=arg.charCodeAt(offset);if(code>127)break;mem[ptr+offset]=code}if(offset!==len){if(offset!==0){arg=arg.slice(offset)}ptr=realloc(ptr,len,len=offset+arg.length*3,1)>>>0;const view=getUint8Memory0().subarray(ptr+offset,ptr+len);const ret=encodeString(arg,view);if(ret.read!==arg.length)throw new Error("failed to pass whole string");offset+=ret.written}WASM_VECTOR_LEN=offset;return ptr}function isLikeNone(x){return x===undefined||x===null}let cachedInt32Memory0=null;function getInt32Memory0(){if(cachedInt32Memory0===null||cachedInt32Memory0.byteLength===0){cachedInt32Memory0=new Int32Array(wasm.memory.buffer)}return cachedInt32Memory0}function debugString(val){const type=typeof val;if(type=="number"||type=="boolean"||val==null){return`${val}`}if(type=="string"){return`"${val}"`}if(type=="symbol"){const description=val.description;if(description==null){return"Symbol"}else{return`Symbol(${description})`}}if(type=="function"){const name=val.name;if(typeof name=="string"&&name.length>0){return`Function(${name})`}else{return"Function"}}if(Array.isArray(val)){const length=val.length;let debug="[";if(length>0){debug+=debugString(val[0])}for(let i=1;i<length;i++){debug+=", "+debugString(val[i])}debug+="]";return debug}const builtInMatches=/\[object ([^\]]+)\]/.exec(toString.call(val));let className;if(builtInMatches.length>1){className=builtInMatches[1]}else{return toString.call(val)}if(className=="Object"){try{return"Object("+JSON.stringify(val)+")"}catch(_){return"Object"}}if(val instanceof Error){return`${val.name}: ${val.message}\n${val.stack}`}return className}const CLOSURE_DTORS=new FinalizationRegistry((state=>{wasm.__wbindgen_export_2.get(state.dtor)(state.a,state.b)}));function makeMutClosure(arg0,arg1,dtor,f){const state={a:arg0,b:arg1,cnt:1,dtor:dtor};const real=(...args)=>{state.cnt++;const a=state.a;state.a=0;try{return f(a,state.b,...args)}finally{if(--state.cnt===0){wasm.__wbindgen_export_2.get(state.dtor)(a,state.b);CLOSURE_DTORS.unregister(state)}else{state.a=a}}};real.original=state;CLOSURE_DTORS.register(real,state,state);return real}function logError(f,args){try{return f.apply(this,args)}catch(e){let error=function(){try{return e instanceof Error?`${e.message}\n\nStack:\n${e.stack}`:e.toString()}catch(_){return"<failed to stringify thrown value>"}}();console.error("wasm-bindgen: imported JS function that was not marked as `catch` threw an error:",error);throw e}}function _assertNum(n){if(typeof n!=="number")throw new Error("expected a number argument")}function __wbg_adapter_32(arg0,arg1,arg2){_assertNum(arg0);_assertNum(arg1);wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h6d443cc9da6424bb(arg0,arg1,addHeapObject(arg2))}function __wbg_adapter_35(arg0,arg1,arg2){_assertNum(arg0);_assertNum(arg1);wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h2505296960a4ca1a(arg0,arg1,addHeapObject(arg2))}function __wbg_adapter_38(arg0,arg1){_assertNum(arg0);_assertNum(arg1);wasm._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hd0e0bfbc8ee80183(arg0,arg1)}function __wbg_adapter_41(arg0,arg1,arg2){_assertNum(arg0);_assertNum(arg1);wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h1e0998a07bccf5bf(arg0,arg1,addHeapObject(arg2))}function ditto_sdk_transports_awdl_is_available(_ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_awdl_is_available(retptr,addHeapObject(_ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_sdk_transports_lan_is_available(_ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_lan_is_available(retptr,addHeapObject(_ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_sdk_transports_ble_is_available(_ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_ble_is_available(retptr,addHeapObject(_ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_sdk_transports_init(out_error){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_init(retptr,addHeapObject(out_error));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_sdk_transports_error_free(it){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_error_free(retptr,addHeapObject(it));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_sdk_transports_error_value(it){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_error_value(retptr,addHeapObject(it));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_sdk_transports_error_new(){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_error_new(retptr);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_free(document){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_free(retptr,addHeapObject(document));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_get_cbor_with_path_type(document,pointer,path_type){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_get_cbor_with_path_type(retptr,addHeapObject(document),addHeapObject(pointer),addHeapObject(path_type));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_remove(document,pointer){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_remove(retptr,addHeapObject(document),addHeapObject(pointer));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_set_cbor_with_timestamp(document,pointer,cbor,_timestamp){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_set_cbor_with_timestamp(retptr,addHeapObject(document),addHeapObject(pointer),addHeapObject(cbor),addHeapObject(_timestamp));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_set_cbor(document,pointer,cbor){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_set_cbor(retptr,addHeapObject(document),addHeapObject(pointer),addHeapObject(cbor));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_increment_counter(document,pointer,amount){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_increment_counter(retptr,addHeapObject(document),addHeapObject(pointer),addHeapObject(amount));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_id(document){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_id(retptr,addHeapObject(document));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_experimental_remove_dql_subscription(ditto,query,query_args_cbor){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_experimental_remove_dql_subscription(retptr,addHeapObject(ditto),addHeapObject(query),addHeapObject(query_args_cbor));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_experimental_add_dql_subscription(ditto,query,query_args_cbor){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_experimental_add_dql_subscription(retptr,addHeapObject(ditto),addHeapObject(query),addHeapObject(query_args_cbor));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_add_subscription(ditto,coll_name,query,query_args_cbor,js_order_by,limit,offset){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_add_subscription(retptr,addHeapObject(ditto),addHeapObject(coll_name),addHeapObject(query),addHeapObject(query_args_cbor),addHeapObject(js_order_by),addHeapObject(limit),addHeapObject(offset));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_remove_subscription(ditto,coll_name,query,query_args_cbor,js_order_by,limit,offset){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_remove_subscription(retptr,addHeapObject(ditto),addHeapObject(coll_name),addHeapObject(query),addHeapObject(query_args_cbor),addHeapObject(js_order_by),addHeapObject(limit),addHeapObject(offset));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_experimental_exec_statement_str(ditto,txn,statement,args_cbor){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_experimental_exec_statement_str(retptr,addHeapObject(ditto),addHeapObject(txn),addHeapObject(statement),addHeapObject(args_cbor));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_get(ditto,coll_name,id,transaction){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_get(retptr,addHeapObject(ditto),addHeapObject(coll_name),addHeapObject(id),addHeapObject(transaction));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_remove(ditto,coll_name,transaction,id){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_remove(retptr,addHeapObject(ditto),addHeapObject(coll_name),addHeapObject(transaction),addHeapObject(id));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_evict(ditto,coll_name,transaction,id){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_evict(retptr,addHeapObject(ditto),addHeapObject(coll_name),addHeapObject(transaction),addHeapObject(id));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_update_multiple(ditto,coll_name,transaction,documents){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_update_multiple(retptr,addHeapObject(ditto),addHeapObject(coll_name),addHeapObject(transaction),addHeapObject(documents));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_update(ditto,coll_name,transaction,document){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_update(retptr,addHeapObject(ditto),addHeapObject(coll_name),addHeapObject(transaction),addHeapObject(document));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_insert_value(ditto,coll_name,doc_cbor,write_strategy,log_hint,txn){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_insert_value(retptr,addHeapObject(ditto),addHeapObject(coll_name),addHeapObject(doc_cbor),addHeapObject(write_strategy),addHeapObject(log_hint),addHeapObject(txn));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_get_collection_names(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_collection_names(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_documents_hash(documents){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_documents_hash(retptr,addHeapObject(documents));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_documents_hash_mnemonic(documents){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_documents_hash_mnemonic(retptr,addHeapObject(documents));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_evict_query_str(ditto,coll_name,txn,query,query_args_cbor,js_order_by,limit,offset){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_evict_query_str(retptr,addHeapObject(ditto),addHeapObject(coll_name),addHeapObject(txn),addHeapObject(query),addHeapObject(query_args_cbor),addHeapObject(js_order_by),addHeapObject(limit),addHeapObject(offset));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_remove_query_str(ditto,coll_name,txn,query,query_args_cbor,js_order_by,limit,offset){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_remove_query_str(retptr,addHeapObject(ditto),addHeapObject(coll_name),addHeapObject(txn),addHeapObject(query),addHeapObject(query_args_cbor),addHeapObject(js_order_by),addHeapObject(limit),addHeapObject(offset));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_exec_query_str(ditto,coll_name,txn,query,query_args_cbor,js_order_by_params,limit,offset){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_exec_query_str(retptr,addHeapObject(ditto),addHeapObject(coll_name),addHeapObject(txn),addHeapObject(query),addHeapObject(query_args_cbor),addHeapObject(js_order_by_params),addHeapObject(limit),addHeapObject(offset));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function jsDocsToCDocs(array){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.jsDocsToCDocs(retptr,addHeapObject(array));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_write_transaction_rollback(_ditto,transaction){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction_rollback(retptr,addHeapObject(_ditto),addHeapObject(transaction));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_write_transaction_commit(ditto,transaction){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction_commit(retptr,addHeapObject(ditto),addHeapObject(transaction));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_write_transaction(ditto,log_hint){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction(retptr,addHeapObject(ditto),addHeapObject(log_hint));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_read_transaction_free(transaction){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_read_transaction_free(retptr,addHeapObject(transaction));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_read_transaction(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_read_transaction(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_presence_v1_callback(ditto,cb_arg){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_presence_v1_callback(retptr,addHeapObject(ditto),addHeapObject(cb_arg));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_presence_v3_callback(ditto,cb_arg){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_presence_v3_callback(retptr,addHeapObject(ditto),addHeapObject(cb_arg));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_logout(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_logout(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_login_with_credentials(ditto,username,password,provider){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_login_with_credentials(retptr,addHeapObject(ditto),addHeapObject(username),addHeapObject(password),addHeapObject(provider));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_login_with_token(ditto,token,provider){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_login_with_token(retptr,addHeapObject(ditto),addHeapObject(token),addHeapObject(provider));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_is_x509_valid(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_is_x509_valid(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_is_web_valid(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_is_web_valid(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_user_id(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_user_id(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_get_app_id(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_get_app_id(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_get_site_id(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_get_site_id(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_set_login_provider(ditto,login_provider){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_set_login_provider(retptr,addHeapObject(ditto),addHeapObject(login_provider));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_manual_v0(config_cbor_b64){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_manual_v0(retptr,addHeapObject(config_cbor_b64));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_shared_key(app_id,key_der_b64,site_id){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_shared_key(retptr,addHeapObject(app_id),addHeapObject(key_der_b64),addHeapObject(site_id));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_offline_playground(app_id,site_id){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_offline_playground(retptr,addHeapObject(app_id),addHeapObject(site_id));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_online_playground(app_id,shared_token,base_url){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_online_playground(retptr,addHeapObject(app_id),addHeapObject(shared_token),addHeapObject(base_url));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_online_with_authentication(app_id,base_url){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_online_with_authentication(retptr,addHeapObject(app_id),addHeapObject(base_url));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_make_login_provider(js_expiring_cb){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_login_provider(retptr,addHeapObject(js_expiring_cb));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_set_validity_listener(ditto,js_validity_update_cb){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_set_validity_listener(retptr,addHeapObject(ditto),addHeapObject(js_validity_update_cb));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_dql_response_affected_document_id_at(response,idx){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_dql_response_affected_document_id_at(retptr,addHeapObject(response),addHeapObject(idx));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_dql_response_affected_document_id_count(response){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_dql_response_affected_document_id_count(retptr,addHeapObject(response));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_dql_response_result_at(response,idx){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_dql_response_result_at(retptr,addHeapObject(response),addHeapObject(idx));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_dql_response_result_count(response){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_dql_response_result_count(retptr,addHeapObject(response));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_dql_response_free(response){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_dql_response_free(retptr,addHeapObject(response));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_dql_result_free(result){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_dql_result_free(retptr,addHeapObject(result));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_result_json(result){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_result_json(retptr,addHeapObject(result));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_result_cbor(result){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_result_cbor(retptr,addHeapObject(result));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_signal_available_next(ditto,id){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_signal_available_next(retptr,addHeapObject(ditto),addHeapObject(id));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_stop(ditto,id){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_stop(retptr,addHeapObject(ditto),addHeapObject(id));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_experimental_webhook_register_dql_live_query_str(ditto,query,query_args_cbor,url){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_experimental_webhook_register_dql_live_query_str(retptr,addHeapObject(ditto),addHeapObject(query),addHeapObject(query_args_cbor),addHeapObject(url));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_start(ditto,id){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_start(retptr,addHeapObject(ditto),addHeapObject(id));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_register_str_detached(ditto,coll_name,query,query_args_cbor,js_order_by,limit,offset,cb){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_register_str_detached(retptr,addHeapObject(ditto),addHeapObject(coll_name),addHeapObject(query),addHeapObject(query_args_cbor),addHeapObject(js_order_by),addHeapObject(limit),addHeapObject(offset),addHeapObject(cb));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_experimental_register_change_observer_str_detached(ditto,query,query_args_cbor,cb){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_experimental_register_change_observer_str_detached(retptr,addHeapObject(ditto),addHeapObject(query),addHeapObject(query_args_cbor),addHeapObject(cb));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_webhook_register_str(ditto,coll_name,query,js_order_by,limit,offset,url){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_webhook_register_str(retptr,addHeapObject(ditto),addHeapObject(coll_name),addHeapObject(query),addHeapObject(js_order_by),addHeapObject(limit),addHeapObject(offset),addHeapObject(url));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_validate_document_id(cbor,out_cbor){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_validate_document_id(retptr,addHeapObject(cbor),addHeapObject(out_cbor));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_id_query_compatible(id,string_primitive_format){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_id_query_compatible(retptr,addHeapObject(id),addHeapObject(string_primitive_format));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_get_sync_scope(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_get_sync_scope(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_sync_scope(ditto,scope){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_sync_scope(retptr,addHeapObject(ditto),addHeapObject(scope));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_get_is_enabled(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_get_is_enabled(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_enabled(ditto,set_enabled){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_enabled(retptr,addHeapObject(ditto),addHeapObject(set_enabled));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_get_metadata(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_get_metadata(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_metadata(ditto,metadata){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_metadata(retptr,addHeapObject(ditto),addHeapObject(metadata));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_transport_config_data(ditto,cbor){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_transport_config_data(retptr,addHeapObject(ditto),addHeapObject(cbor));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_init_sdk_version(platform,language,sdk_semver){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_init_sdk_version(retptr,addHeapObject(platform),addHeapObject(language),addHeapObject(sdk_semver));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_get_sdk_semver(){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_get_sdk_semver(retptr);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_get_sdk_version(){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_sdk_version(retptr);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_disable_sync_with_v3(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_disable_sync_with_v3(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_run_garbage_collection(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_run_garbage_collection(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_sync_group(ditto,sync_group){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_sync_group(retptr,addHeapObject(ditto),addHeapObject(sync_group));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_connect_retry_interval(ditto,retry_interval_millis){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_connect_retry_interval(retptr,addHeapObject(ditto),addHeapObject(retry_interval_millis));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_device_name(ditto,device_name){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_device_name(retptr,addHeapObject(ditto),addHeapObject(device_name));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_presence_v3(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_presence_v3(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_presence_v1(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_presence_v1(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_clear_presence_v3_callback(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_clear_presence_v3_callback(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_clear_presence_callback(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_clear_presence_callback(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_free(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_free(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_shutdown(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_shutdown(retptr,addHeapObject(ditto));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_make(uninit_ditto,identity_config,history_tracking){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_make(retptr,addHeapObject(uninit_ditto),addHeapObject(identity_config),addHeapObject(history_tracking));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_uninitialized_ditto_make(working_dir){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_uninitialized_ditto_make(retptr,addHeapObject(working_dir));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_static_websocket_clients(ditto,list_of_servers,routing_hint){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_static_websocket_clients(retptr,addHeapObject(ditto),addHeapObject(list_of_servers),addHeapObject(routing_hint));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_transport_condition_changed_callback(js_ptr,js_fun_or_null){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_transport_condition_changed_callback(retptr,addHeapObject(js_ptr),addHeapObject(js_fun_or_null));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_error_message(){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_error_message(retptr);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_cancel_resolve_attachment(ditto,id,cancel_token){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_cancel_resolve_attachment(retptr,addHeapObject(ditto),addHeapObject(id),addHeapObject(cancel_token));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_free_attachment_handle(handle){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_free_attachment_handle(retptr,addHeapObject(handle));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_get_complete_attachment_data(ditto,handle){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_complete_attachment_data(retptr,addHeapObject(ditto),addHeapObject(handle));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_new_attachment_from_bytes(ditto,bytes,out_attachment){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_new_attachment_from_bytes(retptr,addHeapObject(ditto),addHeapObject(bytes),addHeapObject(out_attachment));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_resolve_attachment(ditto,id,on_complete_cb,on_progress_cb,on_deleted_cb){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_resolve_attachment(retptr,addHeapObject(ditto),addHeapObject(id),addHeapObject(on_complete_cb),addHeapObject(on_progress_cb),addHeapObject(on_deleted_cb));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_log(level,msg){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_log(retptr,addHeapObject(level),addHeapObject(msg));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_minimum_log_level_get(){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_minimum_log_level_get(retptr);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_minimum_log_level(log_level){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_minimum_log_level(retptr,addHeapObject(log_level));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_emoji_headings_enabled_get(){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_emoji_headings_enabled_get(retptr);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_emoji_headings_enabled(enabled){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_emoji_headings_enabled(retptr,addHeapObject(enabled));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_enabled_get(){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_enabled_get(retptr);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_enabled(enabled){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_enabled(retptr,addHeapObject(enabled));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_init(){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_init(retptr);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_set_log_file(log_file){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_set_log_file(retptr,addHeapObject(log_file));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_set_custom_log_cb(arg){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_set_custom_log_cb(retptr,addHeapObject(arg));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_error_description(error){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_error_description(retptr,addHeapObject(error));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_error_code(error){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_error_code(retptr,addHeapObject(error));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_error_free(error){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_error_free(retptr,addHeapObject(error));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function websocket_client_free_handle(handle){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.websocket_client_free_handle(retptr,addHeapObject(handle));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_verify_license(license,out_err_msg){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_verify_license(retptr,addHeapObject(license),addHeapObject(out_err_msg));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function handleError(f,args){try{return f.apply(this,args)}catch(e){wasm.__wbindgen_exn_store(addHeapObject(e))}}function notDefined(what){return()=>{throw new Error(`${what} is not defined`)}}function getArrayU8FromWasm0(ptr,len){ptr=ptr>>>0;return getUint8Memory0().subarray(ptr/1,ptr/1+len)}function __wbg_adapter_391(arg0,arg1,arg2,arg3){_assertNum(arg0);_assertNum(arg1);wasm.wasm_bindgen__convert__closures__invoke2_mut__h72a3eb6b57359c1f(arg0,arg1,addHeapObject(arg2),addHeapObject(arg3))}function boxCStringIntoString(arg){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.boxCStringIntoString(retptr,addHeapObject(arg));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function refCStringToString(arg){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.refCStringToString(retptr,addHeapObject(arg));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function boxCBytesIntoBuffer(arg){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.boxCBytesIntoBuffer(retptr,addHeapObject(arg));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function withOutPtr$1(ty,cb){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.withOutPtr(retptr,addHeapObject(ty),addHeapObject(cb));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function withOutBoxCBytes(cb){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.withOutBoxCBytes(retptr,addHeapObject(cb));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function cStringVecToStringArray(arg){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.cStringVecToStringArray(retptr,addHeapObject(arg));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];if(r2){throw takeObject(r1)}return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}async function __wbg_load(module,imports){if(typeof Response==="function"&&module instanceof Response){if(typeof WebAssembly.instantiateStreaming==="function"){try{return await WebAssembly.instantiateStreaming(module,imports)}catch(e){if(module.headers.get("Content-Type")!="application/wasm"){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",e)}else{throw e}}}const bytes=await module.arrayBuffer();return await WebAssembly.instantiate(bytes,imports)}else{const instance=await WebAssembly.instantiate(module,imports);if(instance instanceof WebAssembly.Instance){return{instance:instance,module:module}}else{return instance}}}function __wbg_get_imports(){const imports={};imports.wbg={};imports.wbg.__wbindgen_cb_drop=function(arg0){const obj=takeObject(arg0).original;if(obj.cnt--==1){obj.a=0;return true}const ret=false;_assertBoolean(ret);return ret};imports.wbg.__wbindgen_string_new=function(arg0,arg1){const ret=getStringFromWasm0(arg0,arg1);return addHeapObject(ret)};imports.wbg.__wbg_log_f7c904296a5a8ff0=function(){return logError((function(arg0,arg1){let deferred0_0;let deferred0_1;try{deferred0_0=arg0;deferred0_1=arg1;console.log(getStringFromWasm0(arg0,arg1))}finally{wasm.__wbindgen_free(deferred0_0,deferred0_1,1)}}),arguments)};imports.wbg.__wbg_error_f851667af71bcfc6=function(){return logError((function(arg0,arg1){let deferred0_0;let deferred0_1;try{deferred0_0=arg0;deferred0_1=arg1;console.error(getStringFromWasm0(arg0,arg1))}finally{wasm.__wbindgen_free(deferred0_0,deferred0_1,1)}}),arguments)};imports.wbg.__wbg_new_abda76e883ba8a5f=function(){return logError((function(){const ret=new Error;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_stack_658279fe44541cf6=function(){return logError((function(arg0,arg1){const ret=getObject(arg1).stack;const ptr1=passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len1=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len1;getInt32Memory0()[arg0/4+0]=ptr1}),arguments)};imports.wbg.__wbindgen_object_drop_ref=function(arg0){takeObject(arg0)};imports.wbg.__wbindgen_string_get=function(arg0,arg1){const obj=getObject(arg1);const ret=typeof obj==="string"?obj:undefined;var ptr1=isLikeNone(ret)?0:passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);var len1=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len1;getInt32Memory0()[arg0/4+0]=ptr1};imports.wbg.__wbindgen_is_string=function(arg0){const ret=typeof getObject(arg0)==="string";_assertBoolean(ret);return ret};imports.wbg.__wbg_fetch_57429b87be3dcc33=function(){return logError((function(arg0){const ret=fetch(getObject(arg0));return addHeapObject(ret)}),arguments)};imports.wbg.__wbindgen_object_clone_ref=function(arg0){const ret=getObject(arg0);return addHeapObject(ret)};imports.wbg.__wbg_setTimeout_09074a1669d0f224=function(){return handleError((function(arg0,arg1){const ret=setTimeout(getObject(arg0),arg1);_assertNum(ret);return ret}),arguments)};imports.wbg.__wbg_setInterval_fa82463ae3f43f48=function(){return handleError((function(arg0,arg1){const ret=setInterval(getObject(arg0),arg1);_assertNum(ret);return ret}),arguments)};imports.wbg.__wbg_clearTimeout_23ee6db72c0ad922=typeof clearTimeout=="function"?clearTimeout:notDefined("clearTimeout");imports.wbg.__wbg_clearInterval_d5655e407a861314=typeof clearInterval=="function"?clearInterval:notDefined("clearInterval");imports.wbg.__wbg_crypto_e1d53a1d73fb10b8=function(){return logError((function(arg0){const ret=getObject(arg0).crypto;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_msCrypto_6e7d3e1f92610cbb=function(){return logError((function(arg0){const ret=getObject(arg0).msCrypto;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_getRandomValues_805f1c3d65988a5a=function(){return handleError((function(arg0,arg1){getObject(arg0).getRandomValues(getObject(arg1))}),arguments)};imports.wbg.__wbg_randomFillSync_6894564c2c334c42=function(){return handleError((function(arg0,arg1,arg2){getObject(arg0).randomFillSync(getArrayU8FromWasm0(arg1,arg2))}),arguments)};imports.wbg.__wbg_require_78a3dcfbdba9cbce=function(){return handleError((function(){const ret=module.require;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_process_038c26bf42b093f8=function(){return logError((function(arg0){const ret=getObject(arg0).process;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_versions_ab37218d2f0b24a8=function(){return logError((function(arg0){const ret=getObject(arg0).versions;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_node_080f4b19d15bc1fe=function(){return logError((function(arg0){const ret=getObject(arg0).node;return addHeapObject(ret)}),arguments)};imports.wbg.__wbindgen_is_object=function(arg0){const val=getObject(arg0);const ret=typeof val==="object"&&val!==null;_assertBoolean(ret);return ret};imports.wbg.__wbindgen_number_new=function(arg0){const ret=arg0;return addHeapObject(ret)};imports.wbg.__wbg_mksendret_58e4351c0f62e857=function(){return logError((function(){const ret=mk_send_ret();return addHeapObject(ret)}),arguments)};imports.wbg.__wbindgen_error_new=function(arg0,arg1){const ret=new Error(getStringFromWasm0(arg0,arg1));return addHeapObject(ret)};imports.wbg.__wbindgen_is_undefined=function(arg0){const ret=getObject(arg0)===undefined;_assertBoolean(ret);return ret};imports.wbg.__wbindgen_is_null=function(arg0){const ret=getObject(arg0)===null;_assertBoolean(ret);return ret};imports.wbg.__wbg_trydownsize_28e49b8073c2a2fc=function(){return logError((function(arg0){const ret=try_downsize(takeObject(arg0));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_isnumber_c97122a46d4ace09=function(){return logError((function(arg0){const ret=is_number(getObject(arg0));_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbg_tostring_7847f1b7af649ba5=function(){return logError((function(arg0,arg1){const ret=to_string(getObject(arg1));const ptr1=passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len1=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len1;getInt32Memory0()[arg0/4+0]=ptr1}),arguments)};imports.wbg.__wbg_fromstring_721719aff319c1fe=function(){return logError((function(arg0,arg1){const ret=from_string(getStringFromWasm0(arg0,arg1));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_getelement_cd48f1e89008c242=function(){return logError((function(arg0,arg1){const ret=get_element(getObject(arg0),arg1>>>0);return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_typeof_cb5c1bc26a697ea8=function(){return logError((function(arg0,arg1){const ret=typeof_(getObject(arg1));const ptr1=passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len1=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len1;getInt32Memory0()[arg0/4+0]=ptr1}),arguments)};imports.wbg.__wbg_newwithstrandinit_05d7180788420c40=function(){return handleError((function(arg0,arg1,arg2){const ret=new Request(getStringFromWasm0(arg0,arg1),getObject(arg2));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_wasClean_2af04e6cf2076497=function(){return logError((function(arg0){const ret=getObject(arg0).wasClean;_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbg_code_24e161f043adce8a=function(){return logError((function(arg0){const ret=getObject(arg0).code;_assertNum(ret);return ret}),arguments)};imports.wbg.__wbg_reason_40159cc3d2fc655d=function(){return logError((function(arg0,arg1){const ret=getObject(arg1).reason;const ptr1=passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len1=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len1;getInt32Memory0()[arg0/4+0]=ptr1}),arguments)};imports.wbg.__wbg_now_8172cd917e5eda6b=function(){return logError((function(arg0){const ret=getObject(arg0).now();return ret}),arguments)};imports.wbg.__wbg_signal_31753ac644b25fbb=function(){return logError((function(arg0){const ret=getObject(arg0).signal;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_new_6396e586b56e1dff=function(){return handleError((function(){const ret=new AbortController;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_abort_064ae59cda5cd244=function(){return logError((function(arg0){getObject(arg0).abort()}),arguments)};imports.wbg.__wbg_data_7b1f01f4e6a64fbe=function(){return logError((function(arg0){const ret=getObject(arg0).data;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_instanceof_Blob_d18d26355bccfd22=function(){return logError((function(arg0){let result;try{result=getObject(arg0)instanceof Blob}catch{result=false}const ret=result;_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbg_newwithu8arraysequenceandoptions_b0ee96dd3232b69c=function(){return handleError((function(arg0,arg1){const ret=new Blob(getObject(arg0),getObject(arg1));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_new_39f0e6d61fc67f0e=function(){return handleError((function(){const ret=new FormData;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_append_1b70fd81d162ab50=function(){return handleError((function(arg0,arg1,arg2,arg3){getObject(arg0).append(getStringFromWasm0(arg1,arg2),getObject(arg3))}),arguments)};imports.wbg.__wbg_append_32853c33a2dd22f0=function(){return handleError((function(arg0,arg1,arg2,arg3,arg4,arg5){getObject(arg0).append(getStringFromWasm0(arg1,arg2),getObject(arg3),getStringFromWasm0(arg4,arg5))}),arguments)};imports.wbg.__wbg_fetch_749a56934f95c96c=function(){return logError((function(arg0,arg1){const ret=getObject(arg0).fetch(getObject(arg1));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_url_1f1b597f64482fd0=function(){return logError((function(arg0,arg1){const ret=getObject(arg1).url;const ptr1=passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len1=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len1;getInt32Memory0()[arg0/4+0]=ptr1}),arguments)};imports.wbg.__wbg_readyState_9c0f66433e329c9e=function(){return logError((function(arg0){const ret=getObject(arg0).readyState;_assertNum(ret);return ret}),arguments)};imports.wbg.__wbg_setonopen_9ce48dce57e549b5=function(){return logError((function(arg0,arg1){getObject(arg0).onopen=getObject(arg1)}),arguments)};imports.wbg.__wbg_setonerror_02393260b3e29972=function(){return logError((function(arg0,arg1){getObject(arg0).onerror=getObject(arg1)}),arguments)};imports.wbg.__wbg_setonclose_4ce49fd8fd7783fb=function(){return logError((function(arg0,arg1){getObject(arg0).onclose=getObject(arg1)}),arguments)};imports.wbg.__wbg_setonmessage_c5a806b62a0c5607=function(){return logError((function(arg0,arg1){getObject(arg0).onmessage=getObject(arg1)}),arguments)};imports.wbg.__wbg_setbinaryType_ee55743ddf4beb37=function(){return logError((function(arg0,arg1){getObject(arg0).binaryType=takeObject(arg1)}),arguments)};imports.wbg.__wbg_new_d29e507f6606de91=function(){return handleError((function(arg0,arg1){const ret=new WebSocket(getStringFromWasm0(arg0,arg1));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_newwithstrsequence_7b0c4aadc1ae1635=function(){return handleError((function(arg0,arg1,arg2){const ret=new WebSocket(getStringFromWasm0(arg0,arg1),getObject(arg2));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_close_45d053bea59e7746=function(){return handleError((function(arg0){getObject(arg0).close()}),arguments)};imports.wbg.__wbg_send_80b256d87a6779e5=function(){return handleError((function(arg0,arg1,arg2){getObject(arg0).send(getStringFromWasm0(arg1,arg2))}),arguments)};imports.wbg.__wbg_send_640853f8eb0f0385=function(){return handleError((function(arg0,arg1,arg2){getObject(arg0).send(getArrayU8FromWasm0(arg1,arg2))}),arguments)};imports.wbg.__wbg_instanceof_Response_eaa426220848a39e=function(){return logError((function(arg0){let result;try{result=getObject(arg0)instanceof Response}catch{result=false}const ret=result;_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbg_url_74285ddf2747cb3d=function(){return logError((function(arg0,arg1){const ret=getObject(arg1).url;const ptr1=passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len1=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len1;getInt32Memory0()[arg0/4+0]=ptr1}),arguments)};imports.wbg.__wbg_status_c4ef3dd591e63435=function(){return logError((function(arg0){const ret=getObject(arg0).status;_assertNum(ret);return ret}),arguments)};imports.wbg.__wbg_headers_fd64ad685cf22e5d=function(){return logError((function(arg0){const ret=getObject(arg0).headers;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_arrayBuffer_4c27b6f00c530232=function(){return handleError((function(arg0){const ret=getObject(arg0).arrayBuffer();return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_code_b09504754e0520f1=function(){return logError((function(arg0){const ret=getObject(arg0).code;_assertNum(ret);return ret}),arguments)};imports.wbg.__wbg_new_2d0053ee81e4dd2a=function(){return handleError((function(){const ret=new Headers;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_append_de37df908812970d=function(){return handleError((function(arg0,arg1,arg2,arg3,arg4){getObject(arg0).append(getStringFromWasm0(arg1,arg2),getStringFromWasm0(arg3,arg4))}),arguments)};imports.wbg.__wbg_new_898a68150f225f2e=function(){return logError((function(){const ret=new Array;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_push_ca1c26067ef907ac=function(){return logError((function(arg0,arg1){const ret=getObject(arg0).push(getObject(arg1));_assertNum(ret);return ret}),arguments)};imports.wbg.__wbg_instanceof_ArrayBuffer_39ac22089b74fddb=function(){return logError((function(arg0){let result;try{result=getObject(arg0)instanceof ArrayBuffer}catch{result=false}const ret=result;_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbg_valueOf_e39b017d2100ede0=function(){return logError((function(arg0){const ret=getObject(arg0).valueOf();_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbg_newnoargs_581967eacc0e2604=function(){return logError((function(arg0,arg1){const ret=new Function(getStringFromWasm0(arg0,arg1));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_apply_64be369596a02ae0=function(){return handleError((function(arg0,arg1,arg2){const ret=getObject(arg0).apply(getObject(arg1),getObject(arg2));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_call_cb65541d95d71282=function(){return handleError((function(arg0,arg1){const ret=getObject(arg0).call(getObject(arg1));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_call_01734de55d61e11d=function(){return handleError((function(arg0,arg1,arg2){const ret=getObject(arg0).call(getObject(arg1),getObject(arg2));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_next_ddb3312ca1c4e32a=function(){return handleError((function(arg0){const ret=getObject(arg0).next();return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_next_526fc47e980da008=function(){return logError((function(arg0){const ret=getObject(arg0).next;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_done_5c1f01fb660d73b5=function(){return logError((function(arg0){const ret=getObject(arg0).done;_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbg_value_1695675138684bd5=function(){return logError((function(arg0){const ret=getObject(arg0).value;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_valueOf_7d8df3cd4f3f583b=function(){return logError((function(arg0){const ret=getObject(arg0).valueOf();return ret}),arguments)};imports.wbg.__wbg_getTime_5e2054f832d82ec9=function(){return logError((function(arg0){const ret=getObject(arg0).getTime();return ret}),arguments)};imports.wbg.__wbg_new0_c0be7df4b6bd481f=function(){return logError((function(){const ret=new Date;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_now_9c5990bda04c7e53=function(){return logError((function(){const ret=Date.now();return ret}),arguments)};imports.wbg.__wbg_instanceof_Object_3daa8298c86298be=function(){return logError((function(arg0){let result;try{result=getObject(arg0)instanceof Object}catch{result=false}const ret=result;_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbg_new_b51585de1b234aff=function(){return logError((function(){const ret=new Object;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_iterator_97f0c81209c6c35a=function(){return logError((function(){const ret=Symbol.iterator;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_new_43f1b47c28813cbd=function(){return logError((function(arg0,arg1){try{var state0={a:arg0,b:arg1};var cb0=(arg0,arg1)=>{const a=state0.a;state0.a=0;try{return __wbg_adapter_391(a,state0.b,arg0,arg1)}finally{state0.a=a}};const ret=new Promise(cb0);return addHeapObject(ret)}finally{state0.a=state0.b=0}}),arguments)};imports.wbg.__wbg_resolve_53698b95aaf7fcf8=function(){return logError((function(arg0){const ret=Promise.resolve(getObject(arg0));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_then_f7e06ee3c11698eb=function(){return logError((function(arg0,arg1){const ret=getObject(arg0).then(getObject(arg1));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_then_b2267541e2a73865=function(){return logError((function(arg0,arg1,arg2){const ret=getObject(arg0).then(getObject(arg1),getObject(arg2));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_globalThis_1d39714405582d3c=function(){return handleError((function(){const ret=globalThis.globalThis;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_self_1ff1d729e9aae938=function(){return handleError((function(){const ret=self.self;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_window_5f4faef6c12b79ec=function(){return handleError((function(){const ret=window.window;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_global_651f05c6a0944d1c=function(){return handleError((function(){const ret=global.global;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_instanceof_Uint8Array_d8d9cb2b8e8ac1d4=function(){return logError((function(arg0){let result;try{result=getObject(arg0)instanceof Uint8Array}catch{result=false}const ret=result;_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbg_new_8125e318e6245eed=function(){return logError((function(arg0){const ret=new Uint8Array(getObject(arg0));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_newwithlength_e5d69174d6984cd7=function(){return logError((function(arg0){const ret=new Uint8Array(arg0>>>0);return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_newwithbyteoffsetandlength_6da8e527659b86aa=function(){return logError((function(arg0,arg1,arg2){const ret=new Uint8Array(getObject(arg0),arg1>>>0,arg2>>>0);return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_subarray_13db269f57aa838d=function(){return logError((function(arg0,arg1,arg2){const ret=getObject(arg0).subarray(arg1>>>0,arg2>>>0);return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_length_72e2208bbc0efc61=function(){return logError((function(arg0){const ret=getObject(arg0).length;_assertNum(ret);return ret}),arguments)};imports.wbg.__wbg_set_5cf90238115182c3=function(){return logError((function(arg0,arg1,arg2){getObject(arg0).set(getObject(arg1),arg2>>>0)}),arguments)};imports.wbg.__wbg_get_97b561fb56f034b5=function(){return handleError((function(arg0,arg1){const ret=Reflect.get(getObject(arg0),getObject(arg1));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_has_c5fcd020291e56b8=function(){return handleError((function(arg0,arg1){const ret=Reflect.has(getObject(arg0),getObject(arg1));_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbg_set_092e06b0f9d71865=function(){return handleError((function(arg0,arg1,arg2){const ret=Reflect.set(getObject(arg0),getObject(arg1),getObject(arg2));_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbindgen_is_function=function(arg0){const ret=typeof getObject(arg0)==="function";_assertBoolean(ret);return ret};imports.wbg.__wbg_buffer_085ec1f694018c4f=function(){return logError((function(arg0){const ret=getObject(arg0).buffer;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_stringify_e25465938f3f611f=function(){return handleError((function(arg0){const ret=JSON.stringify(getObject(arg0));return addHeapObject(ret)}),arguments)};imports.wbg.__wbindgen_debug_string=function(arg0,arg1){const ret=debugString(getObject(arg1));const ptr1=passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len1=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len1;getInt32Memory0()[arg0/4+0]=ptr1};imports.wbg.__wbindgen_throw=function(arg0,arg1){throw new Error(getStringFromWasm0(arg0,arg1))};imports.wbg.__wbindgen_memory=function(){const ret=wasm.memory;return addHeapObject(ret)};imports.wbg.__wbindgen_closure_wrapper1913=function(){return logError((function(arg0,arg1,arg2){const ret=makeMutClosure(arg0,arg1,3246,__wbg_adapter_32);return addHeapObject(ret)}),arguments)};imports.wbg.__wbindgen_closure_wrapper97452=function(){return logError((function(arg0,arg1,arg2){const ret=makeMutClosure(arg0,arg1,5410,__wbg_adapter_35);return addHeapObject(ret)}),arguments)};imports.wbg.__wbindgen_closure_wrapper146989=function(){return logError((function(arg0,arg1,arg2){const ret=makeMutClosure(arg0,arg1,7955,__wbg_adapter_38);return addHeapObject(ret)}),arguments)};imports.wbg.__wbindgen_closure_wrapper157705=function(){return logError((function(arg0,arg1,arg2){const ret=makeMutClosure(arg0,arg1,8586,__wbg_adapter_41);return addHeapObject(ret)}),arguments)};return imports}function __wbg_finalize_init(instance,module){wasm=instance.exports;init$2.__wbindgen_wasm_module=module;cachedInt32Memory0=null;cachedUint8Memory0=null;return wasm}async function init$2(input){if(wasm!==undefined)return wasm;if(typeof input==="undefined"){throw new Error("Can't load ditto.wasm, expected module to be provided at initialization time but got nothing.")}const imports=__wbg_get_imports();if(typeof input==="string"||typeof Request==="function"&&input instanceof Request||typeof URL==="function"&&input instanceof URL){input=fetch(input)}const{instance:instance,module:module}=await __wbg_load(await input,imports);return __wbg_finalize_init(instance,module)}const isWebBuild=true;const PREFIX_REGEX=new RegExp(/^<.*?>\s*/);class DittoFFIError extends Error{constructor(code,messageOverride,messageFallback){const threadLocalErrorMessage=ffiErrorMessage();super(messageOverride||threadLocalErrorMessage||messageFallback);this.code=code}}function throwOnErrorResult(ffiError,ffiFunctionName){if(ffiError!==null){let errorCode;let errorMsg;try{errorCode=dittoffi_error_code(ffiError);errorMsg=boxCStringIntoString(dittoffi_error_description(ffiError));dittoffi_error_free(ffiError)}catch(err){throw new DittoFFIError(-1,`Failed to retrieve Ditto core error message: ${err.message}`)}if(errorMsg==null){errorMsg=`${ffiFunctionName}() failed with error code: ${errorCode}`}else{errorMsg=errorMsg.replace(PREFIX_REGEX,"")}throw new DittoFFIError(errorCode,errorMsg)}}function ffiErrorMessage(){const errorMessageCString=ditto_error_message();return boxCStringIntoString(errorMessageCString)}const DittoCRDTTypeKey="_ditto_internal_type_jkb12973t4b";const DittoCRDTValueKey="_value";var DittoCRDTType;(function(DittoCRDTType){DittoCRDTType[DittoCRDTType["counter"]=0]="counter";DittoCRDTType[DittoCRDTType["register"]=1]="register";DittoCRDTType[DittoCRDTType["attachment"]=2]="attachment";DittoCRDTType[DittoCRDTType["rga"]=3]="rga";DittoCRDTType[DittoCRDTType["rwMap"]=4]="rwMap"})(DittoCRDTType||(DittoCRDTType={}));function documentSetCBORWithTimestamp(document,path,cbor,timestamp){ensureInitialized();const pathX=bytesFromString(path);const errorCode=ditto_document_set_cbor_with_timestamp(document,pathX,cbor,timestamp);if(errorCode!==0)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${errorCode}`)}function documentSetCBOR(document,path,cbor){ensureInitialized();const pathX=bytesFromString(path);const errorCode=ditto_document_set_cbor(document,pathX,cbor);if(errorCode!==0)throw new Error(errorMessage()||`ditto_document_set_cbor() failed with error code: ${errorCode}`)}function documentID(self){ensureInitialized();const documentIDX=ditto_document_id(self);return boxCBytesIntoBuffer(documentIDX)}function documentGetCBORWithPathType(document,path,pathType){ensureInitialized();const pathBytes=bytesFromString(path);const cborPathResultRaw=ditto_document_get_cbor_with_path_type(document,pathBytes,pathType);const cborPathResult={statusCode:cborPathResultRaw.status_code,cbor:boxCBytesIntoBuffer(cborPathResultRaw.cbor)};return cborPathResult}function documentRemove(document,path){ensureInitialized();const pathBytes=bytesFromString(path);const errorCode=ditto_document_remove(document,pathBytes);if(errorCode!==0)throw new Error(errorMessage()||`ditto_document_remove() failed with error code: ${errorCode}`)}function documentIncrementCounter(document,path,amount){ensureInitialized();const pathBytes=bytesFromString(path);const errorCode=ditto_document_increment_counter(document,pathBytes,amount);if(errorCode!==0)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${errorCode}`)}function documentFree(self){ensureInitialized();ditto_document_free(self)}function documentIDQueryCompatible(docID,stringPrimitiveFormat){ensureInitialized();const docIDString=ditto_document_id_query_compatible(docID,stringPrimitiveFormat);return boxCStringIntoString(docIDString)}function validateDocumentID(docID){ensureInitialized();const cborCBytes=withOutBoxCBytes((outCBOR=>{const errorCode=ditto_validate_document_id(docID,outCBOR);if(errorCode!==0)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${errorCode}`);return outCBOR}));return boxCBytesIntoBuffer(cborCBytes)}async function collectionGet(ditto,collectionName,documentID,readTransaction){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const{status_code:errorCode,document:document}=await ditto_collection_get(ditto,collectionNameX,documentID,readTransaction);if(errorCode===NOT_FOUND_ERROR_CODE)return null;if(errorCode!==0)throw new Error(errorMessage()||`ditto_collection_get() failed with error code: ${errorCode}`);return document}async function collectionInsertValue(ditto,collectionName,doc_cbor,writeStrategy,writeTransaction){ensureInitialized();const collectionNameX=bytesFromString(collectionName);let strategy;switch(writeStrategy){case"merge":strategy="Merge";break;case"insertIfAbsent":strategy="InsertIfAbsent";break;case"insertDefaultIfAbsent":strategy="InsertDefaultIfAbsent";break;default:throw new Error("Invalid write strategy provided")}const{status_code:errorCode,id:id}=await ditto_collection_insert_value(ditto,collectionNameX,doc_cbor,strategy,null,writeTransaction!==null&&writeTransaction!==void 0?writeTransaction:null);if(errorCode!==0)throw new Error(errorMessage()||`ditto_collection_insert_value() failed with error code: ${errorCode}`);return boxCBytesIntoBuffer(id)}async function collectionRemove(ditto,collectionName,writeTransaction,documentID){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const{status_code:errorCode,bool_value:didRemove}=await ditto_collection_remove(ditto,collectionNameX,writeTransaction,documentID);if(errorCode!==0)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${errorCode}`);return didRemove}async function collectionEvict(ditto,collectionName,writeTransaction,documentID){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const{status_code:errorCode,bool_value:didEvict}=await ditto_collection_evict(ditto,collectionNameX,writeTransaction,documentID);if(errorCode!==0)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${errorCode}`);return didEvict}async function collectionUpdate(ditto,collectionName,writeTransaction,document){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const errorCode=await ditto_collection_update(ditto,collectionNameX,writeTransaction,document);if(errorCode!==0)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${errorCode}`)}async function collectionUpdateMultiple(ditto,collectionName,writeTransaction,documents){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const cDocuments=jsDocsToCDocs(documents);const errorCode=await ditto_collection_update_multiple(ditto,collectionNameX,writeTransaction,cDocuments);if(errorCode!==0)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${errorCode}`)}async function collectionExecQueryStr(ditto,collectionName,writeTransaction,query,queryArgsCBOR,orderBy,limit,offset){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const queryX=bytesFromString(query);return await ditto_collection_exec_query_str(ditto,collectionNameX,writeTransaction,queryX,queryArgsCBOR,orderBy,limit,offset)}async function collectionRemoveQueryStr(ditto,collectionName,writeTransaction,query,queryArgsCBOR,orderBy,limit,offset){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const queryX=bytesFromString(query);return await ditto_collection_remove_query_str(ditto,collectionNameX,writeTransaction,queryX,queryArgsCBOR,orderBy,limit,offset)}async function collectionEvictQueryStr(ditto,collectionName,writeTransaction,query,queryArgsCBOR,orderBy,limit,offset){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const queryX=bytesFromString(query);return await ditto_collection_evict_query_str(ditto,collectionNameX,writeTransaction,queryX,queryArgsCBOR,orderBy,limit,offset)}async function tryExperimentalExecQueryStr(ditto,writeTransaction,query,queryArgsCBOR){ensureInitialized();const queryBytesPointer=bytesFromString(query);const result=await dittoffi_try_experimental_exec_statement_str(ditto,writeTransaction,queryBytesPointer,queryArgsCBOR);throwOnErrorResult(result.error,"dittoffi_try_experimental_exec_statement_str");return result.success}function addSubscription(ditto,collectionName,query,queryArgsCBOR,orderBy,limit,offset){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const queryX=bytesFromString(query);return ditto_add_subscription(ditto,collectionNameX,queryX,queryArgsCBOR,orderBy,limit,offset)}function removeSubscription(ditto,collectionName,query,queryArgsCBOR,orderBy,limit,offset){ensureInitialized();const collectionNameX=bytesFromString(collectionName);const queryX=bytesFromString(query);return ditto_remove_subscription(ditto,collectionNameX,queryX,queryArgsCBOR,orderBy,limit,offset)}function tryExperimentalAddDQLSubscription(dittoPointer,query,queryArgsCBOR){ensureInitialized();const queryBuffer=bytesFromString(query);const result=dittoffi_try_experimental_add_dql_subscription(dittoPointer,queryBuffer,queryArgsCBOR);throwOnErrorResult(result.error,"dittoffi_try_experimental_add_dql_subscription");return}function tryExperimentalRemoveDQLSubscription(dittoPointer,query,queryArgsCBOR){ensureInitialized();const queryBuffer=bytesFromString(query);const result=dittoffi_try_experimental_remove_dql_subscription(dittoPointer,queryBuffer,queryArgsCBOR);throwOnErrorResult(result.error,"dittoffi_try_experimental_remove_dql_subscription");return}function dqlResponseFree(responsePointer){ensureInitialized();ditto_dql_response_free(responsePointer)}function dqlResultFree(resultPointer){ensureInitialized();ditto_dql_result_free(resultPointer)}function dqlResponseResults(responsePointer){ensureInitialized();const rv=[];const resultCount=ditto_dql_response_result_count(responsePointer);for(let i=0;i<resultCount;i++){rv.push(ditto_dql_response_result_at(responsePointer,i))}return rv}function dqlMutatedDocumentIDs(responsePointer){ensureInitialized();const rv=[];const resultCount=ditto_dql_response_affected_document_id_count(responsePointer);for(let i=0;i<resultCount;i++){const cborBytes=ditto_dql_response_affected_document_id_at(responsePointer,i);rv.push(boxCBytesIntoBuffer(cborBytes))}return rv}function dqlResultCBOR(resultPointer){ensureInitialized();const cborBytes=ditto_result_cbor(resultPointer);return boxCBytesIntoBuffer(cborBytes)}function dqlResultJSON(resultPointer){ensureInitialized();const jsonBytes=ditto_result_json(resultPointer);return boxCStringIntoString(jsonBytes)}function liveQueryRegister(ditto,collectionName,query,queryArgsCBOR,orderBy,limit,offset,eventHandler,onError){ensureInitialized();const collectionNameBuffer=bytesFromString(collectionName);const queryBuffer=bytesFromString(query);const{status_code:errorCode,i64:id}=ditto_live_query_register_str_detached(ditto,collectionNameBuffer,queryBuffer,queryArgsCBOR,orderBy,limit,offset,wrapBackgroundCbForFFI(onError,eventHandler));if(errorCode!==0)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${errorCode}`);return id}function tryExperimentalRegisterChangeObserver(ditto,query,queryArgsCBOR,changeHandler){ensureInitialized();const errorHandler=err=>log("Error",`The registered store observer callback failed with ${err}`);const wrappedCallback=wrapBackgroundCbForFFI(errorHandler,changeHandler);const queryBuffer=bytesFromString(query);const result=dittoffi_try_experimental_register_change_observer_str_detached(ditto,queryBuffer,queryArgsCBOR,wrappedCallback);throwOnErrorResult(result.error,"dittoffi_try_experimental_register_change_observer_str_detached");return result.success}async function liveQueryStart(ditto,liveQueryID){ensureInitialized();const errorCode=await ditto_live_query_start(ditto,liveQueryID);if(errorCode!==0)throw new Error(errorMessage()||`\`ditto_live_query_start()\` failed with error code: ${errorCode}`)}function liveQueryStop(ditto,liveQueryID){ensureInitialized();ditto_live_query_stop(ditto,liveQueryID)}async function liveQuerySignalAvailableNext(ditto,liveQueryID){ensureInitialized();await ditto_live_query_signal_available_next(ditto,liveQueryID)}async function liveQueryWebhookRegister(ditto,collectionName,query,orderBy,limit,offset,url){ensureInitialized();const collectionNameBuffer=bytesFromString(collectionName);const queryBuffer=bytesFromString(query);const urlBuffer=bytesFromString(url);const{status_code:errorCode,id:id}=await ditto_live_query_webhook_register_str(ditto,collectionNameBuffer,queryBuffer,orderBy,limit,offset,urlBuffer);if(errorCode!==0)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${errorCode}`);return boxCBytesIntoBuffer(id)}async function tryExperimentalWebhookRegisterDqlLiveQuery(ditto,query,queryArgsCBOR,url){ensureInitialized();const queryBuffer=bytesFromString(query);const urlBuffer=bytesFromString(url);const result=await dittoffi_try_experimental_webhook_register_dql_live_query_str(ditto,queryBuffer,queryArgsCBOR,urlBuffer);throwOnErrorResult(result.error,"dittoffi_try_experimental_webhook_register_dql_live_query_str");const documentIdCBOR=result.success;return boxCBytesIntoBuffer(documentIdCBOR)}async function readTransaction(ditto){ensureInitialized();const{status_code:errorCode,txn:readTransaction}=await ditto_read_transaction(ditto);if(errorCode!==0)throw new Error(errorMessage()||`\`ditto_read_transaction()\` failed with error code: ${errorCode}`);return readTransaction}function readTransactionFree(self){ensureInitialized();return ditto_read_transaction_free(self)}async function writeTransaction(ditto){ensureInitialized();const{status_code:errorCode,txn:writeTransaction}=await ditto_write_transaction(ditto,null);if(errorCode!==0)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${errorCode}`);return writeTransaction}async function writeTransactionCommit(ditto,self){ensureInitialized();const errorCode=await ditto_write_transaction_commit(ditto,self);if(errorCode!==0)throw new Error(errorMessage()||`ditto_write_transaction_commit() failed with error code: ${errorCode}`)}async function writeTransactionRollback(ditto,transaction){ensureInitialized();const errorCode=await ditto_write_transaction_rollback(ditto,transaction);if(errorCode!==0)throw new Error(errorMessage()||`ditto_write_transaction_rollback() failed with error code: ${errorCode}`)}function staticTCPClientFreeHandle(self){undefined(self)}function websocketClientFreeHandle(self){ensureInitialized();websocket_client_free_handle(self)}function loggerInit(){ensureInitialized();ditto_logger_init()}async function loggerSetCustomLogCb(cb){ensureInitialized();if(null===cb){await ditto_logger_set_custom_log_cb(null)}else{const wrappedCallback=wrapBackgroundCbForFFI(null,((loglevel,cMsg)=>{try{const msg=boxCStringIntoString(cMsg);cb(loglevel,msg)}catch(e){log("Error",`The registered cb in \`ditto_logger_set_custom_log_cb()\` failed with: ${e}`)}}));await ditto_logger_set_custom_log_cb(wrappedCallback)}}function loggerEnabled(enabled){ensureInitialized();ditto_logger_enabled(!!enabled)}function loggerEnabledGet(){ensureInitialized();return!!ditto_logger_enabled_get()}function loggerEmojiHeadingsEnabled(loggerEmojiHeadingsEnabled){ensureInitialized();ditto_logger_emoji_headings_enabled(loggerEmojiHeadingsEnabled)}function loggerEmojiHeadingsEnabledGet(){ensureInitialized();return ditto_logger_emoji_headings_enabled_get()}function loggerMinimumLogLevel(logLevel){ensureInitialized();ditto_logger_minimum_log_level(logLevel)}function loggerMinimumLogLevelGet(){ensureInitialized();return ditto_logger_minimum_log_level_get()}function loggerSetLogFile(path){ensureInitialized();const pathBytesOrNull=path?bytesFromString(path):null;const errorCode=ditto_logger_set_log_file(pathBytesOrNull);if(errorCode!==0){errorMessage();throw new Error(`Can't set log file, due to error: ${errorMessage}`)}}function log(level,message){ensureInitialized();const messageBuffer=bytesFromString(message);ditto_log(level,messageBuffer)}function dittoIdentityConfigMakeOnlinePlayground(appID,sharedToken,baseURL){ensureInitialized();const appIDX=bytesFromString(appID);const sharedTokenX=bytesFromString(sharedToken);const baseURLX=bytesFromString(baseURL);const{status_code:errorCode,identity_config:identityConfig}=ditto_identity_config_make_online_playground(appIDX,sharedTokenX,baseURLX);if(errorCode!==0)throw new Error(errorMessage()||`ditto_identity_config_make_online_playground() failed with error code: ${errorCode}`);return identityConfig}function dittoIdentityConfigMakeOnlineWithAuthentication(appID,baseURL){ensureInitialized();const appIDX=bytesFromString(appID);const baseURLX=bytesFromString(baseURL);const{status_code:errorCode,identity_config:identityConfig}=ditto_identity_config_make_online_with_authentication(appIDX,baseURLX);if(errorCode!==0)throw new Error(errorMessage()||`ditto_identity_config_make_online_with_authentication() failed with error code: ${errorCode}`);return identityConfig}function dittoIdentityConfigMakeOfflinePlayground(appId,siteID){ensureInitialized();const appIdX=bytesFromString(appId);const siteIDX=Number(siteID);const{status_code:errorCode,identity_config:identityConfig}=ditto_identity_config_make_offline_playground(appIdX,siteIDX);if(errorCode!==0)throw new Error(errorMessage()||`ditto_identity_config_make_offline_playground() failed with error code: ${errorCode}`);return identityConfig}function dittoIdentityConfigMakeSharedKey(appId,sharedKey,siteID){ensureInitialized();const appIdX=bytesFromString(appId);const sharedKeyX=bytesFromString(sharedKey);const siteIDX=Number(siteID);const{status_code:errorCode,identity_config:identityConfig}=ditto_identity_config_make_shared_key(appIdX,sharedKeyX,siteIDX);if(errorCode!==0)throw new Error(errorMessage()||`ditto_identity_config_make_shared_key() failed with error code: ${errorCode}`);return identityConfig}function dittoIdentityConfigMakeManual(configCBORBase64){ensureInitialized();const configCBORBase64X=bytesFromString(configCBORBase64);const{status_code:errorCode,identity_config:identityConfig}=ditto_identity_config_make_manual_v0(configCBORBase64X);if(errorCode!==0)throw new Error(errorMessage()||`ditto_identity_config_make_manual_v0() failed with error code: ${errorCode}`);return identityConfig}function dittoAuthClientGetSiteID(ditto){ensureInitialized();return ditto_auth_client_get_site_id(ditto)}function dittoAuthClientGetAppID(ditto){ensureInitialized();const cString=ditto_auth_client_get_app_id(ditto);return boxCStringIntoString(cString)}function dittoAuthClientUserID(ditto){ensureInitialized();const cStr=ditto_auth_client_user_id(ditto);return boxCStringIntoString(cStr)}function dittoAuthClientIsWebValid(ditto){ensureInitialized();return ditto_auth_client_is_web_valid(ditto)!==0}function dittoAuthClientIsX509Valid(ditto){ensureInitialized();return ditto_auth_client_is_x509_valid(ditto)!==0}async function dittoAuthClientLoginWithToken(ditto,token,provider){ensureInitialized();const tokenBytes=bytesFromString(token);const providerBytes=bytesFromString(provider);const errorCode=await ditto_auth_client_login_with_token(ditto,tokenBytes,providerBytes);if(errorCode!==0)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${errorCode}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(ditto,username,password,provider){ensureInitialized();const usernameBytes=bytesFromString(username);const passwordBytes=bytesFromString(password);const providerBytes=bytesFromString(provider);const errorCode=await ditto_auth_client_login_with_credentials(ditto,usernameBytes,passwordBytes,providerBytes);if(errorCode!==0)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${errorCode}).`)}async function dittoAuthClientLogout(ditto){ensureInitialized();const errorCode=await ditto_auth_client_logout(ditto);if(errorCode!==0)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${errorCode}).`)}function uninitializedDittoMake(path){ensureInitialized();const pathX=bytesFromString(path);return ditto_uninitialized_ditto_make(pathX)}function dittoMake(uninitializedDitto,identityConfig){ensureInitialized();return ditto_make(uninitializedDitto,identityConfig,"Disabled")}async function dittoGetCollectionNames(self){ensureInitialized();const result=await ditto_get_collection_names(self);const errorCode=result.status_code;const cStringVec=result.names;if(errorCode!==0)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${errorCode}`);const strings=cStringVecToStringArray(cStringVec);return strings}function dittoFree(self){ensureInitialized();return ditto_free(self)}async function dittoRegisterPresenceV1Callback(self,cb){ensureInitialized();ditto_register_presence_v1_callback(self,wrapBackgroundCbForFFI((err=>log("Error",`The registered presence callback v1 errored with ${err}`)),(cJsonStr=>{const jsonStr=refCStringToString(cJsonStr);cb(jsonStr)})))}async function dittoClearPresenceCallback(self){ensureInitialized();await ditto_clear_presence_callback(self)}async function dittoRegisterPresenceV3Callback(self,cb){ensureInitialized();ditto_register_presence_v3_callback(self,wrapBackgroundCbForFFI((err=>log("Error",`The registered presence callback v3 errored with ${err}`)),(cJsonStr=>{const jsonStr=refCStringToString(cJsonStr);cb(jsonStr)})))}async function dittoClearPresenceV3Callback(self){ensureInitialized();ditto_clear_presence_v3_callback(self)}function dittoSmallPeerInfoGetIsEnabled(dittoPointer){ensureInitialized();return ditto_small_peer_info_get_is_enabled(dittoPointer)}async function dittoSmallPeerInfoSetEnabled(dittoPointer,isEnabled){ensureInitialized();ditto_small_peer_info_set_enabled(dittoPointer,isEnabled)}async function dittoSmallPeerInfoGetSyncScope(dittoPointer){ensureInitialized();return ditto_small_peer_info_get_sync_scope(dittoPointer)}async function dittoSmallPeerInfoSetSyncScope(dittoPointer,syncScope){ensureInitialized();return ditto_small_peer_info_set_sync_scope(dittoPointer,syncScope)}function dittoSmallPeerInfoGetMetadata(dittoPointer){ensureInitialized();const cString=ditto_small_peer_info_get_metadata(dittoPointer);return boxCStringIntoString(cString)}function dittoSmallPeerInfoSetMetadata(dittoPointer,metadata){ensureInitialized();const metadataCString=bytesFromString(metadata);const statusCode=ditto_small_peer_info_set_metadata(dittoPointer,metadataCString);switch(statusCode){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()||`'${metadata}' is not a valid JSON object`}`);default:throw new Error(errorMessage()||`Internal inconsistency, ditto_small_peer_info_set_metadata() returned an unknown error code: ${statusCode}`)}}async function dittoSmallPeerInfoCollectionSetTransportConfigData(self,transportConfigData){ensureInitialized();ditto_small_peer_info_set_transport_config_data(self,transportConfigData)}function dittoRegisterTransportConditionChangedCallback(self,cb){ensureInitialized();if(!cb){ditto_register_transport_condition_changed_callback(self,null)}else{ditto_register_transport_condition_changed_callback(self,wrapBackgroundCbForFFI((err=>log("Error",`The registered "transport condition changed" callback errored with ${err}`)),cb))}}function dittoSetDeviceName(dittoPointer,deviceName){ensureInitialized();let deviceNameCString=bytesFromString(deviceName);{if(deviceNameCString.length>64){const sanitizedDeviceName=deviceName.replace(/[^ -~]+/g,"");deviceNameCString=bytesFromString(sanitizedDeviceName.substr(0,63))}}return ditto_set_device_name(dittoPointer,deviceNameCString)}function dittoSetConnectRetryInterval(dittoPointer,retryInterval){ensureInitialized();const UINT32_MAX=4294967295;const clampedInterval=Math.min(Math.max(0,retryInterval),UINT32_MAX);return ditto_set_connect_retry_interval(dittoPointer,clampedInterval)}function dittoSetSyncGroup(dittoPointer,syncGroup){ensureInitialized();return ditto_set_sync_group(dittoPointer,syncGroup)}async function dittoNewAttachmentFromBytes(ditto,bytes){ensureInitialized();const outAttachment={};const errorCode=await ditto_new_attachment_from_bytes(ditto,bytes,outAttachment);if(errorCode!==0){throw new Error(errorMessage()||`ditto_new_attachment_from_bytes() failed with error code: ${errorCode}`)}return outAttachment}async function dittoResolveAttachment(ditto,id,namedCallbacks,onError){ensureInitialized();const{onComplete:onComplete,onProgress:onProgress,onDelete:onDelete}=namedCallbacks;const{status_code:errorCode,cancel_token:cancelToken}=await ditto_resolve_attachment(ditto,id,wrapBackgroundCbForFFI(onError,onComplete),wrapBackgroundCbForFFI(onError,onProgress),wrapBackgroundCbForFFI(onError,onDelete));if(errorCode!==0){throw new Error(errorMessage()||`ditto_resolve_attachment() failed with error code: ${errorCode}`)}return cancelToken}function dittoCancelResolveAttachment(dittoPointer,id,cancelToken){ensureInitialized();const errorCode=ditto_cancel_resolve_attachment(dittoPointer,id,cancelToken);if(errorCode!==0)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${errorCode}`)}function freeAttachmentHandle(attachmentHandlePointer){ensureInitialized();ditto_free_attachment_handle(attachmentHandlePointer)}async function dittoGetCompleteAttachmentData(dittoPointer,attachmentHandlePointer){ensureInitialized();const{status:errorCode,data:data}=await ditto_get_complete_attachment_data(dittoPointer,attachmentHandlePointer);if(errorCode!==0)throw new Error(errorMessage()||`\`ditto_get_complete_attachment_data()\` failed with error code: ${errorCode}`);return boxCBytesIntoBuffer(data)}function dittoGetSDKVersion(ditto){ensureInitialized();const cString=ditto_get_sdk_version();return boxCStringIntoString(cString)}function dittoGetSDKSemver(){ensureInitialized();const cString=dittoffi_get_sdk_semver();return boxCStringIntoString(cString)}function dittoPresenceV1(self){ensureInitialized();const cString=ditto_presence_v1(self);return boxCStringIntoString(cString)}function dittoPresenceV3(self){ensureInitialized();const cString=ditto_presence_v3(self);return boxCStringIntoString(cString)}function dittoStartTCPServer(dittoPointer,bind){ensureInitialized();const bindBuffer=bytesFromString(bind);return undefined(dittoPointer,bindBuffer)}function dittoStopTCPServer(dittoPointer){ensureInitialized();return undefined(dittoPointer)}async function dittoShutdown(dittoPointer){ensureInitialized();return await ditto_shutdown(dittoPointer)}function dittoStartHTTPServer(dittoPointer,bind,staticPath,websocketMode,tlsCertPath,tlsKeyPath){ensureInitialized();const bindBuffer=bytesFromString(bind);const staticPathBuffer=bytesFromString(staticPath);const tlsCertPathBuffer=bytesFromString(tlsCertPath);const tlsKeyPathBuffer=bytesFromString(tlsKeyPath);return undefined(dittoPointer,bindBuffer,staticPathBuffer,websocketMode,tlsCertPathBuffer,tlsKeyPathBuffer)}function dittoStopHTTPServer(dittoPointer){ensureInitialized();return undefined(dittoPointer)}function dittoRunGarbageCollection(dittoPointer){ensureInitialized();return ditto_run_garbage_collection(dittoPointer)}async function dittoDisableSyncWithV3(dittoPointer){ensureInitialized();const errorCode=await ditto_disable_sync_with_v3(dittoPointer);if(errorCode!==0)throw new Error(errorMessage()||`ditto_disable_sync_with_v3() failed with error code: ${errorCode}`)}function dittoSetStaticTCPClients(ditto,listOfServers){ensureInitialized();{if(listOfServers.length>0){throw new Error(`Web variant of Ditto does not support connecting to TCP servers: ${listOfServers.join(", ")}`)}}}function dittoSetStaticWebsocketClients(ditto,listOfServers,routingHint){ensureInitialized();const listOfServersBytes=listOfServers.map((server=>bytesFromString(server)));ditto_set_static_websocket_clients(ditto,listOfServersBytes,routingHint)}function documentsHash(documents){ensureInitialized();const{status_code:errorCode,u64:hash}=ditto_documents_hash(documents);if(errorCode!==0)throw new Error(errorMessage()||`\`ditto_documents_hash()\` failed with error code: ${errorCode}`);return BigInt(hash)}function documentsHashMnemonic(documents){ensureInitialized();const{status_code:errorCode,c_string:c_string}=ditto_documents_hash_mnemonic(documents);if(errorCode!==0)throw new Error(errorMessage()||`\`ditto_documents_hash_mnemonic()\` failed with error code: ${errorCode}`);return boxCStringIntoString(c_string)}async function dittoAuthSetLoginProvider(ditto,loginProvider){ensureInitialized();return await ditto_auth_set_login_provider(ditto,loginProvider)}function dittoAuthClientMakeLoginProvider(expiringCb,onError){ensureInitialized();return ditto_auth_client_make_login_provider(wrapBackgroundCbForFFI(onError,expiringCb))}function dittoAuthClientSetValidityListener(ditto,validityUpdateCb,onError){ensureInitialized();const validityUpdateRawCb=wrapBackgroundCbForFFI(onError,(function(isWebValidInt,isX509ValidInt){return validityUpdateCb(isWebValidInt===1,isX509ValidInt===1)}));return ditto_auth_client_set_validity_listener(ditto,validityUpdateRawCb)}function transportsInit(){ensureInitialized();const transportsErrorPointer=ditto_sdk_transports_error_new();const wasInitialized=ditto_sdk_transports_init(transportsErrorPointer);const errorType=ditto_sdk_transports_error_value(transportsErrorPointer);ditto_sdk_transports_error_free(transportsErrorPointer);if(wasInitialized===false){throw new Error(`Failed to initialize transports (${errorType} error)`)}}function transportsBLEIsAvailable(ditto){ensureInitialized();return ditto_sdk_transports_ble_is_available(ditto)}function transportsLANIsAvailable(ditto){ensureInitialized();return ditto_sdk_transports_lan_is_available(ditto)}function transportsAWDLIsAvailable(ditto){ensureInitialized();return ditto_sdk_transports_awdl_is_available(ditto)}let isInitialized$1=false;let withOutPtr;async function init$1(webAssemblyModule){{if(webAssemblyModule){await init$2(webAssemblyModule)}else{await init$2()}isInitialized$1=true;withOutPtr=wrapFFIOutFunction(withOutPtr$1)}}function initSDKVersion(platform,language,semVer){ensureInitialized();bytesFromString(platform);bytesFromString(language);const semVerCString=bytesFromString(semVer);const errorCode=ditto_init_sdk_version(platform,language,semVerCString);if(typeof errorCode!=="undefined"&&errorCode!==0)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${errorCode}`)}function verifyLicense(license){ensureInitialized();const licenseBuffer=bytesFromString(license);let result;const errorMessageCString=withOutPtr("char *",(outErrorMessage=>{result=ditto_verify_license(licenseBuffer,outErrorMessage);return outErrorMessage}));const errorMessage=boxCStringIntoString(errorMessageCString);return{result:result,errorMessage:errorMessage}}const NOT_FOUND_ERROR_CODE=-30798;function wrapBackgroundCbForFFI(onError,cb){if(onError===undefined){onError=err=>log("Error",`The registered callback failed with ${err}`)}return(ret_sender,...args)=>{let ret;try{ret=cb(...args)}catch(err){try{onError(err)}catch(nested_error){log("Error",`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${nested_error}`)}}return ret_sender(ret)}}function wrapFFIOutFunction(ffiOutFunction){return function(...args){let occurredError=undefined;let callbackResult=undefined;let isCallbackResultOutParameter=false;const callback=args[args.length-1];const previous_args=args.splice(0,args.length-1);const dittoCoreResult=ffiOutFunction(...previous_args,(outParameter=>{try{callbackResult=callback(outParameter);isCallbackResultOutParameter=callbackResult===outParameter}catch(error){occurredError=error}}));if(occurredError){throw occurredError}return isCallbackResultOutParameter?dittoCoreResult:callbackResult}}function bytesFromString(jsString){if(typeof jsString==="undefined")return undefined;if(jsString===null)return null;if(typeof jsString!=="string")throw new Error(`Can't convert string to Uint8Array, not a string: ${jsString}`);const textEncoder=new TextEncoder;return textEncoder.encode(`${jsString}\0`)}function errorMessage(){ensureInitialized();const errorMessageCString=ditto_error_message();return boxCStringIntoString(errorMessageCString)}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.")}}class AttachmentToken{constructor(jsObj){const type=jsObj[DittoCRDTTypeKey];if(type!==DittoCRDTType.attachment){throw new Error("Invalid attachment token")}const id=jsObj["_id"];if(!(id instanceof Uint8Array)){throw new Error("Invalid attachment token id")}const len=jsObj["_len"];if(typeof len!=="number"||len<0){throw new Error("Invalid attachment token length")}const meta=jsObj["_meta"];if(typeof meta!=="object"){throw new Error("Invalid attachment token meta")}this.id=id;this.len=len;this.metadata=meta}}const fullBuildVersionString="4.5.3";const defaultDittoWasmFileURL="https://software.ditto.live/js/Ditto/4.5.3/ditto.wasm";let isInitialized=false;async function init(options={}){if(!isInitialized){{const webAssemblyModule=options.webAssemblyModule||defaultDittoWasmFileURL;await init$1(webAssemblyModule);initSDKVersion("Web","JavaScript",fullBuildVersionString);loggerInit()}isInitialized=true}}class Logger{static get logFile(){return this._logFile}static setLogFile(path){if(path){loggerSetLogFile(path);this._logFile=path}else{loggerSetLogFile(undefined);delete this._logFile}}static setLogFileURL(url){var _a;this.setLogFile((_a=url===null||url===void 0?void 0:url.pathname)!==null&&_a!==void 0?_a:null)}static get enabled(){return loggerEnabledGet()}static set enabled(enabled){loggerEnabled(enabled)}static get emojiLogLevelHeadingsEnabled(){return loggerEmojiHeadingsEnabledGet()}static set emojiLogLevelHeadingsEnabled(emojiLogLevelHeadingsEnabled){loggerEmojiHeadingsEnabled(emojiLogLevelHeadingsEnabled)}static get minimumLogLevel(){return loggerMinimumLogLevelGet()}static set minimumLogLevel(minimumLogLevel){loggerMinimumLogLevel(minimumLogLevel)}static get customLogCallback(){return this._customLogCallback}static async setCustomLogCallback(callback){if(callback){await loggerSetCustomLogCb(callback);this._customLogCallback=callback}else{await loggerSetCustomLogCb(null);delete this._customLogCallback}}static log(level,message){log(level,message)}static error(message){this.log("Error",message)}static warning(message){this.log("Warning",message)}static info(message){this.log("Info",message)}static debug(message){this.log("Debug",message)}static verbose(message){this.log("Verbose",message)}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"});const EMPTY_KEY=Symbol("EMPTY_KEY");const OMIT_VALUE=Symbol("OMIT_VALUE");const POW_2_24=5.960464477539063e-8;const POW_2_32=4294967296;const POW_2_53=9007199254740992;const MAX_SAFE_INTEGER=18446744073709551616n;const DECODE_CHUNK_SIZE=8192;const kCborTag=6;const kCborTagUint8=64;const kCborTagUint16=69;const kCborTagUint32=70;const kCborTagInt8=72;const kCborTagInt16=77;const kCborTagInt32=78;const kCborTagFloat32=85;const kCborTagFloat64=86;function objectIs(x,y){if(typeof Object.is==="function")return Object.is(x,y);if(x===y){return x!==0||1/x===1/y}return x!==x&&y!==y}function options(options){function isDictionary(value){return typeof value==="string"&&["object","map"].includes(value)}function isMode(value){return typeof value==="string"&&["loose","strict","sequence"].includes(value)}const bag={...CBOR_OPTIONS};if(typeof options==="object"){bag.dictionary=isDictionary(options.dictionary)?options.dictionary:CBOR_OPTIONS.dictionary;bag.mode=isMode(options.mode)?options.mode:CBOR_OPTIONS.mode}return Object.freeze(bag)}function lexicographicalCompare(left,right){const minLength=Math.min(left.byteLength,right.byteLength);for(let i=0;i<minLength;i++){const result=left[i]-right[i];if(result!==0)return result}return left.byteLength-right.byteLength}var __classPrivateFieldGet=undefined&&undefined.__classPrivateFieldGet||function(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)};var _Sequence_instances,_Sequence_toInspectString;class Sequence{static from(iterable){return new Sequence(Array.from(iterable))}constructor(data){_Sequence_instances.add(this);Object.defineProperty(this,"_data",{enumerable:true,configurable:true,writable:true,value:void 0});if(data)this._data=data;else this._data=[]}add(item){return this._data.push(item)-1}remove(index){return this._data.splice(index,1)[0]}get(index){return this._data[index]}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(inspect){return`${this[Symbol.toStringTag]()}(${this.size}) ${inspect(this._data)}`},Symbol.for("Deno.customInspect"))](inspect){return __classPrivateFieldGet(this,_Sequence_instances,"m",_Sequence_toInspectString).call(this,inspect)}[Symbol.for("nodejs.util.inspect.custom")](_depth,_opts,inspect){return __classPrivateFieldGet(this,_Sequence_instances,"m",_Sequence_toInspectString).call(this,inspect)}}class SimpleValue{static create(value){if(value===undefined)return new SimpleValue(23);if(value===null)return new SimpleValue(22);if(value===true)return new SimpleValue(21);if(value===false)return new SimpleValue(20);if(typeof value==="number"&&value>=0&&value<=255){return new SimpleValue(value)}throw new Error("CBORError: Value out of range or not a simple value.")}constructor(value){Object.defineProperty(this,"semantic",{enumerable:true,configurable:true,writable:true,value:void 0});Object.defineProperty(this,"value",{enumerable:true,configurable:true,writable:true,value:void 0});switch(true){case value===20:this.semantic="false";break;case value===21:this.semantic="true";break;case value===22:this.semantic="null";break;case value===23:this.semantic="undefined";break;case value>23&&value<32:this.semantic="reserved";break;default:this.semantic="unassigned";break}this.value=value}toPrimitive(){switch(this.semantic){case"false":return false;case"true":return true;case"null":return null;case"undefined":default:return undefined}}}class TaggedValue{constructor(value,tag){Object.defineProperty(this,"value",{enumerable:true,configurable:true,writable:true,value:void 0});Object.defineProperty(this,"tag",{enumerable:true,configurable:true,writable:true,value:void 0});this.value=value;this.tag=tag}}function decode(data,reviver,cborOptions={}){const{dictionary:dictionary,mode:mode}=options(cborOptions);const isStrict=mode==="sequence"||mode==="strict";const dataView=new DataView(data);const ta=new Uint8Array(data);let offset=0;let reviverFunction=function(_key,value){return value};if(typeof reviver==="function")reviverFunction=reviver;function commitRead(length,value){offset+=length;return value}function readArrayBuffer(length){return commitRead(length,new Uint8Array(data,offset,length))}function readFloat16(){const tempArrayBuffer=new ArrayBuffer(4);const tempDataView=new DataView(tempArrayBuffer);const value=readUint16();const sign=value&32768;let exponent=value&31744;const fraction=value&1023;if(exponent===31744)exponent=255<<10;else if(exponent!==0)exponent+=127-15<<10;else if(fraction!==0)return(sign?-1:1)*fraction*POW_2_24;tempDataView.setUint32(0,sign<<16|exponent<<13|fraction<<13);return tempDataView.getFloat32(0)}function readFloat32(){return commitRead(4,dataView.getFloat32(offset))}function readFloat64(){return commitRead(8,dataView.getFloat64(offset))}function readUint8(){return commitRead(1,ta[offset])}function readUint16(){return commitRead(2,dataView.getUint16(offset))}function readUint32(){return commitRead(4,dataView.getUint32(offset))}function readUint64(){return commitRead(8,dataView.getBigUint64(offset))}function readBreak(){if(ta[offset]!==255)return false;offset+=1;return true}function readLength(additionalInformation){if(additionalInformation<24)return additionalInformation;if(additionalInformation===24)return readUint8();if(additionalInformation===25)return readUint16();if(additionalInformation===26)return readUint32();if(additionalInformation===27){const integer=readUint64();if(integer<POW_2_53)return Number(integer);return integer}if(additionalInformation===31)return-1;throw new Error("CBORError: Invalid length encoding")}function readIndefiniteStringLength(majorType){const initialByte=readUint8();if(initialByte===255)return-1;const length=readLength(initialByte&31);if(length<0||initialByte>>5!==majorType){throw new Error("CBORError: Invalid indefinite length element")}return Number(length)}function appendUtf16Data(utf16data,length){for(let i=0;i<length;++i){let value=readUint8();if(value&128){if(value<224){value=(value&31)<<6|readUint8()&63;length-=1}else if(value<240){value=(value&15)<<12|(readUint8()&63)<<6|readUint8()&63;length-=2}else{value=(value&15)<<18|(readUint8()&63)<<12|(readUint8()&63)<<6|readUint8()&63;length-=3}}if(value<65536){utf16data.push(value)}else{value-=65536;utf16data.push(55296|value>>10);utf16data.push(56320|value&1023)}}}function decodeItem(){const initialByte=readUint8();const majorType=initialByte>>5;const additionalInformation=initialByte&31;let i;let length;if(majorType===7){switch(additionalInformation){case 25:return readFloat16();case 26:return readFloat32();case 27:return readFloat64()}}length=readLength(additionalInformation);if(length<0&&(majorType<2||6<majorType)){throw new Error("CBORError: Invalid length")}switch(majorType){case 0:return reviverFunction(EMPTY_KEY,length);case 1:if(typeof length==="number"){return reviverFunction(EMPTY_KEY,-1-length)}return reviverFunction(EMPTY_KEY,-1n-length);case 2:{if(length<0){const elements=[];let fullArrayLength=0;while((length=readIndefiniteStringLength(majorType))>=0){fullArrayLength+=length;elements.push(readArrayBuffer(length))}const fullArray=new Uint8Array(fullArrayLength);let fullArrayOffset=0;for(i=0;i<elements.length;++i){fullArray.set(elements[i],fullArrayOffset);fullArrayOffset+=elements[i].length}return reviverFunction(EMPTY_KEY,fullArray)}return reviverFunction(EMPTY_KEY,readArrayBuffer(length))}case 3:{const utf16data=[];if(length<0){while((length=readIndefiniteStringLength(majorType))>=0){appendUtf16Data(utf16data,length)}}else{appendUtf16Data(utf16data,length)}let string="";for(i=0;i<utf16data.length;i+=DECODE_CHUNK_SIZE){string+=String.fromCharCode.apply(null,utf16data.slice(i,i+DECODE_CHUNK_SIZE))}return reviverFunction(EMPTY_KEY,string)}case 4:{let retArray;if(length<0){retArray=[];let index=0;while(!readBreak()){retArray.push(reviverFunction(index++,decodeItem()))}}else{retArray=new Array(length);for(i=0;i<length;++i){retArray[i]=reviverFunction(i,decodeItem())}}return reviverFunction(EMPTY_KEY,retArray)}case 5:{if(dictionary==="map"){const retMap=new Map;for(i=0;i<length||length<0&&!readBreak();++i){const key=decodeItem();if(isStrict&&retMap.has(key)){throw new Error("CBORError: Duplicate key encountered")}retMap.set(key,reviverFunction(key,decodeItem()))}return reviverFunction(EMPTY_KEY,retMap)}const retObject={};for(i=0;i<length||length<0&&!readBreak();++i){const key=decodeItem();if(isStrict&&Object.prototype.hasOwnProperty.call(retObject,key)){throw new Error("CBORError: Duplicate key encountered")}retObject[key]=reviverFunction(key,decodeItem())}return reviverFunction(EMPTY_KEY,retObject)}case 6:{const value=decodeItem();const tag=length;if(value instanceof Uint8Array){const buffer=value.buffer.slice(value.byteOffset,value.byteLength+value.byteOffset);switch(tag){case kCborTagUint8:return reviverFunction(EMPTY_KEY,new Uint8Array(buffer));case kCborTagInt8:return reviverFunction(EMPTY_KEY,new Int8Array(buffer));case kCborTagUint16:return reviverFunction(EMPTY_KEY,new Uint16Array(buffer));case kCborTagInt16:return reviverFunction(EMPTY_KEY,new Int16Array(buffer));case kCborTagUint32:return reviverFunction(EMPTY_KEY,new Uint32Array(buffer));case kCborTagInt32:return reviverFunction(EMPTY_KEY,new Int32Array(buffer));case kCborTagFloat32:return reviverFunction(EMPTY_KEY,new Float32Array(buffer));case kCborTagFloat64:return reviverFunction(EMPTY_KEY,new Float64Array(buffer))}}return reviverFunction(EMPTY_KEY,new TaggedValue(value,tag))}case 7:switch(length){case 20:return reviverFunction(EMPTY_KEY,false);case 21:return reviverFunction(EMPTY_KEY,true);case 22:return reviverFunction(EMPTY_KEY,null);case 23:return reviverFunction(EMPTY_KEY,undefined);default:return reviverFunction(EMPTY_KEY,new SimpleValue(length))}}}const ret=decodeItem();if(offset!==data.byteLength){if(mode!=="sequence")throw new Error("CBORError: Remaining bytes");const seq=new Sequence([ret]);while(offset<data.byteLength){seq.add(reviverFunction(EMPTY_KEY,decodeItem()))}return seq}return mode==="sequence"?new Sequence([ret]):ret}function parse(data,reviver,cborOptions){return decode(data,reviver,cborOptions)}function encode(value,replacer){let data=new ArrayBuffer(256);let dataView=new DataView(data);let byteView=new Uint8Array(data);let lastLength;let offset=0;let replacerFunction=(_key,value)=>value;if(typeof replacer==="function")replacerFunction=replacer;if(Array.isArray(replacer)){const exclusive=replacer.slice();replacerFunction=(key,value)=>{if(key===EMPTY_KEY||exclusive.includes(key))return value;return OMIT_VALUE}}function prepareWrite(length){let newByteLength=data.byteLength;const requiredLength=offset+length;while(newByteLength<requiredLength)newByteLength<<=1;if(newByteLength!==data.byteLength){const oldDataView=dataView;data=new ArrayBuffer(newByteLength);dataView=new DataView(data);byteView=new Uint8Array(data);const uint32count=offset+3>>2;for(let i=0;i<uint32count;++i){dataView.setUint32(i<<2,oldDataView.getUint32(i<<2))}}lastLength=length;return dataView}function commitWrite(..._args){offset+=lastLength}function writeFloat64(val){commitWrite(prepareWrite(8).setFloat64(offset,val))}function writeUint8(val){commitWrite(prepareWrite(1).setUint8(offset,val))}function writeUint8Array(val){prepareWrite(val.length);byteView.set(val,offset);commitWrite()}function writeUint16(val){commitWrite(prepareWrite(2).setUint16(offset,val))}function writeUint32(val){commitWrite(prepareWrite(4).setUint32(offset,val))}function writeUint64(val){const low=val%POW_2_32;const high=(val-low)/POW_2_32;const view=prepareWrite(8);view.setUint32(offset,high);view.setUint32(offset+4,low);commitWrite()}function writeBigUint64(val){commitWrite(prepareWrite(8).setBigUint64(offset,val))}function writeVarUint(val,mod){if(val<=255){if(val<24){writeUint8(Number(val)|mod)}else{writeUint8(24|mod);writeUint8(Number(val))}}else if(val<=65535){writeUint8(25|mod);writeUint16(Number(val))}else if(val<=4294967295){writeUint8(26|mod);writeUint32(Number(val))}else{writeUint8(27|mod);if(typeof val==="number")writeUint64(val);else writeBigUint64(val)}}function writeTypeAndLength(type,length){if(length<24){writeUint8(type<<5|length)}else if(length<256){writeUint8(type<<5|24);writeUint8(length)}else if(length<65536){writeUint8(type<<5|25);writeUint16(length)}else if(length<4294967296){writeUint8(type<<5|26);writeUint32(length)}else{writeUint8(type<<5|27);writeUint64(length)}}function writeArray(val){const startOffset=offset;const length=val.length;let total=0;writeTypeAndLength(4,length);const typeLengthOffset=offset;for(let i=0;i<length;i+=1){const result=replacerFunction(i,val[i]);if(result===OMIT_VALUE)continue;encodeItem(result);total+=1}if(length>total){const encoded=byteView.slice(typeLengthOffset,offset);offset=startOffset;writeTypeAndLength(4,total);writeUint8Array(encoded)}}function writeDictionary(val){const encodedMap=[];const startOffset=offset;let typeLengthOffset=offset;let keyCount=0;let keyTotal=0;if(val instanceof Map){keyCount=val.size;writeTypeAndLength(5,keyCount);typeLengthOffset=offset;for(const[key,value]of val.entries()){const result=replacerFunction(key,value);if(result===OMIT_VALUE)continue;let cursor=offset;encodeItem(key);const keyBytes=byteView.slice(cursor,offset);cursor=offset;encodeItem(result);const valueBytes=byteView.slice(cursor,offset);keyTotal+=1;encodedMap.push([keyBytes,valueBytes])}}else{const keys=Object.keys(val);keyCount=keys.length;writeTypeAndLength(5,keyCount);typeLengthOffset=offset;for(let i=0;i<keyCount;i+=1){const key=keys[i];const result=replacerFunction(key,val[key]);if(result===OMIT_VALUE)continue;let cursor=offset;encodeItem(key);const keyBytes=byteView.slice(cursor,offset);cursor=offset;encodeItem(result);const valueBytes=byteView.slice(cursor,offset);keyTotal+=1;encodedMap.push([keyBytes,valueBytes])}}function sortEncodedKeys(length){offset=startOffset;writeTypeAndLength(5,keyTotal);encodedMap.sort((([keyA],[keyB])=>lexicographicalCompare(keyA,keyB)));for(let i=0;i<length;i+=1){const[encodedKey,encodedValue]=encodedMap[i];writeUint8Array(encodedKey);writeUint8Array(encodedValue)}}if(keyCount>keyTotal){const encodedMapLength=encodedMap.length;if(encodedMapLength>1){sortEncodedKeys(encodedMapLength)}else{const encoded=byteView.slice(typeLengthOffset,offset);offset=startOffset;writeTypeAndLength(5,keyTotal);writeUint8Array(encoded)}}else{const encodedMapLength=encodedMap.length;if(encodedMapLength>1){sortEncodedKeys(encodedMapLength)}}}function writeBigInteger(val){let type=0;if(0<=val&&val<=MAX_SAFE_INTEGER){type=0}else if(-MAX_SAFE_INTEGER<=val&&val<0){type=1;val=-(val+1n)}else{throw new Error("CBORError: Encountered unsafe integer outside of valid CBOR range.")}if(val<0x100000000n){return writeTypeAndLength(type,Number(val))}else{writeUint8(type<<5|27);writeBigUint64(val)}}function encodeItem(val){if(val===OMIT_VALUE)return;if(val===false)return writeUint8(244);if(val===true)return writeUint8(245);if(val===null)return writeUint8(246);if(val===undefined)return writeUint8(247);if(objectIs(val,-0))return writeUint8Array([249,128,0]);switch(typeof val){case"bigint":return writeBigInteger(val);case"number":if(Math.floor(val)===val){if(0<=val&&val<=POW_2_53)return writeTypeAndLength(0,val);if(-POW_2_53<=val&&val<0){return writeTypeAndLength(1,-(val+1))}}writeUint8(251);return writeFloat64(val);case"string":{const utf8data=[];const strLength=val.length;for(let i=0;i<strLength;++i){let charCode=val.charCodeAt(i);if(charCode<128){utf8data.push(charCode)}else if(charCode<2048){utf8data.push(192|charCode>>6);utf8data.push(128|charCode&63)}else if(charCode<55296||charCode>=57344){utf8data.push(224|charCode>>12);utf8data.push(128|charCode>>6&63);utf8data.push(128|charCode&63)}else{charCode=(charCode&1023)<<10;charCode|=val.charCodeAt(++i)&1023;charCode+=65536;utf8data.push(240|charCode>>18);utf8data.push(128|charCode>>12&63);utf8data.push(128|charCode>>6&63);utf8data.push(128|charCode&63)}}writeTypeAndLength(3,utf8data.length);return writeUint8Array(utf8data)}default:{let converted;if(Array.isArray(val)){writeArray(val)}else if(val instanceof Uint8Array){writeVarUint(kCborTagUint8,kCborTag<<5);writeTypeAndLength(2,val.length);writeUint8Array(val)}else if(val instanceof Int8Array){writeVarUint(kCborTagInt8,kCborTag<<5);writeTypeAndLength(2,val.byteLength);writeUint8Array(new Uint8Array(val.buffer))}else if(val instanceof Uint16Array){writeVarUint(kCborTagUint16,kCborTag<<5);writeTypeAndLength(2,val.byteLength);writeUint8Array(new Uint8Array(val.buffer))}else if(val instanceof Int16Array){writeVarUint(kCborTagInt16,kCborTag<<5);writeTypeAndLength(2,val.byteLength);writeUint8Array(new Uint8Array(val.buffer))}else if(val instanceof Uint32Array){writeVarUint(kCborTagUint32,kCborTag<<5);writeTypeAndLength(2,val.byteLength);writeUint8Array(new Uint8Array(val.buffer))}else if(val instanceof Int32Array){writeVarUint(kCborTagInt32,kCborTag<<5);writeTypeAndLength(2,val.byteLength);writeUint8Array(new Uint8Array(val.buffer))}else if(val instanceof Float32Array){writeVarUint(kCborTagFloat32,kCborTag<<5);writeTypeAndLength(2,val.byteLength);writeUint8Array(new Uint8Array(val.buffer))}else if(val instanceof Float64Array){writeVarUint(kCborTagFloat64,kCborTag<<5);writeTypeAndLength(2,val.byteLength);writeUint8Array(new Uint8Array(val.buffer))}else if(ArrayBuffer.isView(val)){converted=new Uint8Array(val.buffer);writeTypeAndLength(2,converted.length);writeUint8Array(converted)}else if(val instanceof ArrayBuffer||typeof SharedArrayBuffer==="function"&&val instanceof SharedArrayBuffer){converted=new Uint8Array(val);writeTypeAndLength(2,converted.length);writeUint8Array(converted)}else if(val instanceof TaggedValue){writeVarUint(val.tag,192);encodeItem(val.value)}else if(val instanceof SimpleValue){writeTypeAndLength(7,val.value)}else if(val instanceof Sequence){if(offset!==0){throw new Error("CBORError: A CBOR Sequence may not be nested.")}const length=val.size;for(let i=0;i<length;i+=1)encodeItem(val.get(i))}else{writeDictionary(val)}}}}encodeItem(replacerFunction(EMPTY_KEY,value));if("slice"in data)return data.slice(0,offset);const ret=new ArrayBuffer(offset);const retView=new DataView(ret);for(let i=0;i<offset;++i)retView.setUint8(i,dataView.getUint8(i));return ret}function binarify(value,replacer){return encode(value,replacer)}const CBOR$1={binarify:binarify,decode:decode,encode:encode,parse:parse};class CBOR{static encode(data,replacer){const arrayBuffer=CBOR$1.encode(data,replacer);return new Uint8Array(arrayBuffer)}static decode(data,reviver){const arrayBuffer=data.buffer;return CBOR$1.decode(arrayBuffer,reviver)}}function documentIDReplacer(key,value){if(value instanceof DocumentID){return value.toString()}return value}class DocumentID{get value(){let value=this["@ditto.value"];if(typeof value==="undefined"){value=CBOR.decode(this["@ditto.cbor"]);this["@ditto.value"]=value}return value}constructor(value,skipCBOREncoding=false,skipValidation=false){const cbor=skipCBOREncoding?value:CBOR.encode(value);const validatedCBOR=skipValidation?cbor:validateDocumentIDCBOR(cbor);if(!validatedCBOR){throw new Error(`Can't create DocumentID, passed in value is not valid: ${value}`)}this.isValidated=!skipValidation;this["@ditto.cbor"]=validatedCBOR}equals(documentID){const left=this["@ditto.cbor"];const right=documentID["@ditto.cbor"];if(left===right){return true}if(!(left instanceof Uint8Array)){return false}if(!(right instanceof Uint8Array)){return false}if(left.length!==right.length){return false}for(let i=0;i<left.length;i+=1){if(left[i]!==right[i])return false}return true}toString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithoutQuotes")}toBase64String(){const bytes=this["@ditto.cbor"];return btoa(String.fromCharCode.apply(null,bytes))}toQueryCompatibleString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithQuotes")}toCBOR(){return this["@ditto.cbor"]}}function validateDocumentIDValue(id){if(typeof id==="undefined"){throw new Error(`Invalid document ID: ${id}`)}return id}function validateDocumentIDCBOR(idCBOR){const validatedIDCBOROrNull=validateDocumentID(idCBOR);return validatedIDCBOROrNull!==null&&validatedIDCBOROrNull!==void 0?validatedIDCBOROrNull:idCBOR}const DEBUG_TYPE_NAMES=[];const DEBUG_ALL_TYPES=false;class Handle{constructor(bridge,object,pointer){this.isClosed=false;this.isFinalized=false;this.isUnregistered=false;this.bridge=bridge;this.objectWeakRef=new WeakRef(object);this.pointer=pointer}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 _b;if(this.isClosed){return null}if(this.isFinalized){return null}if(this.isUnregistered){return null}return(_b=this.pointer)!==null&&_b!==void 0?_b:null}object(){const object=this.objectWeakRef.deref();if(object==null){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 object}objectOrNull(){var _b;return(_b=this.objectWeakRef.deref())!==null&&_b!==void 0?_b:null}toString(){const pointer=this.derefOrNull();return`{ Handle | type: ${this.bridge.type}, object: ${this.objectWeakRef.deref()}, FFI address: ${pointer===null||pointer===void 0?void 0:pointer.addr}, FFI type: ${pointer===null||pointer===void 0?void 0:pointer.type} }`}bridgeWillClose(){this.isClosed=true}bridgeDidClose(){this.pointer=null}bridgeWillFinalize(){this.isFinalized=true}bridgeDidFinalize(){this.pointer=null}bridgeWillUnregister(){this.isUnregistered=true}bridgeDidUnregister(){this.pointer=null}}class Handles{constructor(bridge,objects){this.handles=objects.map((object=>bridge.handleFor(object)))}deref(){return this.handles.map((handle=>handle.deref()))}}class Bridge{constructor(release){this.internalType=null;this.release=release;this.handlesByAddress={};this.handlesByObject=new WeakMap;this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this));Bridge.all.push(new WeakRef(this))}get type(){if(this.internalType==null){throw new Error("Bridge type has not been registered yet.")}return this.internalType}registerType(value){if(this.internalType===value){return}if(this.internalType){throw new Error(`Can't register bridged type '${value.name}', another type was already registered: ${this.internalType}`)}this.internalType=value}handleFor(object){const handle=this.handlesByObject.get(object);if(handle==null){throw new Error(`Bridging error: ${this.type.name} object is not currently registered in this bridge.`)}return handle}handlesFor(objects){return new Handles(this,objects)}objectFor(pointer){const handle=this.handlesByAddress[pointer.addr];if(!handle)return undefined;if(handle.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${handle.type} but this bridge is configured for ${this.type}`);return handle.object()}bridge(pointer,objectOrCreate){const existingObject=this.objectFor(pointer);if(existingObject){return existingObject}if(!objectOrCreate){objectOrCreate=()=>Reflect.construct(this.type,[])}let object;if(typeof objectOrCreate==="function"){object=objectOrCreate();if(!(object instanceof this.type)){throw new Error(`Can't bridge, expected passed in create function to return a ${this.type.name} object but got: ${object}`)}}else{object=objectOrCreate}this.register(object,pointer);return object}register(object,pointer){const objectType=object.constructor;if(objectType!==this.type)throw new Error(`Can't register, bridge is configured for type ${this.type.name} but passed in object is of type ${objectType.name}`);const existingHandle=this.handlesByObject.get(object);const existingPointer=existingHandle?existingHandle.pointer:null;if(existingPointer!=null&&existingHandle!=null)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${existingHandle.object()}`);if(existingPointer!=null&&existingHandle==null)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no handle entry: ${objectType.name} at ${existingPointer.type} ${existingPointer.addr}`);if(existingPointer==null&&existingHandle!=null)throw new Error(`Internal inconsistency, trying to register an object which has a handle entry but no associated pointer: ${objectType.name} ${object}`);const handle=new Handle(this,object,pointer);this.handlesByAddress[pointer.addr]=handle;this.handlesByObject.set(object,handle);this.finalizationRegistry.register(object,handle,object);if(DEBUG_TYPE_NAMES.includes(this.type.name)||DEBUG_ALL_TYPES){Logger.debug(`[VERBOSE] Bridge REGISTERED a new instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}}unregister(object){const objectType=object.constructor;const bridgeType=this.type;if(objectType!==bridgeType)throw new Error(`Can't unregister, bridge is configured for type ${bridgeType.name} but passed in object is of type ${objectType.name}`);const handle=this.handlesByObject.get(object);if(handle==null)throw new Error(`Can't unregister, object has not been registered before: ${object}`);if(handle.type!==bridgeType)throw new Error(`Internal inconsistency, trying to unregister an object that has a handle with a different type than that of the bridge: ${handle}`);if(handle.objectOrNull()!==object)throw new Error(`Internal inconsistency, trying to unregister an object whose associated handle holds a different object: ${handle}`);if(handle.isClosed)throw new Error(`Can't unregister, object has been closed before: ${object}`);if(handle.isFinalized)throw new Error(`Can't unregister, object has been finalized before: ${object}`);if(handle.isUnregistered)throw new Error(`Can't unregister, object has been unregistered already: ${object}`);handle.bridgeWillUnregister();this.finalizationRegistry.unregister(object);delete this.handlesByAddress[handle.pointer.addr];this.handlesByObject.delete(object);handle.bridgeDidUnregister();if(DEBUG_TYPE_NAMES.includes(this.type.name)||DEBUG_ALL_TYPES){Logger.debug(`[VERBOSE] Bridge UNREGISTERED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}}unregisterAll(){if(DEBUG_TYPE_NAMES.includes(this.type.name)||DEBUG_ALL_TYPES){Logger.debug(`[VERBOSE] Unregistering ALL bridged instances of type ${this.type.name}.`)}for(const handle of Object.values(this.handlesByAddress)){const object=handle.object();if(object){this.unregister(object)}}}async close(object){const objectType=object.constructor;const bridgeType=this.type;if(objectType!==bridgeType)throw new Error(`Can't close, bridge is configured for type ${bridgeType.name} but passed in object is of type ${objectType.name}`);const handle=this.handlesByObject.get(object);if(handle==null)throw new Error(`Can't close an object that has not been registered before: ${object}`);if(handle.type!==bridgeType)throw new Error(`Internal inconsistency, trying to close an object that has a handle with a different type than that of the bridge: ${handle}`);if(handle.isUnregistered)throw new Error(`Can't close object, object has been unregistered.`);if(handle.isFinalized)throw new Error(`Internal inconsistency, trying to close an object that has already been finalized.`);if(handle.isClosed)return;const pointer=handle.pointer;if(!pointer)throw new Error(`Internal inconsistency, trying to close an object whose pointer is null.`);handle.bridgeWillClose();delete this.handlesByAddress[pointer.addr];await this.release(pointer);handle.bridgeDidClose();if(DEBUG_TYPE_NAMES.includes(this.type.name)||DEBUG_ALL_TYPES){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(handle){if(handle.isFinalized)throw new Error(`Internal inconsistency, trying to finalize an object that has already been finalized.`);if(handle.isUnregistered)throw new Error(`Internal inconsistency, trying to finalize an object that has been unregistered before.`);handle.bridgeWillFinalize();if(!handle.isClosed){const pointer=handle.pointer;if(!pointer)throw new Error(`Internal inconsistency, trying to finalize an object whose pointer is null.`);delete this.handlesByAddress[pointer.addr];await this.release(pointer)}handle.bridgeDidFinalize();if(DEBUG_TYPE_NAMES.includes(this.type.name)||DEBUG_ALL_TYPES){Logger.debug(`[VERBOSE] Bridge FINALIZED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)}}}Bridge.all=[];Bridge.attachment=new Bridge(freeAttachmentHandle);Bridge.document=new Bridge(documentFree);Bridge.mutableDocument=new Bridge(documentFree);Bridge.dqlResponse=new Bridge(dqlResponseFree);Bridge.dqlResult=new Bridge(dqlResultFree);Bridge.staticTCPClient=new Bridge(staticTCPClientFreeHandle);Bridge.websocketClient=new Bridge(websocketClientFreeHandle);Bridge.ditto=new Bridge((async dittoPointer=>{dittoClearPresenceCallback(dittoPointer);await dittoShutdown(dittoPointer);dittoFree(dittoPointer)}));class UpdateResult{static set(docID,path,value){return new UpdateResult("set",docID,path,value,undefined)}static incremented(docID,path,amount){return new UpdateResult("incremented",docID,path,undefined,amount)}static removed(docID,path){return new UpdateResult("removed",docID,path,undefined,undefined)}constructor(type,docID,path,value,amount){this.type=type;this.docID=docID;this.path=path;if(value!==undefined)this.value=value;if(amount!==undefined)this.amount=amount}}class Attachment{get metadata(){return this.token.metadata}getData(){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return this.ditto.deferCloseAsync((async()=>{{const attachmentHandle=Bridge.attachment.handleFor(this);return await dittoGetCompleteAttachmentData(dittoHandle.deref(),attachmentHandle.deref())}}))}copyToPath(path){const ditto=this.ditto;Bridge.ditto.handleFor(ditto);return this.ditto.deferCloseAsync((async()=>{{throw new Error(`Can't copy attachment to path, not available when running in the browser.`)}}))}constructor(ditto,token){this.ditto=ditto;this.token=token}}function augmentJSONValue(json,mutDoc,workingPath){if(json&&typeof json==="object"){if(Array.isArray(json)){return json.map(((v,idx)=>augmentJSONValue(v,mutDoc,`${workingPath}[${idx}]`)))}else if(json[DittoCRDTTypeKey]===DittoCRDTType.counter){return Counter["@ditto.create"](mutDoc,workingPath,json[DittoCRDTValueKey])}else if(json[DittoCRDTTypeKey]===DittoCRDTType.register){return Register["@ditto.create"](mutDoc,workingPath,json[DittoCRDTValueKey])}else if(json[DittoCRDTTypeKey]===DittoCRDTType.attachment){return new AttachmentToken(json)}else{for(const[key,value]of Object.entries(json)){json[key]=augmentJSONValue(value,mutDoc,`${workingPath}['${key}']`)}return json}}else{return json}}function desugarJSObject(jsObj,atRoot=false){if(jsObj&&typeof jsObj==="object"){if(Array.isArray(jsObj)){return jsObj.map(((v,idx)=>desugarJSObject(v,false)))}else if(jsObj instanceof DocumentID){return jsObj.value}else if(jsObj instanceof Counter){const counterJSON={};counterJSON[DittoCRDTTypeKey]=DittoCRDTType.counter;counterJSON[DittoCRDTValueKey]=jsObj.value;return counterJSON}else if(jsObj instanceof Register){const registerJSON={};registerJSON[DittoCRDTTypeKey]=DittoCRDTType.register;registerJSON[DittoCRDTValueKey]=jsObj.value;return registerJSON}else if(jsObj instanceof Attachment){const attachmentJSON={_id:jsObj.token.id,_len:jsObj.token.len,_meta:jsObj.token.metadata};attachmentJSON[DittoCRDTTypeKey]=DittoCRDTType.attachment;return attachmentJSON}else{for(const[key,value]of Object.entries(jsObj)){jsObj[key]=desugarJSObject(value,false)}return jsObj}}else{checkForUnsupportedValues(jsObj);return jsObj}}function checkForUnsupportedValues(jsObj){if(Number.isNaN(jsObj)||jsObj===Infinity||jsObj===-Infinity){throw new Error("Non-finite float values are not supported")}}const defaultDittoCloudDomain=`cloud.ditto.live`;function defaultAuthURL(appID){return`https://${appID}.${defaultDittoCloudDomain}`}function defaultDittoCloudURL(appID){return`wss://${appID}.${defaultDittoCloudDomain}`}function validateNumber(value,options={}){var _a;const errorMessagePrefix=(_a=options["errorMessagePrefix"])!==null&&_a!==void 0?_a:"Number validation failed:";const integer=!!options["integer"];const min=options["min"];const max=options["max"];const minX=options["minX"];const maxX=options["maxX"];if(typeof value!=="number")throw new Error(`${errorMessagePrefix} '${value}' is not a number.`);if(integer&&Math.floor(value)!==value)throw new Error(`${errorMessagePrefix} '${value}' is not an integer.`);if(typeof min!=="undefined"&&value<min)throw new Error(`${errorMessagePrefix} '${value}' must be >= ${min}.`);if(typeof max!=="undefined"&&value>max)throw new Error(`${errorMessagePrefix} '${value}' must be <= ${max}.`);if(typeof minX!=="undefined"&&value<=minX)throw new Error(`${errorMessagePrefix} '${value}' must be > ${minX}.`);if(typeof maxX!=="undefined"&&value>=maxX)throw new Error(`${errorMessagePrefix} '${value}' must be < ${maxX}.`);return value}function validateQuery(query,options={}){var _a;const errorMessagePrefix=(_a=options["errorMessagePrefix"])!==null&&_a!==void 0?_a:"Query validation failed,";if(typeof query!=="string")throw new Error(`${errorMessagePrefix} query is not a string: ${query}`);if(query==="")throw new Error(`${errorMessagePrefix} query is an empty string.`);const validatedQuery=query.trim();if(validatedQuery==="")throw new Error(`${errorMessagePrefix} query contains only whitespace characters.`);return validatedQuery}function generateEphemeralToken(){let webcrypto=undefined;let data=new Uint16Array(16);{webcrypto=crypto;webcrypto.getRandomValues(data)}const doublets=Array.from(data);return doublets.map((doublet=>doublet.toString(16))).join("")}function sleep(milliseconds){return new Promise(((resolve,reject)=>{setTimeout(resolve,milliseconds)}))}async function step(closure){await sleep(0);return closure()}const performAsyncToWorkaroundNonAsyncFFIAPI=step;const regularKeyPattern=/\.([A-Za-z_]\w*)/.source;const subscriptIndexPattern=/\[(\d+)\]/.source;const subscriptSingleQuoteKeyPattern=/\[\'(.+?)\'\]/.source;const subscriptDoubleQuoteKeyPattern=/\[\"(.+?)\"\]/.source;const validKeyPathPattern=`((${regularKeyPattern})|(${subscriptIndexPattern})|(${subscriptSingleQuoteKeyPattern})|(${subscriptDoubleQuoteKeyPattern}))*`;const regularKeyRegExp=new RegExp(`^${regularKeyPattern}`);const subscriptIndexRegExp=new RegExp(`^${subscriptIndexPattern}`);const subscriptSingleQuoteKeyRegExp=new RegExp(`^${subscriptSingleQuoteKeyPattern}`);const subscriptDoubleQuoteKeyRegExp=new RegExp(`^${subscriptDoubleQuoteKeyPattern}`);const validKeyPathRegExp=new RegExp(`^${validKeyPathPattern}$`);class KeyPath{static withLeadingDot(keyPath){if(typeof keyPath==="number"){return keyPath}if(typeof keyPath!=="string"){throw new Error(`Key-path must be a string or a number but is ${typeof keyPath}: ${keyPath}`)}const needsLeadingDot=typeof keyPath==="string"&&!!keyPath.match(/^[A-Za-z_]/);return needsLeadingDot?`.${keyPath}`:keyPath}static withoutLeadingDot(keyPath){if(typeof keyPath==="number"){return keyPath}if(typeof keyPath!=="string"){throw new Error(`Key-path must be a string or a number but is ${typeof keyPath}: ${keyPath}`)}const hasLeadingDot=typeof keyPath==="string"&&!!keyPath.match(/^\./);return hasLeadingDot?keyPath.slice(1):keyPath}static validate(keyPath,options={}){var _a;const isInitial=(_a=options.isInitial)!==null&&_a!==void 0?_a:false;if(typeof keyPath==="number"){return Math.floor(Math.abs(keyPath))}if(typeof keyPath!=="string"){throw new Error(`Key-path must be a string or a number but is ${typeof keyPath}: ${keyPath}`)}const keyPathWithLeadingDot=this.withLeadingDot(keyPath);if(!validKeyPathRegExp.test(keyPathWithLeadingDot)){throw new Error(`Key-path is not valid: ${keyPath}`)}return isInitial?keyPath:keyPathWithLeadingDot}static evaluate(keyPath,object,options={}){var _a;const stopAtLastContainer=(_a=options.stopAtLastContainer)!==null&&_a!==void 0?_a:false;const evaluationResult={keyPath:keyPath,object:object,options:{...options},coveredPath:null,nextPathComponent:null,remainingPath:keyPath,value:object};function advance(keyPath){if(typeof keyPath==="number"){return{nextPathComponentRaw:keyPath,nextPathComponent:keyPath,remainingPath:""}}if(typeof keyPath!=="string"){throw new Error(`Can't return value at given keyPath, expected keyPath to be a string or a number but got ${typeof keyPath}: ${keyPath}`)}const regularKeyMatch=keyPath.match(regularKeyRegExp);if(regularKeyMatch!==null){const nextPathComponentRaw=regularKeyMatch[0];const nextPathComponent=regularKeyMatch[1];const remainingPath=keyPath.slice(nextPathComponent.length+1);return{nextPathComponentRaw:nextPathComponentRaw,nextPathComponent:nextPathComponent,remainingPath:remainingPath}}const subscriptIndexMatch=keyPath.match(subscriptIndexRegExp);if(subscriptIndexMatch!==null){const nextPathComponentRaw=subscriptIndexMatch[0];const nextPathComponentString=subscriptIndexMatch[1];const nextPathComponent=parseInt(nextPathComponentString);const remainingPath=keyPath.slice(nextPathComponentString.length+2);return{nextPathComponentRaw:nextPathComponentRaw,nextPathComponent:nextPathComponent,remainingPath:remainingPath}}const subscriptSingleQuoteMatch=keyPath.match(subscriptSingleQuoteKeyRegExp);if(subscriptSingleQuoteMatch!==null){const nextPathComponentRaw=subscriptSingleQuoteMatch[0];const nextPathComponent=subscriptSingleQuoteMatch[1];const remainingPath=keyPath.slice(nextPathComponent.length+4);return{nextPathComponentRaw:nextPathComponentRaw,nextPathComponent:nextPathComponent,remainingPath:remainingPath}}const subscriptDoubleQuoteMatch=keyPath.match(subscriptDoubleQuoteKeyRegExp);if(subscriptDoubleQuoteMatch!==null){const nextPathComponentRaw=subscriptDoubleQuoteMatch[0];const nextPathComponent=subscriptDoubleQuoteMatch[1];const remainingPath=keyPath.slice(nextPathComponent.length+4);return{nextPathComponentRaw:nextPathComponentRaw,nextPathComponent:nextPathComponent,remainingPath:remainingPath}}throw new Error(`Can't return value at keyPath because the following part of the keyPath is invalid: ${keyPath}`)}function recurse(object,keyPath){if(keyPath===""){evaluationResult.value=object;return evaluationResult}const{nextPathComponentRaw:nextPathComponentRaw,nextPathComponent:nextPathComponent,remainingPath:remainingPath}=advance(keyPath);evaluationResult.nextPathComponent=nextPathComponent;evaluationResult.remainingPath=remainingPath;if(evaluationResult.coveredPath===null||typeof nextPathComponentRaw==="number"){evaluationResult.coveredPath=nextPathComponentRaw}else{evaluationResult.coveredPath+=nextPathComponentRaw}if(remainingPath===""&&stopAtLastContainer){evaluationResult.value=object;return evaluationResult}const nextObject=object[nextPathComponent];return recurse(nextObject,remainingPath)}const keyPathWithLeadingDot=this.withLeadingDot(keyPath);return recurse(object,keyPathWithLeadingDot)}constructor(){}}class DocumentPath{at(keyPathOrIndex){if(typeof keyPathOrIndex==="string"){const keyPath=keyPathOrIndex;const validatedKeyPath=KeyPath.validate(keyPath);const absoluteKeyPath=KeyPath.withoutLeadingDot(`${this.path}${validatedKeyPath}`);return new DocumentPath(this.document,absoluteKeyPath,false)}if(typeof keyPathOrIndex==="number"){const index=keyPathOrIndex;const validatedIndex=validateNumber(index,{integer:true,min:0,errorMessagePrefix:"DocumentPath.at() validation failed index:"});return new DocumentPath(this.document,`${this.path}[${validatedIndex.toString()}]`,false)}throw new Error(`Can't return document path at key-path or index, string or number expected but got ${typeof keyPathOrIndex}: ${keyPathOrIndex}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const underlyingValue=this.underlyingValueForPathType("Counter");return typeof underlyingValue!=="undefined"?Counter["@ditto.create"](null,this.path,underlyingValue):null}get register(){const underlyingValue=this.underlyingValueForPathType("Register");return typeof underlyingValue!=="undefined"?Register["@ditto.create"](null,this.path,underlyingValue):null}get attachmentToken(){const underlyingValue=this.underlyingValueForPathType("Attachment");return typeof underlyingValue!=="undefined"?new AttachmentToken(underlyingValue):null}constructor(document,path,validate){this.document=document;this.path=validate?KeyPath.validate(path,{isInitial:true}):path}underlyingValueForPathType(pathType){const path=this.path;const document=this.document;const documentHandle=Bridge.document.handleFor(document);const cborPathResult=documentGetCBORWithPathType(documentHandle.deref(),path,pathType);return cborPathResult.cbor!==null?CBOR.decode(cborPathResult.cbor):undefined}}class MutableDocumentPath{at(keyPathOrIndex){if(typeof keyPathOrIndex==="string"){const keyPath=keyPathOrIndex;const validatedKeyPath=KeyPath.validate(keyPath);const absoluteKeyPath=KeyPath.withoutLeadingDot(`${this.path}${validatedKeyPath}`);return new MutableDocumentPath(this.mutableDocument,absoluteKeyPath,false)}if(typeof keyPathOrIndex==="number"){const index=keyPathOrIndex;const validatedIndex=validateNumber(index,{integer:true,min:0,errorMessagePrefix:"MutableDocumentPath.at() validation failed index:"});return new MutableDocumentPath(this.mutableDocument,`${this.path}[${validatedIndex.toString()}]`,false)}throw new Error(`Can't return mutable document path at key-path or index, string or number expected but got ${typeof keyPathOrIndex}: ${keyPathOrIndex}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const underlyingValue=this.underlyingValueForPathType("Counter");return typeof underlyingValue!=="undefined"?Counter["@ditto.create"](this.mutableDocument,this.path,underlyingValue):null}get register(){const underlyingValue=this.underlyingValueForPathType("Register");return typeof underlyingValue!=="undefined"?Register["@ditto.create"](this.mutableDocument,this.path,underlyingValue):null}get attachmentToken(){const underlyingValue=this.underlyingValueForPathType("Attachment");return typeof underlyingValue!=="undefined"?new AttachmentToken(underlyingValue):null}set(value,isDefault){return this["@ditto.set"](value,isDefault)}remove(){return this["@ditto.remove"]()}constructor(mutableDocument,path,validate){this.mutableDocument=mutableDocument;this.path=validate?KeyPath.validate(path,{isInitial:true}):path}underlyingValueForPathType(pathType){const path=this.path;const document=this.mutableDocument;const documentHandle=Bridge.mutableDocument.handleFor(document);const cborPathResult=documentGetCBORWithPathType(documentHandle.deref(),path,pathType);return cborPathResult.cbor!==null?CBOR.decode(cborPathResult.cbor):undefined}"@ditto.increment"(amount){const documentHandle=Bridge.mutableDocument.handleFor(this.mutableDocument);documentIncrementCounter(documentHandle.deref(),this.path,amount);const updateResult=UpdateResult.incremented(this.mutableDocument.id,this.path,amount);this.recordUpdateResult(updateResult)}"@ditto.set"(value,isDefault){const documentHandle=Bridge.mutableDocument.handleFor(this.mutableDocument);const valueJSON=desugarJSObject(value,false);const valueCBOR=CBOR.encode(valueJSON);if(isDefault){documentSetCBORWithTimestamp(documentHandle.deref(),this.path,valueCBOR,0)}else{documentSetCBOR(documentHandle.deref(),this.path,valueCBOR)}const valueJSONCopy=CBOR.decode(valueCBOR);const valueCopy=augmentJSONValue(valueJSONCopy,this.mutableDocument,this.path);const updateResult=UpdateResult.set(this.mutableDocument.id,this.path,valueCopy);this.recordUpdateResult(updateResult)}"@ditto.remove"(){const documentHandle=Bridge.mutableDocument.handleFor(this.mutableDocument);documentRemove(documentHandle.deref(),this.path);this.updateInMemory(((container,lastPathComponent)=>{if(Array.isArray(container)&&typeof lastPathComponent==="number"){container.splice(lastPathComponent,1)}else{delete container[lastPathComponent]}}));const updateResult=UpdateResult.removed(this.mutableDocument.id,this.path);this.recordUpdateResult(updateResult)}updateInMemory(block){const mutableDocumentValue=this.mutableDocument.value;const evaluationResult=KeyPath.evaluate(this.path,mutableDocumentValue,{stopAtLastContainer:true});block(evaluationResult.value,evaluationResult.nextPathComponent)}recordUpdateResult(updateResult){const updateResults=this.mutableDocument["@ditto.updateResults"].slice();updateResults.push(updateResult);Object.freeze(updateResults);this.mutableDocument["@ditto.updateResults"]=updateResults}}class Document{static hash(documentOrMany){const documents=documentsFrom(documentOrMany);const documentHandles=documents.map((doc=>Bridge.document.handleFor(doc)));return documentsHash(documentHandles.map((handle=>handle.deref())))}static hashMnemonic(documentOrMany){const documents=documentsFrom(documentOrMany);const documentHandles=Bridge.document.handlesFor(documents);return documentsHashMnemonic(documentHandles.deref())}get id(){let id=this["@ditto.id"];if(typeof id==="undefined"){const documentHandle=Bridge.document.handleFor(this);const documentIDCBOR=documentID(documentHandle.deref());id=new DocumentID(documentIDCBOR,true);this["@ditto.id"]=id}return id}get path(){return new DocumentPath(this,"",false)}get value(){let value=this["@ditto.value"];if(typeof value==="undefined"){value=this.path.value;this["@ditto.value"]=value}return value}at(keyPathOrIndex){return this.path.at(keyPathOrIndex)}constructor(){}static idCBOR(document){const documentHandle=Bridge.document.handleFor(document);return documentID(documentHandle.deref())}static canonicalizedIDCBOR(idCBOR){return validateDocumentIDCBOR(idCBOR)}static isIDCBORCanonical(idCBOR){const canonicalIDCBOR=this.canonicalizedIDCBOR(idCBOR);return idCBOR===canonicalIDCBOR}}class MutableDocument{get id(){let id=this["@ditto.id"];if(typeof id==="undefined"){const documentHandle=Bridge.mutableDocument.handleFor(this);const documentIDCBOR=documentID(documentHandle.deref());id=new DocumentID(documentIDCBOR,true);this["@ditto.id"]=id}return id}get path(){return new MutableDocumentPath(this,"",false)}get value(){return this.path.value}at(keyPathOrIndex){return this.path.at(keyPathOrIndex)}constructor(){this["@ditto.updateResults"]=[]}static idCBOR(mutableDocument){const documentHandle=Bridge.mutableDocument.handleFor(mutableDocument);return documentID(documentHandle.deref())}}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR;MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;function documentsFrom(documentOrMany){if(!documentOrMany){return[]}if(documentOrMany instanceof Document){return[documentOrMany]}if(documentOrMany instanceof Array){return documentOrMany}throw new Error(`Expected null, a single document, or an array of documents but got value of type ${typeof documentOrMany}: ${documentOrMany}`)}class UpdateResultsMap{get(documentIDOrValue){const documentID=documentIDOrValue instanceof DocumentID?documentIDOrValue:new DocumentID(documentIDOrValue);const documentIDString=documentID.toString();return this.updateResultsByDocumentIDString[documentIDString]}keys(){return this.documentIDs.slice()}constructor(documentIDs,updateResultsByDocumentIDString){const documentIDStrings=documentIDs.map((documentID=>documentID.toString())).sort().join(", ");const updateResultsKeys=Object.keys(updateResultsByDocumentIDString).sort().join(", ");if(documentIDStrings!==updateResultsKeys){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=documentIDs.slice();this.updateResultsByDocumentIDString={...updateResultsByDocumentIDString}}}class BasePendingCursorOperation{sort(propertyPath,direction="ascending"){this.orderBys.push({query:propertyPath,direction:direction==="ascending"?"Ascending":"Descending"});return this}offset(offset){if(offset<0)throw new Error(`Can't offset by '${offset}', offset must be >= 0`);if(!Number.isFinite(offset))throw new Error(`Can't offset by '${offset}', offset must be a finite number`);if(Number.isNaN(offset))throw new Error(`Can't offset by '${offset}', offset must be a valid number`);const integerOffset=Math.round(offset);if(offset!==integerOffset)throw new Error(`Can't offset by '${offset}', offset must be an integer number`);this.currentOffset=offset;return this}limit(limit){if(limit<-1)throw new Error(`Can't limit to '${limit}', limit must be >= -1 (where -1 means unlimited)`);if(!Number.isFinite(limit))throw new Error(`Can't limit to '${limit}', limit must be a finite number`);if(Number.isNaN(limit))throw new Error(`Can't limit to '${limit}', limit must be a valid number`);const integerLimit=Math.round(limit);if(limit!==integerLimit)throw new Error(`Can't limit to '${limit}', limit must be an integer number`);this.currentLimit=limit;return this}async exec(){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>{const query=this.query;const documentPointers=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionExecQueryStr(dittoHandle.deref(),this.collection.name,null,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)));return documentPointers.map((documentPointer=>Bridge.document.bridge(documentPointer)))}))}async updateWithTransaction(closure,writeTransactionX){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const query=this.query;const documentsX=await collectionExecQueryStr(dittoHandle.deref(),this.collection.name,writeTransactionX,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);const mutableDocuments=documentsX.map((documentX=>Bridge.mutableDocument.bridge(documentX,(()=>new MutableDocument))));closure(mutableDocuments);const updateResultsDocumentIDs=[];const updateResultsByDocumentIDString={};for(const mutableDocument of mutableDocuments){const documentID=mutableDocument.id;const documentIDString=documentID.toString();const updateResults=mutableDocument["@ditto.updateResults"];if(updateResultsByDocumentIDString[documentIDString]){throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${documentIDString}`)}updateResultsDocumentIDs.push(documentID);updateResultsByDocumentIDString[documentIDString]=updateResults;Bridge.mutableDocument.unregister(mutableDocument)}await collectionUpdateMultiple(dittoHandle.deref(),this.collection.name,writeTransactionX,documentsX);return new UpdateResultsMap(updateResultsDocumentIDs,updateResultsByDocumentIDString)}))))}constructor(query,queryArgs,collection){this.currentLimit=-1;this.currentOffset=0;this.orderBys=[];this.query=validateQuery(query);this.queryArgs=queryArgs?Object.freeze({...queryArgs}):null;this.collection=collection;this.queryArgsCBOR=queryArgs?CBOR.encode(queryArgs):null}then(onfulfilled,onrejected){return this.exec().then(onfulfilled,onrejected)}}class BasePendingIDSpecificOperation{async exec(){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const readTransactionX=await readTransaction(dittoHandle.deref());const documentX=await collectionGet(dittoHandle.deref(),this.collection.name,this.documentIDCBOR,readTransactionX);let document=undefined;if(documentX)document=Bridge.document.bridge(documentX);readTransactionFree(readTransactionX);return document}))))}constructor(documentID,collection){this.documentID=documentID;this.collection=collection;this.documentIDCBOR=documentID.toCBOR()}then(onfulfilled,onrejected){return this.exec().then(onfulfilled,onrejected)}get query(){return`_id == ${this.documentID.toQueryCompatibleString()}`}}class ObserverManager{constructor(id,options={}){var _a,_b,_c,_d;const keepAlive=(_a=options.keepAlive)!==null&&_a!==void 0?_a:null;const register=(_b=options.register)!==null&&_b!==void 0?_b:null;const unregister=(_c=options.unregister)!==null&&_c!==void 0?_c:null;const process=(_d=options.process)!==null&&_d!==void 0?_d:null;this.id=id;this.keepAlive=keepAlive;this.isClosed=false;this.isRegistered=false;this.callbacksByToken={};if(register!==null){this.register=register}if(unregister!==null){this.unregister=unregister}if(process!==null){this.process=process}}addObserver(callback){var _a;if(this.isClosed){throw new Error(`Internal inconsistency, can't add '${this.id}' observer, observer mananger close()-ed.`)}this.registerIfNeeded();const token=generateEphemeralToken();this.callbacksByToken[token]=callback;(_a=this.keepAlive)===null||_a===void 0?void 0:_a.retain(`${this.id}.${token}`);return token}removeObserver(token){var _a;const callback=this.callbacksByToken[token];if(typeof callback==="undefined"){throw new Error(`Can't remove '${this.id}' observer, token '${token}' has never been registered before.`)}if(callback===null){return}this.callbacksByToken[token]=null;(_a=this.keepAlive)===null||_a===void 0?void 0:_a.release(`${this.id}.${token}`);this.unregisterIfNeeded()}hasObserver(token){return typeof this.callbacksByToken[token]!="undefined"}notify(...args){if(this.isClosed){return}const processedArgs=this.process(...args);for(const token in this.callbacksByToken){const callback=this.callbacksByToken[token];if(callback)callback(...processedArgs)}}close(){this.isClosed=true;for(const token in this.callbacksByToken){this.removeObserver(token)}}register(callback){}unregister(){}process(...args){return args}hasObservers(){return Object.keys(this.callbacksByToken).length>0}registerIfNeeded(){const needsToRegister=!this.isRegistered;if(needsToRegister){const weakThis=new WeakRef(this);this.isRegistered=true;this.register((function(...args){const strongThis=weakThis.deref();if(!strongThis){return}strongThis.notify(...args)}))}}unregisterIfNeeded(){const needsToUnregister=!this.hasObservers()&&this.isRegistered;if(needsToUnregister){this.isRegistered=false;this.unregister()}}}class Authenticator{get status(){return this._status}loginWithToken(token,provider){throw new Error(`Authenticator.loginWithToken() is abstract and must be implemented by subclasses.`)}loginWithUsernameAndPassword(username,password,provider){throw new Error(`Authenticator.loginWithUsernameAndPassword() is abstract and must be implemented by subclasses.`)}logout(cleanupFn){throw new Error(`Authenticator.logout() is abstract and must be implemented by subclasses.`)}observeStatus(callback){const token=this.observerManager.addObserver(callback);return new Observer(this.observerManager,token,{stopsWhenFinalized:true})}constructor(keepAlive){this.keepAlive=keepAlive;this._status={isAuthenticated:false,userID:null};this.loginSupported=false;this.observerManager=new ObserverManager("AuthenticationStatusObservation",{keepAlive:keepAlive})}"@ditto.authenticationExpiring"(number){throw new Error(`Authenticator['@ditto.authenticationExpiring']() is abstract and must be implemented by subclasses.`)}"@ditto.authClientValidityChanged"(isWebValid,isX509Valid){throw new Error(`Authenticator['@ditto.authClientValidityChanged']() is abstract and must be implemented by subclasses.`)}close(){this.observerManager.close()}}class OnlineAuthenticator extends Authenticator{async loginWithToken(token,provider){const ditto=this.ditto.deref();if(!ditto){return}const dittoHandle=Bridge.ditto.handleFor(ditto);const dittoPointer=dittoHandle.derefOrNull();if(!dittoPointer){return}return ditto.deferCloseAsync((async()=>{await dittoAuthClientLoginWithToken(dittoPointer,token,provider)}))}async loginWithUsernameAndPassword(username,password,provider){const ditto=this.ditto.deref();if(!ditto){return}const dittoHandle=Bridge.ditto.handleFor(ditto);const dittoPointer=dittoHandle.derefOrNull();if(!dittoPointer){return}return ditto.deferCloseAsync((async()=>{await dittoAuthClientLoginWithUsernameAndPassword(dittoPointer,username,password,provider)}))}async logout(cleanupFn){const ditto=this.ditto.deref();if(!ditto){return}const dittoHandle=Bridge.ditto.handleFor(ditto);const dittoPointer=dittoHandle.derefOrNull();if(!dittoPointer){return}return ditto.deferCloseAsync((async()=>{await dittoAuthClientLogout(dittoPointer);ditto.stopSync();cleanupFn===null||cleanupFn===void 0?void 0:cleanupFn(ditto)}))}constructor(keepAlive,ditto,authenticationHandler){super(keepAlive);this.loginSupported=true;this._status={isAuthenticated:false,userID:null};this.ditto=new WeakRef(ditto);this.authenticationHandler=authenticationHandler;this.updateAndNotify(false)}"@ditto.authenticationExpiring"(secondsRemaining){const authenticationHandler=this.authenticationHandler;if(secondsRemaining>0){authenticationHandler.authenticationExpiringSoon(this,secondsRemaining)}else{authenticationHandler.authenticationRequired(this)}}"@ditto.authClientValidityChanged"(isWebValid,isX509Valid){this.updateAndNotify(true)}updateAndNotify(shouldNotify){var _a;const ditto=this.ditto.deref();if(!ditto){Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");return}const dittoHandle=Bridge.ditto.handleFor(ditto);const dittoPointer=dittoHandle.derefOrNull();if(!dittoPointer){Logger.debug("Unable to update auth status and notify, related Ditto object does not exist anymore.");return}const wasAuthenticated=this.status.isAuthenticated;const previousUserID=this.status.userID;const isAuthenticated=dittoAuthClientIsWebValid(dittoPointer);const userID=dittoAuthClientUserID(dittoPointer);const status={isAuthenticated:isAuthenticated,userID:userID};this._status=status;if(shouldNotify){const sameStatus=!!wasAuthenticated===!!isAuthenticated&&previousUserID===userID;if(!sameStatus){(_a=this.authenticationHandler.authenticationStatusDidChange)===null||_a===void 0?void 0:_a.call(this.authenticationHandler,this);this.observerManager.notify(status)}}}}class NotAvailableAuthenticator extends Authenticator{async loginWithToken(token,provider){throw new Error(`Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.`)}async loginWithUsernameAndPassword(username,password,provider){throw new Error(`Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.`)}logout(cleanupFn){throw new Error(`Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.`)}"@ditto.authenticationExpiring"(secondsRemaining){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${this}`)}"@ditto.authClientValidityChanged"(isWebValid,isX509Valid){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(serialized){const peerToPeerJSON=serialized["peer_to_peer"];const bluetoothLEJSON=peerToPeerJSON["bluetooth_le"];const bluetoothLEEnabled=bluetoothLEJSON["enabled"];const awdlJSON=peerToPeerJSON["awdl"];const awdlEnabled=awdlJSON["enabled"];const lanJSON=peerToPeerJSON["lan"];const lanEnabled=lanJSON["enabled"];const lanMdnsEnabled=lanJSON["mdns_enabled"];const lanMulticastEnabled=lanJSON["multicast_enabled"];const connectJSON=serialized["connect"];const connectTcpServers=connectJSON["tcp_servers"];const connectWebsocketURLs=connectJSON["websocket_urls"];const connectRetryInterval=connectJSON["retry_interval"];const listenJSON=serialized["listen"];const tcpJSON=listenJSON["tcp"];const tcpEnabled=tcpJSON["enabled"];const tcpInterfaceIP=tcpJSON["interface_ip"];const tcpPort=tcpJSON["port"];const httpJSON=listenJSON["http"];const httpEnabled=httpJSON["enabled"];const httpInterfaceIP=httpJSON["interface_ip"];const httpPort=httpJSON["port"];const httpStaticContentPath=httpJSON["static_content_path"];const httpWebsocketSync=httpJSON["websocket_sync"];const httpTLSKeyPath=httpJSON["tls_key_path"];const httpTLSCertificatePath=httpJSON["tls_certificate_path"];const globalJSON=serialized["global"];const globalSyncGroup=globalJSON["sync_group"];const globalRoutingHint=globalJSON["routing_hint"];const config=new TransportConfig;config.peerToPeer.bluetoothLE.isEnabled=bluetoothLEEnabled;config.peerToPeer.awdl.isEnabled=awdlEnabled;config.peerToPeer.lan.isEnabled=lanEnabled;config.peerToPeer.lan.isMdnsEnabled=lanMdnsEnabled;config.peerToPeer.lan.isMulticastEnabled=lanMulticastEnabled;config.connect.tcpServers=connectTcpServers;config.connect.websocketURLs=connectWebsocketURLs;config.connect.retryInterval=connectRetryInterval;config.listen.tcp.isEnabled=tcpEnabled;config.listen.tcp.interfaceIP=tcpInterfaceIP;config.listen.tcp.port=tcpPort;config.listen.http.isEnabled=httpEnabled;config.listen.http.interfaceIP=httpInterfaceIP;config.listen.http.port=httpPort;config.listen.http.staticContentPath=httpStaticContentPath;config.listen.http.websocketSync=httpWebsocketSync;config.listen.http.tlsKeyPath=httpTLSKeyPath;config.listen.http.tlsCertificatePath=httpTLSCertificatePath;config.global.syncGroup=globalSyncGroup;config.global.routingHint=globalRoutingHint;return config}function transportConfigToSerializable(config){const peerToPeer=config.peerToPeer;const connect=config.connect;const listen=config.listen;const global=config.global;const serialized={peer_to_peer:{bluetooth_le:{enabled:peerToPeer.bluetoothLE.isEnabled},awdl:{enabled:peerToPeer.awdl.isEnabled},lan:{enabled:peerToPeer.lan.isEnabled,mdns_enabled:peerToPeer.lan.isMdnsEnabled,multicast_enabled:peerToPeer.lan.isMulticastEnabled}},connect:{tcp_servers:connect.tcpServers,websocket_urls:connect.websocketURLs,retry_interval:connect.retryInterval},listen:{tcp:{enabled:listen.tcp.isEnabled,interface_ip:listen.tcp.interfaceIP,port:listen.tcp.port},http:{enabled:listen.http.isEnabled,interface_ip:listen.http.interfaceIP,port:listen.http.port,websocket_sync:listen.http.websocketSync}},global:{sync_group:global.syncGroup,routing_hint:global.routingHint}};if(listen.http.staticContentPath){serialized.listen.http["static_content_path"]=listen.http.staticContentPath}if(listen.http.tlsKeyPath){serialized.listen.http["tls_key_path"]=listen.http.tlsKeyPath}if(listen.http.tlsCertificatePath){serialized.listen.http["tls_certificate_path"]=listen.http.tlsCertificatePath}return serialized}const NO_PREFERRED_ROUTE_HINT=0;class TransportConfig{constructor(){this._isFrozen=false;this.peerToPeer={bluetoothLE:{isEnabled:false},awdl:{isEnabled:false},lan:{isEnabled:false,isMdnsEnabled:true,isMulticastEnabled:true}};this.connect={tcpServers:[],websocketURLs:[],retryInterval:5e3};this.listen={tcp:{isEnabled:false,interfaceIP:"0.0.0.0",port:4040},http:{isEnabled:false,interfaceIP:"0.0.0.0",port:80,websocketSync:true}};this.global={syncGroup:0,routingHint:NO_PREFERRED_ROUTE_HINT}}setAllPeerToPeerEnabled(enabled){this.peerToPeer.bluetoothLE.isEnabled=enabled;this.peerToPeer.lan.isEnabled=enabled;this.peerToPeer.awdl.isEnabled=enabled}get isFrozen(){return this._isFrozen}freeze(){if(this.isFrozen)return this;this._isFrozen=true;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);return this}copy(){const copy=new TransportConfig;copy.peerToPeer.bluetoothLE.isEnabled=this.peerToPeer.bluetoothLE.isEnabled;copy.peerToPeer.awdl.isEnabled=this.peerToPeer.awdl.isEnabled;copy.peerToPeer.lan.isEnabled=this.peerToPeer.lan.isEnabled;copy.peerToPeer.lan.isMdnsEnabled=this.peerToPeer.lan.isMdnsEnabled;copy.peerToPeer.lan.isMulticastEnabled=this.peerToPeer.lan.isMulticastEnabled;copy.connect.tcpServers=this.connect.tcpServers.slice();copy.connect.websocketURLs=this.connect.websocketURLs.slice();copy.connect.retryInterval=this.connect.retryInterval;copy.listen.tcp={...this.listen.tcp};copy.listen.http={...this.listen.http};copy.global.syncGroup=this.global.syncGroup;copy.global.routingHint=this.global.routingHint;return copy}static areListenTCPsEqual(left,right){return left.isEnabled===right.isEnabled&&left.interfaceIP===right.interfaceIP&&left.port===right.port}static areListenHTTPsEqual(left,right){return left.isEnabled===right.isEnabled&&left.interfaceIP===right.interfaceIP&&left.port===right.port&&left.staticContentPath===right.staticContentPath&&left.websocketSync===right.websocketSync&&left.tlsKeyPath===right.tlsKeyPath&&left.tlsCertificatePath===right.tlsCertificatePath}}class Subscription{get isCancelled(){return this._isCancelled}get collectionName(){return this.collection.name}cancel(){if(!this.isCancelled){this._isCancelled=true;this.manager.remove(this)}}constructor(collection,query,queryArgsCBOR,orderBys,limit,offset){this._isCancelled=false;this.query=query;this.queryArgsCBOR=queryArgsCBOR;this.collection=collection;this.contextInfo={id:generateEphemeralToken(),collectionName:collection.name,query:query,queryArgsCBOR:queryArgsCBOR,orderBys:orderBys,limit:limit,offset:offset};this.manager=collection.store.ditto.subscriptionManager;this.manager.add(this)}}class LiveQueryEventInitial{constructor(){this.isInitial=true}hash(documents){Logger.warning("LiveQueryEventInitial.hash() is deprecated, use Document.hash() instead");const documentHandles=Bridge.document.handlesFor(documents);return documentsHash(documentHandles.deref())}hashMnemonic(documents){Logger.warning("LiveQueryEventInitial.hashMnemonic() is deprecated, use Document.hashMnemonic() instead");const documentHandles=Bridge.document.handlesFor(documents);return documentsHashMnemonic(documentHandles.deref())}}class LiveQueryEventUpdate{hash(documents){Logger.warning("LiveQueryEventUpdate.hash() is deprecated, use Document.hash() instead");const documentHandles=Bridge.document.handlesFor(documents);return documentsHash(documentHandles.deref())}hashMnemonic(documents){Logger.warning("LiveQueryEventUpdate.hashMnemonic() is deprecated, use Document.hashMnemonic() instead");const documentHandles=Bridge.document.handlesFor(documents);return documentsHashMnemonic(documentHandles.deref())}constructor(params){this.isInitial=false;this.oldDocuments=params.oldDocuments;this.insertions=params.insertions;this.deletions=params.deletions;this.updates=params.updates;this.moves=params.moves}}class SingleDocumentLiveQueryEvent{hash(document){Logger.warning("SingleDocumentLiveQueryEvent.hash() is deprecated, use Document.hash() instead");const documentHandles=Bridge.document.handlesFor(document==null?[]:[document]);return documentsHash(documentHandles.deref())}hashMnemonic(document){Logger.warning("SingleDocumentLiveQueryEvent.hashMnemonic() is deprecated, use Document.hashMnemonic() instead");const documentHandles=Bridge.document.handlesFor(document==null?[]:[document]);return documentsHashMnemonic(documentHandles.deref())}constructor(isInitial,oldDocument){this.isInitial=isInitial;this.oldDocument=oldDocument}}class LiveQuery{get collectionName(){return this.collection.name}get isStopped(){return!this.liveQueryManager}stop(){if(!this.isStopped){this.liveQueryManager.stopLiveQuery(this)}}get liveQueryID(){return this._liveQueryID}constructor(query,queryArgs,queryArgsCBOR,orderBys,limit,offset,collection,handler){this.query=query;this.queryArgs=queryArgs?Object.freeze({...queryArgs}):null;this.queryArgsCBOR=queryArgsCBOR;this.orderBys=orderBys;this.limit=limit;this.offset=offset;this.collection=collection;this.handler=handler;this.liveQueryManager=null;const collectionName=collection.name;const weakDitto=new WeakRef(collection.store.ditto);let liveQueryID=undefined;const signalNext=async()=>{const ditto=weakDitto.deref();if(!ditto)return;const dittoHandle=Bridge.ditto.handleFor(ditto);const dittoPointer=dittoHandle.derefOrNull();if(!dittoPointer)return;return ditto.deferCloseAsync((async()=>{await liveQuerySignalAvailableNext(dittoPointer,liveQueryID)}))};const ditto=collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);ditto.deferClose((()=>{liveQueryID=liveQueryRegister(dittoHandle.deref(),collectionName,query,queryArgsCBOR,this.orderBys,limit,offset,(cCBParams=>{const documents=cCBParams.documents.map((ptr=>Bridge.document.bridge(ptr)));let event;if(cCBParams.is_initial){event=new LiveQueryEventInitial}else{event=new LiveQueryEventUpdate({oldDocuments:cCBParams.old_documents.map((ptr=>Bridge.document.bridge(ptr))),insertions:cCBParams.insertions,deletions:cCBParams.deletions,updates:cCBParams.updates,moves:cCBParams.moves.map((move=>({from:move[0],to:move[1]})))})}handler(documents,event,signalNext)}))}));if(!liveQueryID){throw new Error("Internal inconsistency, couldn't create a valid live query ID.")}this._liveQueryID=liveQueryID}async signalNext(){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);const dittoPointer=dittoHandle.derefOrNull();if(!dittoPointer)return;return ditto.deferCloseAsync((async()=>{await liveQuerySignalAvailableNext(dittoHandle.deref(),this.liveQueryID)}))}}class PendingCursorOperation extends BasePendingCursorOperation{sort(propertyPath,direction="ascending"){return super.sort(propertyPath,direction)}offset(offset){return super.offset(offset)}limit(limit){return super.limit(limit)}async remove(){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>{const query=this.query;const documentsX=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const writeTransactionX=await writeTransaction(dittoHandle.deref());const results=await collectionRemoveQueryStr(dittoHandle.deref(),this.collection.name,writeTransactionX,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);await writeTransactionCommit(dittoHandle.deref(),writeTransactionX);return results}));return documentsX.map((idCBOR=>new DocumentID(idCBOR,true)))}))}async evict(){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>{const query=this.query;const documentsX=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const writeTransactionX=await writeTransaction(dittoHandle.deref());const results=await collectionEvictQueryStr(dittoHandle.deref(),this.collection.name,writeTransactionX,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);await writeTransactionCommit(dittoHandle.deref(),writeTransactionX);return results}));return documentsX.map((idCBOR=>new DocumentID(idCBOR,true)))}))}async update(closure){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const writeTransactionX=await writeTransaction(dittoHandle.deref());const results=await super.updateWithTransaction(closure,writeTransactionX);await writeTransactionCommit(dittoHandle.deref(),writeTransactionX);return results}))))}subscribe(){const subscription=new Subscription(this.collection,this.query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);this.collection.store.ditto.subscriptionManager.add(subscription);return subscription}observeLocal(handler){return this._observe(handler,false)}observeLocalWithNextSignal(handler){return this._observe(handler,true)}constructor(query,queryArgs,collection){super(query,queryArgs,collection)}_observe(handler,waitForNextSignal){function wrappedHandler(documents,event,nextSignal){try{return handler.call(this,documents,event)}finally{nextSignal()}}const handlerOrWrapped=waitForNextSignal?handler:wrappedHandler;const liveQuery=new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,handlerOrWrapped);this.collection.store.ditto.liveQueryManager.startLiveQuery(liveQuery);return liveQuery}}class PendingIDSpecificOperation extends BasePendingIDSpecificOperation{async remove(){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const writeTransactionX=await writeTransaction(dittoHandle.deref());const didRemove=await collectionRemove(dittoHandle.deref(),this.collection.name,writeTransactionX,this.documentIDCBOR);await writeTransactionCommit(dittoHandle.deref(),writeTransactionX);return didRemove}))))}async evict(){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const writeTransactionX=await writeTransaction(dittoHandle.deref());const didEvict=await collectionEvict(dittoHandle.deref(),this.collection.name,writeTransactionX,this.documentIDCBOR);await writeTransactionCommit(dittoHandle.deref(),writeTransactionX);return didEvict}))))}async update(closure){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>{const readTransactionX=await readTransaction(dittoHandle.deref());const documentX=await collectionGet(dittoHandle.deref(),this.collection.name,this.documentIDCBOR,readTransactionX);readTransactionFree(readTransactionX);if(!documentX)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const mutableDocument=Bridge.mutableDocument.bridge(documentX,(()=>new MutableDocument));closure(mutableDocument);Bridge.mutableDocument.unregister(mutableDocument);const writeTransactionX=await writeTransaction(dittoHandle.deref());await collectionUpdate(dittoHandle.deref(),this.collection.name,writeTransactionX,documentX);await writeTransactionCommit(dittoHandle.deref(),writeTransactionX);return mutableDocument["@ditto.updateResults"].slice()}))}subscribe(){const subscription=new Subscription(this.collection,this.query,null,[],-1,0);this.collection.store.ditto.subscriptionManager.add(subscription);return subscription}observeLocal(handler){return this._observe(handler,false)}observeLocalWithNextSignal(handler){return this._observe(handler,true)}constructor(documentID,collection){super(documentID,collection)}_observe(handler,waitForNextSignal){const liveQuery=new LiveQuery(this.query,null,null,[],-1,0,this.collection,((documents,event,signalNext)=>{if(documents.length>1){const documentIDsAsBase64Strings=documents.map((document=>document.id.toBase64String()));throw new Error(`Internal inconsistency, single document live query returned more than one document. Query: ${this.query}, documentIDs: ${documentIDsAsBase64Strings.join(", ")}.`)}if(event.isInitial===false&&event.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(event.isInitial===false&&event.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(event.isInitial===false&&event.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(event.isInitial===false&&event.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(event.isInitial===false&&event.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}.`);const totalNumberOfManipulations=event.isInitial===true?0:event.insertions.length+event.deletions.length+event.updates.length;if(totalNumberOfManipulations>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 document=documents[0]||null;const oldDocument=event.isInitial===true?undefined:event.oldDocuments[0];const singleDocumentEvent=new SingleDocumentLiveQueryEvent(event.isInitial,oldDocument);if(waitForNextSignal){handler(document,singleDocumentEvent,signalNext)}else{try{handler(document,singleDocumentEvent)}finally{signalNext()}}}));this.collection.store.ditto.liveQueryManager.startLiveQuery(liveQuery);return liveQuery}}class Collection{find(query,queryArgs){return new PendingCursorOperation(query,queryArgs!==null&&queryArgs!==void 0?queryArgs:null,this)}findAll(){return this.find("true")}findByID(id){const documentID=id instanceof DocumentID?id:new DocumentID(id);return new PendingIDSpecificOperation(documentID,this)}async upsert(value,options={}){const ditto=this.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>{var _a;const writeStrategy=(_a=options.writeStrategy)!==null&&_a!==void 0?_a:"merge";const documentValueJSON=desugarJSObject(value,true);const documentValueCBOR=CBOR.encode(documentValueJSON);const idCBOR=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionInsertValue(dittoHandle.deref(),this.name,documentValueCBOR,writeStrategy,undefined)));return new DocumentID(idCBOR,true)}))}async newAttachment(pathOrData,metadata={}){const ditto=this.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>{const{id:id,len:len,handle:handle}=await(async()=>{if(typeof pathOrData==="string"){{throw new Error(`Can't create attachment from file when running in the browser. Please pass the raw data (as a Uint8Array) instead.`)}}if(pathOrData instanceof Uint8Array){return await dittoNewAttachmentFromBytes(dittoHandle.deref(),pathOrData)}throw new Error(`Can't create new attachment, only file path as string or raw data as Uint8Array are supported, but got: ${typeof pathOrData}, ${pathOrData}`)})();const attachmentTokenJSON={_id:id,_len:len,_meta:{...metadata}};attachmentTokenJSON[DittoCRDTTypeKey]=DittoCRDTType.attachment;const attachmentToken=new AttachmentToken(attachmentTokenJSON);const attachment=new Attachment(ditto,attachmentToken);return Bridge.attachment.bridge(handle,(()=>attachment))}))}fetchAttachment(token,eventHandler){if(token==null||!(token instanceof AttachmentToken)){throw new Error(`Invalid attachment token: ${token}`)}const ditto=this.store.ditto;return ditto.deferClose((()=>ditto.attachmentFetcherManager.startAttachmentFetcher(token,eventHandler)))}constructor(name,store){this.name=name;this.store=store}findByIDCBOR(idCBOR){const documentID=new DocumentID(idCBOR,true,true);return new PendingIDSpecificOperation(documentID,this)}}const ERROR_CODES={internal:"An unexpected internal error occured. Please get in touch with Ditto customer service to report this incident.","internal/unknown-error":"An unexpected internal error occured. Please get in touch with Ditto customer service to report this incident.","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.","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."};const DEFAULT_STATUS_CODE_MAPPING={JsFloatingStoreOperation:["internal","Internal inconsistency, an outstanding store operation was not awaited."],DqlQueryCompilation:["query/invalid"],DqlInvalidQueryArgs:["query/arguments-invalid"],DqlUnsupported:["query/unsupported"],StoreQuery:["query/execution"],StoreDocumentNotFound:["store/document-not-found"],StoreDatabase:["store/backend"],Crdt:["store/crdt"],default:["internal/unknown-error"]};class DittoError extends Error{constructor(code,message,context={}){if(ERROR_CODES[code]==null){throw new DittoError("internal",`Invalid error code: ${code}`)}super(`<${code}> ${message||ERROR_CODES[code]}`);this.code="internal";this.code=code;this.context=Object.freeze({...context})}static fromFFIError(ffiError,code,messageOverride,context){const message=messageOverride||ffiError.message;const errorContext={coreError:ffiError.code,coreErrorMessage:ffiError.message,...context};return new DittoError(code,message,errorContext)}}function mapFFIErrors(closure,statusCodeMapping,context){try{return closure()}catch(error){if(error instanceof DittoFFIError){throw translateFFIError(error,statusCodeMapping,context)}throw error}}async function mapFFIErrorsAsync(closure,statusCodeMapping,context){try{return await closure()}catch(error){if(error instanceof DittoFFIError){throw translateFFIError(error,statusCodeMapping,context)}throw error}}const translateFFIError=(ffiError,customStatusCodeMapping,context)=>{var _a;const statusCode=ffiError.code.toString();let code,message;if(customStatusCodeMapping!=null&&customStatusCodeMapping[statusCode]!=null){[code,message]=customStatusCodeMapping[statusCode]}else{[code,message]=(_a=DEFAULT_STATUS_CODE_MAPPING[statusCode])!==null&&_a!==void 0?_a:DEFAULT_STATUS_CODE_MAPPING.default}return DittoError.fromFFIError(ffiError,code,message,context)};class QueryResult{mutatedDocumentIDs(){const responseHandle=Bridge.dqlResponse.handleFor(this);const affectedCBORIDs=dqlMutatedDocumentIDs(responseHandle.deref());return affectedCBORIDs.map((id=>new DocumentID(id,true)))}constructor(responsePointer){if(responsePointer==null){throw new Error("Internal inconsistency, failed to initialize query result without a response pointer")}const results=dqlResponseResults(responsePointer);this.items=results.map((r=>Bridge.dqlResult.bridge(r)))}}class StoreObserver{get isCancelled(){return this._isCancelled}cancel(){if(this._isCancelled)return;this._isCancelled=true;this.ditto.store.unregisterObserver(this)}constructor(ditto,query,queryArguments,observationHandler){this._isCancelled=false;this.queryString=query;this.queryArguments=queryArguments?Object.freeze({...queryArguments}):undefined;this.ditto=ditto;let queryArgumentsCBOR=null;if(queryArguments!=null){try{queryArgumentsCBOR=CBOR.encode(queryArguments,documentIDReplacer)}catch(error){throw new DittoError("query/arguments-invalid")}}let storeObserverID;const dittoHandle=Bridge.ditto.handleFor(ditto);this.ditto.deferClose((()=>{const weakThis=new WeakRef(this);function wrappedObservationHandler(cCBParams){const strongThis=weakThis.deref();if(strongThis==null){Logger.debug(`Ignoring change event received by store observer ${storeObserverID} after it was cancelled`);return}const response=Bridge.dqlResponse.bridge(cCBParams.query_result,(()=>new QueryResult(cCBParams.query_result)));Logger.debug(`Invoking user event handler with new event for store observer ${storeObserverID}`);observationHandler(response,(()=>{strongThis.signalNext()}))}const errorContext={query:query,queryArguments:queryArguments};mapFFIErrors((()=>{storeObserverID=tryExperimentalRegisterChangeObserver(dittoHandle.deref(),query,queryArgumentsCBOR,wrappedObservationHandler)}),undefined,errorContext)}));if(storeObserverID==null){throw new DittoError("internal","Internal inconsistency, store observer ID is undefined after registering")}this.liveQueryID=storeObserverID}signalNext(){const ditto=this.ditto;if(!ditto||ditto.isClosed)return;const dittoHandle=Bridge.ditto.handleFor(ditto);const dittoPointer=dittoHandle.derefOrNull();if(!dittoPointer)return;if(this.liveQueryID==null){throw new Error("live query ID is null while signaling ready for next event")}return ditto.deferCloseAsync((async()=>{Logger.debug(`Signaling availability for live query ${this.liveQueryID}`);await liveQuerySignalAvailableNext(dittoPointer,this.liveQueryID)}))}}class CollectionsEvent{static initial(collections){return new CollectionsEvent({isInitial:true,collections:collections,oldCollections:[],insertions:[],deletions:[],updates:[],moves:[]})}constructor(params){this.isInitial=params.isInitial;this.collections=params.collections;this.oldCollections=params.oldCollections;this.insertions=params.insertions;this.deletions=params.deletions;this.updates=params.updates;this.moves=params.moves}}class PendingCollectionsOperation{sort(propertyPath,direction="ascending"){this.pendingCursorOperation.sort(propertyPath,direction);return this}offset(offset){this.pendingCursorOperation.offset(offset);return this}limit(limit){this.pendingCursorOperation.limit(limit);return this}subscribe(){return this.pendingCursorOperation.subscribe()}observeLocal(handler){return this._observe(handler,false)}observeLocalWithNextSignal(handler){return this._observe(handler,true)}async exec(){const documents=await this.pendingCursorOperation.exec();return collectionsFromDocuments(documents,this.store)}constructor(store){this.store=store;this.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",store))}then(onfulfilled,onrejected){return this.exec().then(onfulfilled,onrejected)}_observe(handler,waitForNextSignal){const weakStore=new WeakRef(this.store);const collectionsObservationHandler=function(documents,event,nextSignal){const strongStore=weakStore.deref();if(!strongStore){return}const collections=collectionsFromDocuments(documents,strongStore);let collEvent;if(event.isInitial===true){collEvent=CollectionsEvent.initial(collections)}else{const oldCollections=collectionsFromDocuments(event.oldDocuments,strongStore);collEvent=new CollectionsEvent({isInitial:false,collections:collections,oldCollections:oldCollections,insertions:event.insertions,deletions:event.deletions,updates:event.updates,moves:event.moves})}if(waitForNextSignal){handler(collEvent,nextSignal)}else{handler(collEvent)}};return this.pendingCursorOperation._observe(collectionsObservationHandler,waitForNextSignal)}}function collectionsFromDocuments(documents,store){const collections=[];for(const document of documents){const collectionName=document.at("name").value;if(collectionName!==undefined&&typeof collectionName==="string"){collections.push(new Collection(collectionName,store))}}return collections}class WriteTransactionPendingCursorOperation extends BasePendingCursorOperation{sort(propertyPath,direction="ascending"){return super.sort(propertyPath,direction)}offset(offset){return super.offset(offset)}limit(limit){return super.limit(limit)}async remove(){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>{const query=this.query;const transaction=this.collection.writeTransaction;const documentsX=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>collectionRemoveQueryStr(dittoHandle.deref(),this.collection.name,transaction.writeTransactionPointer,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)));const results=documentsX.map((idCBOR=>new DocumentID(idCBOR,true)));results.forEach((documentId=>{transaction.addResult("removed",documentId,this.collection.name)}));return results}))}async evict(){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>{const query=this.query;const transaction=this.collection.writeTransaction;const documentsX=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>collectionEvictQueryStr(dittoHandle.deref(),this.collection.name,transaction.writeTransactionPointer,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)));const results=documentsX.map((idCBOR=>new DocumentID(idCBOR,true)));results.forEach((documentId=>{transaction.addResult("evicted",documentId,this.collection.name)}));return results}))}async update(closure){const transaction=this.collection.writeTransaction;const results=await super.updateWithTransaction(closure,transaction.writeTransactionPointer);results.keys().forEach((documentId=>{transaction.addResult("updated",documentId,this.collection.name)}));return results}constructor(query,queryArgs,collection){super(query,queryArgs,collection)}}class WriteTransactionPendingIDSpecificOperation extends BasePendingIDSpecificOperation{async remove(){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>{const transaction=this.collection.writeTransaction;const result=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>collectionRemove(dittoHandle.deref(),this.collection.name,transaction.writeTransactionPointer,this.documentIDCBOR)));transaction.addResult("removed",this.documentID,this.collection.name);return result}))}async evict(){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>{const transaction=this.collection.writeTransaction;const result=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionEvict(dittoHandle.deref(),this.collection.name,transaction.writeTransactionPointer,this.documentIDCBOR)));transaction.addResult("evicted",this.documentID,this.collection.name);return result}))}async update(closure){const ditto=this.collection.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>{const transaction=this.collection.writeTransaction;const readTransactionX=await readTransaction(dittoHandle.deref());const documentX=await collectionGet(dittoHandle.deref(),this.collection.name,this.documentIDCBOR,readTransactionX);readTransactionFree(readTransactionX);if(!documentX)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const mutableDocument=Bridge.mutableDocument.bridge(documentX,(()=>new MutableDocument));closure(mutableDocument);Bridge.mutableDocument.unregister(mutableDocument);await collectionUpdate(dittoHandle.deref(),this.collection.name,transaction.writeTransactionPointer,documentX);transaction.addResult("updated",this.documentID,this.collection.name);return mutableDocument["@ditto.updateResults"].slice()}))}constructor(documentID,collection){super(documentID,collection)}}class WriteTransactionCollection{find(query,queryArgs){return new WriteTransactionPendingCursorOperation(query,queryArgs!==null&&queryArgs!==void 0?queryArgs:null,this)}findAll(){return this.find("true")}findByID(id){const documentID=id instanceof DocumentID?id:new DocumentID(id);return new WriteTransactionPendingIDSpecificOperation(documentID,this)}async upsert(value,options={}){const ditto=this.store.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>{var _a;const writeStrategy=(_a=options.writeStrategy)!==null&&_a!==void 0?_a:"merge";const documentValueJSON=desugarJSObject(value,true);const documentValueCBOR=CBOR.encode(documentValueJSON);const idCBOR=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionInsertValue(dittoHandle.deref(),this.name,documentValueCBOR,writeStrategy,this.writeTransaction.writeTransactionPointer)));const insertedDocumentId=new DocumentID(idCBOR,true);this.writeTransaction.addResult("inserted",insertedDocumentId,this.name);return new DocumentID(idCBOR,true)}))}findByIDCBOR(idCBOR){const documentID=new DocumentID(idCBOR,true,true);return new WriteTransactionPendingIDSpecificOperation(documentID,this)}constructor(name,store,writeTransaction){this.name=name;this.store=store;this.writeTransaction=writeTransaction}}class WriteTransaction{static async init(ditto){return ditto.deferCloseAsync((async()=>{const dittoHandle=Bridge.ditto.handleFor(ditto);const writeTransactionPointer=await writeTransaction(dittoHandle.deref());return new WriteTransaction(ditto,writeTransactionPointer)}))}scoped(toCollectionNamed){if(typeof toCollectionNamed!=="string"){throw new Error("Collection name must be a string")}return new WriteTransactionCollection(toCollectionNamed,this.ditto.store,this)}async commit(){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>writeTransactionCommit(dittoHandle.deref(),this.writeTransactionPointer)))}async rollback(){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>writeTransactionRollback(dittoHandle.deref(),this.writeTransactionPointer)))}addResult(type,docID,collectionName){this.results.push({type:type,docID:docID,collectionName:collectionName})}constructor(ditto,cTransaction){this.writeTransactionPointer=cTransaction;this.ditto=ditto;this.results=[]}}class Store{registerObserver(query,observationHandler,queryArguments){const changeHandlerWithSignalNext=(queryResult,signalNext)=>{try{observationHandler(queryResult)}finally{signalNext()}};return this.registerObserverWithSignalNext(query,changeHandlerWithSignalNext,queryArguments)}registerObserverWithSignalNext(query,observationHandler,queryArguments){if(typeof query!=="string"){throw new DittoError("query/invalid",`Expected parameter 'query' to be of type 'string', found: ${typeof query}`)}const storeObserver=new StoreObserver(this.ditto,query,queryArguments!==null&&queryArguments!==void 0?queryArguments:null,observationHandler);this.observers=Object.freeze([...this.observers,storeObserver]);const dittoHandle=Bridge.ditto.handleFor(this.ditto);this.ditto.deferCloseAsync((async()=>new Promise((resolve=>{step((async()=>{try{await mapFFIErrorsAsync((async()=>await liveQueryStart(dittoHandle.deref(),storeObserver.liveQueryID)))}catch(error){Logger.error(`Failed to start live query: ${error.message}`)}resolve()}))}))));return storeObserver}collection(name){return new Collection(name,this)}collections(){return new PendingCollectionsOperation(this)}collectionNames(){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferClose((()=>mapFFIErrors((()=>dittoGetCollectionNames(dittoHandle.deref())))))}async execute(query,queryArguments){if(typeof query!=="string"){throw new DittoError("query/invalid",`Expected parameter 'query' to be of type 'string', found: ${typeof query}`)}const dittoHandle=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{const writeTransaction=null;let queryArgumentsCBOR=null;if(queryArguments!=null){try{queryArgumentsCBOR=CBOR.encode(queryArguments,documentIDReplacer)}catch(error){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${error.message}`)}}const errorContext={query:query,queryArguments:queryArguments};const responsePointer=await mapFFIErrorsAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((()=>tryExperimentalExecQueryStr(dittoHandle.deref(),writeTransaction,query,queryArgumentsCBOR)))),undefined,errorContext);return Bridge.dqlResponse.bridge(responsePointer,(()=>new QueryResult(responsePointer)))}))}async write(callback){return this.ditto.deferCloseAsync((async()=>{const transaction=await WriteTransaction.init(this.ditto);try{await callback(transaction)}catch(error){await transaction.rollback();Logger.warning(`Transaction rolled back due to an error: ${error===null||error===void 0?void 0:error.message}`);throw error}await transaction.commit();return transaction.results}))}constructor(ditto){this.observers=Object.freeze([]);this.ditto=ditto}async registerObserverWebhook(query,url,queryArguments){let queryArgumentsCBOR=null;if(queryArguments!=null){try{queryArgumentsCBOR=CBOR.encode(queryArguments,documentIDReplacer)}catch(error){throw new DittoError("query/arguments-invalid",`Invalid query arguments: ${error.message}`)}}const errorContext={query:query,queryArguments:queryArguments};const dittoHandle=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{const webhookIDCBOR=await mapFFIErrorsAsync((async()=>await tryExperimentalWebhookRegisterDqlLiveQuery(dittoHandle.deref(),query,queryArgumentsCBOR,url)),undefined,errorContext);return new DocumentID(webhookIDCBOR,true)}))}unregisterObserver(storeObserver){if(storeObserver.ditto!==this.ditto){throw new DittoError("internal",`Internal inconsistency, can't remove store observer that does not belong to this store`)}if(!storeObserver.isCancelled){throw new DittoError("internal","Internal inconsistency, can't remove store observer that has not been cancelled")}const indexToDelete=this.observers.findIndex((observer=>observer===storeObserver));if(indexToDelete===-1){return false}const newObservers=[...this.observers];newObservers.splice(indexToDelete,1);this.observers=Object.freeze(newObservers);const dittoHandle=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{mapFFIErrors((()=>liveQueryStop(dittoHandle.deref(),storeObserver.liveQueryID)))}));return true}close(){for(const observer of this.observers){observer.cancel()}}async registerLiveQueryWebhook(collectionName,query,url){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferCloseAsync((async()=>{const validatedQuery=validateQuery(query);const idCBOR=await liveQueryWebhookRegister(dittoHandle.deref(),collectionName,validatedQuery,[],0,0,url);return new DocumentID(idCBOR,true)}))}}function addressToString(address){return`${address.siteId}-${address.pubkey}`}class Presence{get graph(){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferClose((()=>{const graphJSONString=dittoPresenceV3(dittoHandle.deref());return JSON.parse(graphJSONString)}))}observe(didChangeHandler){const observerToken=this.observerManager.addObserver(didChangeHandler);const observer=new Observer(this.observerManager,observerToken,{stopsWhenFinalized:true});didChangeHandler(this.graph);return observer}constructor(ditto){this.ditto=ditto;this.observerManager=new ObserverManager("PresenceObservation",{keepAlive:ditto.keepAlive,register:callback=>{const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);ditto.deferClose((()=>{dittoRegisterPresenceV3Callback(dittoHandle.deref(),callback)}))},unregister:()=>{const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);ditto.deferClose((()=>{dittoClearPresenceV3Callback(dittoHandle.deref())}))},process:presenceGraphJSONString=>{const presenceGraph=JSON.parse(presenceGraphJSONString);return[presenceGraph]}})}close(){this.observerManager.close()}}class LiveQueryManager{constructor(ditto,keepAlive){this.finalizationRegistry=new FinalizationRegistry(this.finalize);this.ditto=ditto;this.keepAlive=keepAlive;this.liveQueriesByID={}}startLiveQuery(liveQuery){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);ditto.deferCloseAsync((async()=>{const liveQueryID=liveQuery.liveQueryID;if(!liveQueryID){throw new Error("Internal inconsistency, tried to add a live query that doesn't have a live query ID (probably stopped).")}const existingLiveQuery=this.liveQueriesByID[liveQueryID];if(existingLiveQuery){throw new Error("Internal inconsistency, tried to add a live query with an ID that has already been added.")}const weakLiveQuery=new WeakRef(liveQuery);this.liveQueriesByID[liveQueryID]=weakLiveQuery;this.finalizationRegistry.register(liveQuery,liveQueryID,this.finalize);liveQuery.liveQueryManager=this;ditto.keepAlive.retain(`LiveQuery.${liveQueryID}`);return new Promise(((resolve,reject)=>{step((async()=>{await liveQueryStart(dittoHandle.deref(),liveQueryID);resolve()}))}))}))}stopLiveQuery(liveQuery){this.finalizationRegistry.unregister(liveQuery);const liveQueryID=liveQuery.liveQueryID;if(!liveQueryID){throw new Error("Internal inconsistency, tried to remove a live query that doesn't have a live query ID (probably stopped).")}liveQuery.liveQueryManager=null;this.stopLiveQueryWithID(liveQueryID)}close(){for(const liveQueryID in this.liveQueriesByID){const weakLiveQuery=this.liveQueriesByID[liveQueryID];const liveQuery=weakLiveQuery.deref();if(liveQuery){this.stopLiveQuery(liveQuery)}}}stopLiveQueryWithID(liveQueryID){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);ditto.deferClose((()=>{liveQueryStop(dittoHandle.deref(),liveQueryID);this.keepAlive.release(`LiveQuery.${liveQueryID}`);delete this.liveQueriesByID[liveQueryID]}))}finalize(liveQueryID){this.stopLiveQueryWithID(liveQueryID)}}class PresenceManager{constructor(ditto){this.ditto=ditto;this.isClosed=false;this.isRegistered=false;this.currentRemotePeers=[];this.callbacksByPresenceToken={}}addObserver(callback){if(this.isClosed){throw new Error(`Internal inconsistency, can't add presence observer, observer mananger close()-ed.`)}this.registerIfNeeded();const token=generateEphemeralToken();this.callbacksByPresenceToken[token]=callback;this.ditto.keepAlive.retain(`PresenceObservation.${token}`);callback(this.currentRemotePeers);return token}removeObserver(token){const callback=this.callbacksByPresenceToken[token];if(typeof callback==="undefined"){throw new Error(`Can't remove presence observer, token '${token}' has never been registered before.`)}if(callback===null){return}if(typeof this.callbacksByPresenceToken[token]!="undefined"){this.ditto.keepAlive.release(`PresenceObservation.${token}`);this.callbacksByPresenceToken[token]=null;this.unregisterIfNeeded()}}hasObserver(token){return typeof this.callbacksByPresenceToken[token]!="undefined"}close(){this.isClosed=true;for(const token in this.callbacksByPresenceToken){this.removeObserver(token)}}hasObservers(){return Object.keys(this.callbacksByPresenceToken).length>0}registerIfNeeded(){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(this.ditto);ditto.deferClose((()=>{const needsToRegister=!this.isRegistered;if(needsToRegister){this.isRegistered=true;const remotePeersJSONString=dittoPresenceV1(dittoHandle.deref());this.currentRemotePeers=this.decode(remotePeersJSONString).sort(this.compareRemotePeers);dittoRegisterPresenceV1Callback(dittoHandle.deref(),this.handlePresenceV1Callback.bind(this))}}))}unregisterIfNeeded(){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);ditto.deferClose((()=>{const needsToUnregister=!this.hasObservers()&&this.isRegistered;if(needsToUnregister){this.isRegistered=false;dittoClearPresenceCallback(dittoHandle.deref());this.currentRemotePeers=[]}}))}handlePresenceV1Callback(remotePeersJSONString){const remotePeers=this.decode(remotePeersJSONString).sort(this.compareRemotePeers);this.currentRemotePeers=remotePeers;this.notify()}notify(){if(this.isClosed){return}for(const token in this.callbacksByPresenceToken){const callback=this.callbacksByPresenceToken[token];if(callback)callback(this.currentRemotePeers)}}decode(remotePeersJSONString){const remotePeersJSON=JSON.parse(remotePeersJSONString);return remotePeersJSON.map((remotePeerJSON=>{var _a,_b;return{networkID:remotePeerJSON["network_id"],deviceName:remotePeerJSON["device_name"],rssi:(_a=remotePeerJSON["rssi"])!==null&&_a!==void 0?_a:undefined,approximateDistanceInMeters:(_b=remotePeerJSON["approximate_distance_in_meters"])!==null&&_b!==void 0?_b:undefined,connections:remotePeerJSON["connections"]}}))}compareRemotePeers(left,right){if(left.connections.length===0&&right.connections.length>0)return+1;if(left.connections.length>0&&right.connections.length===0)return-1;if(left.deviceName<right.deviceName)return-1;if(left.deviceName>right.deviceName)return+1;return 0}}class TransportConditionsManager extends ObserverManager{constructor(ditto){const keepAlive=ditto.keepAlive;super("TransportConditionsObservation",{keepAlive:keepAlive});this.ditto=ditto}register(callback){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferClose((()=>dittoRegisterTransportConditionChangedCallback(dittoHandle.deref(),callback)))}unregister(){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferClose((()=>dittoRegisterTransportConditionChangedCallback(dittoHandle.deref(),null)))}process(conditionSource,transportCondition){let apiConditionSource;switch(conditionSource){case"Bluetooth":apiConditionSource="BLE";break;case"Tcp":apiConditionSource="TCP";break;case"Awdl":apiConditionSource="AWDL";break;case"Mdns":apiConditionSource="MDNS";break}let apiTransportCondition;switch(transportCondition){case"Unknown":apiTransportCondition="Unknown";break;case"Ok":apiTransportCondition="OK";break;case"GenericFailure":apiTransportCondition="GenericFailure";break;case"AppInBackground":apiTransportCondition="AppInBackground";break;case"MdnsFailure":apiTransportCondition="MDNSFailure";break;case"TcpListenFailure":apiTransportCondition="TCPListenFailure";break;case"NoBleCentralPermission":apiTransportCondition="NoBLECentralPermission";break;case"NoBlePeripheralPermission":apiTransportCondition="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":apiTransportCondition="CannotEstablishConnection";break;case"BleDisabled":apiTransportCondition="BLEDisabled";break;case"NoBleHardware":apiTransportCondition="NoBLEHardware";break;case"WifiDisabled":apiTransportCondition="WiFiDisabled";break;case"TemporarilyUnavailable":apiTransportCondition="TemporarilyUnavailable";break}return[apiTransportCondition,apiConditionSource]}}class SyncSubscription{get isCancelled(){return this._isCancelled}cancel(){if(this._isCancelled)return;this._isCancelled=true;this.ditto.sync.unregisterSubscription(this)}constructor(ditto,query,queryArguments,queryArgumentsCBOR){this._isCancelled=false;if(queryArguments==null!==(queryArgumentsCBOR==null)){throw new DittoError("internal","Internal inconsistency, query arguments and query arguments CBOR must be both null or both non-null",{queryArguments:queryArguments,queryArgumentsCBOR:queryArgumentsCBOR})}this.ditto=ditto;this.queryString=query;this.queryArguments=queryArguments?Object.freeze({...queryArguments}):undefined;this.queryArgumentsCBOR=queryArgumentsCBOR}}class Sync{registerSubscription(query,queryArguments){if(typeof query!=="string"){throw new DittoError("query/invalid",`Expected parameter 'query' to be of type 'string', found: ${typeof query}`)}let queryArgumentsCBOR=null;if(queryArguments!=null){try{queryArgumentsCBOR=CBOR.encode(queryArguments,documentIDReplacer)}catch(error){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${error.message}`)}}const errorContext={query:query,queryArguments:queryArguments};const dittoHandle=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{mapFFIErrors((()=>tryExperimentalAddDQLSubscription(dittoHandle.deref(),query,queryArgumentsCBOR)),undefined,errorContext)}));const subscription=new SyncSubscription(this.ditto,query,queryArguments||null,queryArgumentsCBOR);this.subscriptions=Object.freeze([...this.subscriptions,subscription]);return subscription}get parameters(){return this.state.underlyingSyncParameters}constructor(ditto){this.subscriptions=Object.freeze([]);this.bluetoothLETransportPointer=null;this.awdlTransportPointer=null;this.lanTransportPointer=null;this.mdnsClientTransportPointer=null;this.mdnsServerAdvertiserPointer=null;const identity=ditto.identity;const transportConfig=new TransportConfig;const parameters={identity:identity,transportConfig:transportConfig,ditto:ditto,isWebValid:false,isX509Valid:false,isSyncActive:false};this.ditto=ditto;this.state=stateFrom(parameters);transportsInit()}unregisterSubscription(syncSubscription){if(syncSubscription.ditto!==this.ditto){throw new DittoError("internal",`Can't remove replication subscription that does not belong to this store`)}if(!syncSubscription.isCancelled){throw new DittoError("internal","Internal inconsistency, can't remove replication subscription that has not been cancelled")}const indexToDelete=this.subscriptions.findIndex((s=>s===syncSubscription));if(indexToDelete===-1){return false}const newSyncSubscriptions=[...this.subscriptions];newSyncSubscriptions.splice(indexToDelete,1);this.subscriptions=Object.freeze(newSyncSubscriptions);const dittoHandle=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{mapFFIErrors((()=>tryExperimentalRemoveDQLSubscription(dittoHandle.deref(),syncSubscription.queryString,syncSubscription.queryArgumentsCBOR)))}));return true}update(parameters){const stateOld=this.state;const stateNew=stateFrom(parameters);this.updatePeerToPeerBluetoothLE(stateOld,stateNew);this.updatePeerToPeerAWDL(stateOld,stateNew);this.updatePeerToPeerLAN(stateOld,stateNew);this.updateListenTCP(stateOld,stateNew);this.updateListenHTTP(stateOld,stateNew);this.updateConnectTCPServers(stateOld,stateNew);this.updateConnectWebsocketURLs(stateOld,stateNew);this.updateGlobal(stateOld,stateNew);this.updateConnectRetryInterval(stateOld,stateNew);this.state=stateNew}close(){if(this.parameters.isSyncActive){throw new Error(`Internal inconsistency, can't close sync object while sync is active, please 'stopSync()' first.`)}for(const subscription of this.subscriptions){subscription.cancel()}}updatePeerToPeerBluetoothLE(stateOld,stateNew){return}updatePeerToPeerAWDL(stateOld,stateNew){return}updatePeerToPeerLAN(stateOld,stateNew){return}updateListenTCP(stateOld,stateNew){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);ditto.deferClose((()=>{const tcpOld=stateOld.effectiveTransportConfig.listen.tcp;const tcpNew=stateNew.effectiveTransportConfig.listen.tcp;if(TransportConfig.areListenTCPsEqual(tcpNew,tcpOld))return;if(tcpOld.isEnabled)dittoStopTCPServer(dittoHandle.deref());if(tcpNew.isEnabled)dittoStartTCPServer(dittoHandle.deref(),`${tcpNew.interfaceIP}:${tcpNew.port}`)}))}updateListenHTTP(stateOld,stateNew){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);ditto.deferClose((()=>{const httpOld=stateOld.effectiveTransportConfig.listen.http;const httpNew=stateNew.effectiveTransportConfig.listen.http;if(TransportConfig.areListenHTTPsEqual(httpOld,httpNew))return;if(httpOld.isEnabled)dittoStopHTTPServer(dittoHandle.deref());if(httpNew.isEnabled){dittoStartHTTPServer(dittoHandle.deref(),`${httpNew.interfaceIP}:${httpNew.port}`,httpNew.staticContentPath||null,httpNew.websocketSync?"Enabled":"Disabled",httpNew.tlsCertificatePath||null,httpNew.tlsKeyPath||null)}}))}updateConnectTCPServers(stateOld,stateNew){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);ditto.deferClose((()=>{const tcpServers=stateNew.effectiveTransportConfig.connect.tcpServers;dittoSetStaticTCPClients(dittoHandle.deref(),tcpServers)}))}updateConnectWebsocketURLs(stateOld,stateNew){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);ditto.deferClose((()=>{const websocketURLs=stateNew.effectiveTransportConfig.connect.websocketURLs;const routingHint=stateNew.effectiveTransportConfig.global.routingHint;dittoSetStaticWebsocketClients(dittoHandle.deref(),websocketURLs,routingHint)}))}updateGlobal(stateOld,stateNew){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);ditto.deferClose((()=>{if(stateOld.effectiveTransportConfig.global.syncGroup!==stateNew.effectiveTransportConfig.global.syncGroup){dittoSetSyncGroup(dittoHandle.deref(),stateNew.effectiveTransportConfig.global.syncGroup)}}))}updateConnectRetryInterval(stateOld,stateNew){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);ditto.deferClose((()=>{dittoSetConnectRetryInterval(dittoHandle.deref(),stateNew.effectiveTransportConfig.connect.retryInterval)}))}}function stateFrom(parameters){var _a,_b;const identity=parameters.identity;const isSyncActive=parameters.isSyncActive;const isX509Valid=parameters.isX509Valid;const isWebValid=parameters.isWebValid;let appID;let customDittoCloudURL;let isDittoCloudSyncEnabled=false;if(identity.type==="onlinePlayground"||identity.type==="onlineWithAuthentication"){appID=identity.appID;customDittoCloudURL=(_a=identity.customDittoCloudURL)!==null&&_a!==void 0?_a:null;isDittoCloudSyncEnabled=(_b=identity.enableDittoCloudSync)!==null&&_b!==void 0?_b:true}validateEnabledTransportsAvailable(parameters.ditto,parameters.transportConfig);const transportConfig=parameters.transportConfig.copy();if(!isSyncActive||!isX509Valid){transportConfig.peerToPeer.bluetoothLE.isEnabled=false;transportConfig.peerToPeer.awdl.isEnabled=false;transportConfig.peerToPeer.lan.isEnabled=false;transportConfig.listen.tcp.isEnabled=false;transportConfig.connect.tcpServers=[]}if(!isSyncActive||!isWebValid){transportConfig.connect.websocketURLs=[]}if(!isSyncActive){transportConfig.listen.http.isEnabled=false}if(isSyncActive&&isWebValid&&isDittoCloudSyncEnabled){const dittoCloudURL=customDittoCloudURL!==null&&customDittoCloudURL!==void 0?customDittoCloudURL:defaultDittoCloudURL(appID);transportConfig.connect.websocketURLs.push(dittoCloudURL)}return{underlyingSyncParameters:parameters,effectiveTransportConfig:transportConfig.freeze()}}function validateEnabledTransportsAvailable(ditto,transportConfig){const dittoHandle=Bridge.ditto.handleFor(ditto);return ditto.deferClose((()=>{const unavailableButEnabledP2PTransports=[];const isBLEAvailable=transportsBLEIsAvailable(dittoHandle.deref());const isAWDLAvailable=transportsAWDLIsAvailable(dittoHandle.deref());const isLANAvailable=transportsLANIsAvailable(dittoHandle.deref());if(transportConfig.peerToPeer.bluetoothLE.isEnabled&&!isBLEAvailable){unavailableButEnabledP2PTransports.push("BluetoothLE")}if(transportConfig.peerToPeer.awdl.isEnabled&&!isAWDLAvailable){unavailableButEnabledP2PTransports.push("AWDL")}if(transportConfig.peerToPeer.lan.isEnabled&&!isLANAvailable){unavailableButEnabledP2PTransports.push("LAN")}if(unavailableButEnabledP2PTransports.length>0){throw new Error(`The following P2P transports are enabled in the transport config but are not supported in the current environment: ${unavailableButEnabledP2PTransports.join(", ")}`)}if(transportConfig.connect.tcpServers.length>0&&isWebBuild){throw new Error(`The transport config contains TCP servers, but this transport is not supported in web environments`)}if(transportConfig.listen.http.isEnabled&&isWebBuild){throw new Error(`The transport config contains an HTTP listener, which is not supported in web environments`)}if(transportConfig.listen.tcp.isEnabled&&isWebBuild){throw new Error(`The transport config contains a TCP listener, which is not supported in web environments`)}}))}class SubscriptionManager{constructor(ditto){this.ditto=ditto;this.subscriptions={};this.finalizationRegistry=new FinalizationRegistry(this.removeWithContextInfo.bind(this))}add(subscription){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);const contextInfo=subscription.contextInfo;ditto.deferClose((async()=>{this.subscriptions[contextInfo.id]=new WeakRef(subscription);this.finalizationRegistry.register(subscription,subscription.contextInfo,subscription);addSubscription(dittoHandle.deref(),contextInfo.collectionName,contextInfo.query,contextInfo.queryArgsCBOR,contextInfo.orderBys,contextInfo.limit,contextInfo.offset)}))}remove(subscription){if(this.subscriptions[subscription.contextInfo.id]==null){throw new Error(`Internal inconsistency, tried to remove a subscription that is not tracked: ${subscription.contextInfo.id}`)}this.finalizationRegistry.unregister(subscription);this.removeWithContextInfo(subscription.contextInfo)}close(){this.ditto.deferClose((async()=>{for(const subscriptionID in this.subscriptions){const subscription=this.subscriptions[subscriptionID].deref();if(subscription!=null){this.remove(subscription)}}}))}removeWithContextInfo(contextInfo){const ditto=this.ditto;const dittoHandle=Bridge.ditto.handleFor(ditto);ditto.deferClose((()=>{delete this.subscriptions[contextInfo.id];removeSubscription(dittoHandle.deref(),contextInfo.collectionName,contextInfo.query,contextInfo.queryArgsCBOR,contextInfo.orderBys,contextInfo.limit,contextInfo.offset)}))}}class AttachmentFetcher{stop(){step((async()=>{await this.manager.stopAttachmentFetcher(this);if(this.rejectPendingFetch!=null){this.rejectPendingFetch()}}))}then(onfulfilled,onrejected){return this.attachment.then(onfulfilled,onrejected)}constructor(ditto,token,manager,eventHandler){this.cancelTokenPromise=null;this.rejectPendingFetch=null;this.ditto=ditto;this.token=token;this.manager=manager;this.id=generateEphemeralToken();const eventHandlerOrNoOp=eventHandler||function(){};const dittoHandle=Bridge.ditto.handleFor(ditto);this.attachment=new Promise(((resolve,reject)=>{const onComplete=attachmentHandlePointer=>{const attachment=new Attachment(this.ditto,this.token);Bridge.attachment.bridge(attachmentHandlePointer,(()=>attachment));eventHandlerOrNoOp({type:"Completed",attachment:attachment});this.rejectPendingFetch=null;resolve(attachment)};const onProgress=(downloaded,toDownload)=>{eventHandlerOrNoOp({type:"Progress",totalBytes:toDownload,downloadedBytes:downloaded})};const onDelete=()=>{eventHandlerOrNoOp({type:"Deleted"});this.rejectPendingFetch=null;resolve(null)};const onError=()=>{};this.rejectPendingFetch=()=>{reject(new Error("Attachment fetch was canceled"))};this.cancelTokenPromise=dittoResolveAttachment(dittoHandle.deref(),token.id,{onComplete:onComplete,onProgress:onProgress,onDelete:onDelete},onError)}))}}class AttachmentFetcherManager{constructor(ditto){this.contextInfoByID={};this.finalizationRegistry=new FinalizationRegistry(this.stopWithContextInfo);this.ditto=ditto}startAttachmentFetcher(token,eventHandler){return this.ditto.deferClose((()=>{const attachmentFetcher=new AttachmentFetcher(this.ditto,token,this,eventHandler);const contextInfo={id:attachmentFetcher.id,attachmentTokenID:token.id,cancelTokenPromise:attachmentFetcher.cancelTokenPromise,attachmentFetcher:new WeakRef(attachmentFetcher)};this.finalizationRegistry.register(attachmentFetcher,contextInfo,attachmentFetcher);this.contextInfoByID[attachmentFetcher.id]=contextInfo;const resetCancelToken=()=>{if(this.contextInfoByID[attachmentFetcher.id]!=null){this.contextInfoByID[attachmentFetcher.id].cancelTokenPromise=null}};attachmentFetcher.attachment.then((value=>{resetCancelToken();return value}),(reason=>{resetCancelToken();return reason}));this.ditto.keepAlive.retain(`AttachmentFetcher.${attachmentFetcher.id})`);return attachmentFetcher}))}async stopAttachmentFetcher(attachmentFetcher){this.finalizationRegistry.unregister(attachmentFetcher);const contextInfo=this.contextInfoByID[attachmentFetcher.id];if(contextInfo==null){throw new Error(`Internal inconsistency: cannot stop attachment fetcher ${attachmentFetcher.id}, which is not registered.`)}await this.stopWithContextInfo(contextInfo)}close(){this.ditto.deferCloseAsync((async()=>{const contextInfos=Object.values(this.contextInfoByID);const stopped=contextInfos.map((async contextInfo=>{const attachmentFetcher=contextInfo.attachmentFetcher.deref();if(attachmentFetcher!=null){await this.stopAttachmentFetcher(attachmentFetcher)}}));await Promise.all(stopped)}))}stopWithContextInfo(contextInfo){const dittoHandle=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{if(this.contextInfoByID[contextInfo.id]==null){throw new Error(`Internal inconsistency: attachment fetcher ${contextInfo.id} not found in active attachment fetchers.`)}delete this.contextInfoByID[contextInfo.id];this.ditto.keepAlive.release(`AttachmentFetcher.${contextInfo.id})`);const cancelToken=await contextInfo.cancelTokenPromise;if(cancelToken){dittoCancelResolveAttachment(dittoHandle.deref(),contextInfo.attachmentTokenID,cancelToken)}}))}}class SmallPeerInfo{get isEnabled(){const dittoHandle=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>dittoSmallPeerInfoGetIsEnabled(dittoHandle.deref())))}set isEnabled(newValue){if(typeof newValue!=="boolean"){throw new TypeError(`Expected boolean, got ${typeof newValue}`)}const dittoHandle=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{dittoSmallPeerInfoSetEnabled(dittoHandle.deref(),newValue)}))}get metadata(){return JSON.parse(this.metadataJSONString)}set metadata(metadata){this.metadataJSONString=JSON.stringify(metadata)}get metadataJSONString(){const dittoHandle=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>dittoSmallPeerInfoGetMetadata(dittoHandle.deref())))}set metadataJSONString(metadata){if(typeof metadata!=="string"){throw new TypeError(`Expected string, got ${typeof metadata}`)}const dittoHandle=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{dittoSmallPeerInfoSetMetadata(dittoHandle.deref(),metadata)}))}async getSyncScope(){const dittoHandle=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>dittoSmallPeerInfoGetSyncScope(dittoHandle.deref())))}async setSyncScope(syncScope){const dittoHandle=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>dittoSmallPeerInfoSetSyncScope(dittoHandle.deref(),syncScope)))}constructor(ditto){this.ditto=ditto}}const DEFAULT_PERSISTENCE_DIRECTORY="ditto";class Ditto{static get VERSION(){return dittoGetSDKSemver()}get sdkVersion(){const dittoHandle=Bridge.ditto.handleFor(this);return this.deferClose((()=>dittoGetSDKVersion(dittoHandle.deref())))}get path(){Logger.warning("⚠️ Deprecation Warning: The 'Ditto.path' property is deprecated. Please update your code to use the new 'Ditto.persistenceDirectory' property instead.");return this.persistenceDirectory}get isActivated(){var _a;return(_a=this._isActivated)!==null&&_a!==void 0?_a:false}get isClosed(){var _a;return(_a=this._isClosed)!==null&&_a!==void 0?_a:false}get isSyncActive(){var _a;return(_a=this._isSyncActive)!==null&&_a!==void 0?_a:false}constructor(identity,persistenceDirectory){this.deferCloseAllowed=true;this.isWebValid=false;this.isX509Valid=false;this._isSyncActive=false;this._isClosed=false;this.pendingOperations=new Set;if(!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(persistenceDirectory);const identityOrDefault=identity!==null&&identity!==void 0?identity:{type:"offlinePlayground",appID:""};const validIdentity=Object.freeze(this.validateIdentity(identityOrDefault));this.identity=Object.freeze(validIdentity);{this.deviceName=navigator.userAgent}this.keepAlive=new KeepAlive;const uninitializedDittoX=uninitializedDittoMake(this.persistenceDirectory);let secondsRemainingUntilAuthenticationExpires=null;const weakThis=new WeakRef(this);const identityConfig=(()=>{var _a,_b,_c;if(validIdentity.type==="offlinePlayground"){return dittoIdentityConfigMakeOfflinePlayground(validIdentity.appID,(_a=validIdentity.siteID)!==null&&_a!==void 0?_a:0)}if(validIdentity.type==="manual"){return dittoIdentityConfigMakeManual(validIdentity.certificate)}if(validIdentity.type==="sharedKey"){return dittoIdentityConfigMakeSharedKey(validIdentity.appID,validIdentity.sharedKey,validIdentity.siteID)}if(validIdentity.type==="onlinePlayground"){const authURL=(_b=validIdentity.customAuthURL)!==null&&_b!==void 0?_b:defaultAuthURL(validIdentity.appID);return dittoIdentityConfigMakeOnlinePlayground(validIdentity.appID,validIdentity.token,authURL)}if(validIdentity.type==="onlineWithAuthentication"){const authURL=(_c=validIdentity.customAuthURL)!==null&&_c!==void 0?_c:defaultAuthURL(validIdentity.appID);return dittoIdentityConfigMakeOnlineWithAuthentication(validIdentity.appID,authURL)}throw new Error(`Can't create Ditto, unsupported identity type: ${validIdentity}`)})();const dittoPointer=dittoMake(uninitializedDittoX,identityConfig);dittoAuthClientSetValidityListener(dittoPointer,(function(...args){const ditto=weakThis.deref();if(ditto==null||ditto.isClosed){Logger.info("Ditto is closed, ignoring auth client validity change")}else{ditto.authClientValidityChanged(...args)}}));const isWebValid=dittoAuthClientIsWebValid(dittoPointer);const isX509Valid=dittoAuthClientIsX509Valid(dittoPointer);const appID=dittoAuthClientGetAppID(dittoPointer);const siteID=dittoAuthClientGetSiteID(dittoPointer);Bridge.ditto.bridge(dittoPointer,this);if(validIdentity.type==="onlineWithAuthentication"){this.auth=new OnlineAuthenticator(this.keepAlive,this,validIdentity.authHandler);const loginProviderX=dittoAuthClientMakeLoginProvider((function(secondsRemaining){const strongThis=weakThis.deref();if(!strongThis){Logger.warning(`Internal inconsistency, LoginProvider callback fired after the corresponding Ditto instance has been deallocated.`);return}if(strongThis.auth){strongThis.auth["@ditto.authenticationExpiring"](secondsRemaining)}else{secondsRemainingUntilAuthenticationExpires=secondsRemaining}}));dittoAuthSetLoginProvider(dittoPointer,loginProviderX)}else if(validIdentity.type==="onlinePlayground"){this.auth=new OnlineAuthenticator(this.keepAlive,this,{authenticationRequired:function(authenticator){},authenticationExpiringSoon:function(authenticator,secondsRemaining){}})}else{this.auth=new NotAvailableAuthenticator(this.keepAlive)}const transportConfig=this.makeDefaultTransportConfig().freeze();this.appID=appID;this.siteID=siteID;this.isX509Valid=isX509Valid;this.isWebValid=isWebValid;this.sync=new Sync(this);this.sync.update({isSyncActive:false,isX509Valid:isX509Valid,isWebValid:isWebValid,identity:validIdentity,ditto:this,transportConfig: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);if(secondsRemainingUntilAuthenticationExpires!=null){this.auth["@ditto.authenticationExpiring"](secondsRemainingUntilAuthenticationExpires)}}static disableDeadlockDetection(){}static hasDeadlockDetection(){return false}static isEnvironmentSupported(){let isIE=false;if(typeof window!=="undefined"&&window.navigator&&window.navigator.userAgent&&window.navigator.appVersion){isIE=window.navigator.userAgent.indexOf("MSIE")!==-1||window.navigator.appVersion.indexOf("Trident/")>-1}let hasRequiredAPIs;try{hasRequiredAPIs=checkAPIs()}catch(error){throw new Error(`Error checking environment support: ${error}`)}return!isIE&&hasRequiredAPIs}static initPersistenceDirectory(path){let validatedPath;if(path==null){validatedPath=DEFAULT_PERSISTENCE_DIRECTORY}else if(path.trim().length===0){throw new Error(`Invalid argument for path parameter: '${path}'`)}else{validatedPath=path}return validatedPath}setOfflineOnlyLicenseToken(licenseToken){{Logger.info("Offline license token are ignored on web builds. Token validation will be skipped.")}{if(IdentityTypesRequiringOfflineLicenseToken.includes(this.identity.type)){const{result:result,errorMessage:errorMessage}=verifyLicense(licenseToken);if(result!=="LicenseOk"){this._isActivated=false;throw new Error(errorMessage)}else{this._isActivated=true}}else{throw new Error("Offline license tokens should only be used for manual, sharedKey or offlinePlayground identities")}}}get transportConfig(){return this.sync.parameters.transportConfig}setTransportConfig(transportConfig){const transportConfigNew=transportConfig.copy().freeze();const identity=this.identity;const isWebValid=this.isWebValid;const isX509Valid=this.isX509Valid;this.sync.update({transportConfig:transportConfigNew,identity:identity,isWebValid:isWebValid,isX509Valid:isX509Valid,isSyncActive:this.isSyncActive,ditto:this});const configSerializeReady=transportConfigToSerializable(transportConfigNew);const configCBOR=CBOR.encode(configSerializeReady);const dittoHandle=Bridge.ditto.handleFor(this);this.deferClose((()=>{dittoSmallPeerInfoCollectionSetTransportConfigData(dittoHandle.deref(),configCBOR)}))}updateTransportConfig(update){const transportConfig=this.transportConfig.copy();update(transportConfig);this.setTransportConfig(transportConfig);return this}startSync(){this.setSyncActive(true)}stopSync(){this.setSyncActive(false)}observePeers(callback){Logger.warning("`ditto.observePeers()` is deprecated, please use `ditto.presence.observe()` instead.");const token=this.presenceManager.addObserver(callback);return new Observer(this.presenceManager,token,{stopsWhenFinalized:true})}observeTransportConditions(callback){const token=this.transportConditionsManager.addObserver(callback);return new Observer(this.transportConditionsManager,token,{stopsWhenFinalized:true})}runGarbageCollection(){const dittoHandle=Bridge.ditto.handleFor(this);return this.deferClose((()=>{dittoRunGarbageCollection(dittoHandle.deref())}))}async disableSyncWithV3(){const dittoHandle=Bridge.ditto.handleFor(this);return this.deferCloseAsync((async()=>{await dittoDisableSyncWithV3(dittoHandle.deref())}))}async close(){if(this.isClosed){return}this._isClosed=true;this.stopSync();this.store.close();this.presence.close();this.auth.close();this.sync.close();this.presenceManager.close();this.liveQueryManager.close();this.attachmentFetcherManager.close();this.transportConditionsManager.close();this.subscriptionManager.close();if(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=false;await Bridge.ditto.close(this)}get numPendingOperations(){return this.pendingOperations.size}deferClose(closure){if(!this.deferCloseAllowed){throw new Error(`Can't perform operation using a Ditto instance that has been closed.`)}return closure()}async deferCloseAsync(closure){if(!this.deferCloseAllowed){throw new Error(`Can't perform operation using a Ditto instance that has been closed.`)}const pendingOperation=closure();this.pendingOperations.add(pendingOperation);let result;try{result=await pendingOperation}finally{this.pendingOperations.delete(pendingOperation)}return result}authClientValidityChanged(isWebValid,isX509Valid){const transportConfig=this.transportConfig;const identity=this.identity;const isSyncActive=this.isSyncActive;this.isX509Valid;this.isWebValid;this.isX509Valid=isX509Valid;this.isWebValid=isWebValid;this.auth["@ditto.authClientValidityChanged"](isWebValid,isX509Valid);this.sync.update({transportConfig:transportConfig,identity:identity,isWebValid:isWebValid,isX509Valid:isX509Valid,isSyncActive:isSyncActive,ditto:this})}validateIdentity(identity){const validIdentity={...identity};const appID=identity.appID;if(!["offlinePlayground","sharedKey","manual","onlinePlayground","onlineWithAuthentication"].includes(identity.type)){throw new Error(`Can't create Ditto instance, unknown identity type: ${identity.type}`)}if((identity.type==="offlinePlayground"||identity.type==="sharedKey"||identity.type==="onlinePlayground"||identity.type==="onlineWithAuthentication")&&typeof appID==="undefined"){throw new Error(`Property .appID must be given for identity, but isn't.`)}if(typeof appID!=="undefined"&&typeof appID!=="string"){throw new Error(`Property .appID must be be of type string, but is of type '${typeof appID}': ${appID}`)}if((identity.type==="offlinePlayground"||identity.type==="sharedKey")&&typeof identity.siteID!=="undefined"){const siteID=identity.siteID;const isSiteIDNumberOrBigInt=typeof siteID==="number"||typeof siteID==="bigint";if(!isSiteIDNumberOrBigInt)throw new Error("Can't create Ditto instance, siteID must be a number or BigInt");if(siteID<0)throw new Error("Can't create Ditto instance, siteID must be >= 0");if(siteID>BigInt("0xffffffffffffffff"))throw new Error("Can't create Ditto instance, siteID must be < 2^64")}if(identity.type==="sharedKey");if(identity.type==="manual");if(identity.type==="onlinePlayground"){const token=identity.token;if(typeof token==="undefined"){throw new Error(`Property .token must be given for identity but isn't. You can find the corresponding token on the Ditto Portal.`)}if(typeof token!=="undefined"&&typeof token!=="string"){throw new Error(`Property .token of identity must be be of type string, but is of type '${typeof token}': ${token}`)}}if(identity.type==="onlineWithAuthentication");return validIdentity}setSyncActive(flag){const dittoHandle=Bridge.ditto.handleFor(this);this.deferClose((()=>{if(flag&&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.")}if(!this.isSyncActive&&flag){this.keepAlive.retain("sync")}if(this.isSyncActive&&!flag){this.keepAlive.release("sync")}this._isSyncActive=flag;const isWebValid=this.isWebValid;const isX509Valid=this.isX509Valid;const identity=this.identity;const transportConfig=this.transportConfig;dittoSetDeviceName(dittoHandle.deref(),this.deviceName);this.sync.update({identity:identity,transportConfig:transportConfig,isWebValid:isWebValid,isX509Valid:isX509Valid,isSyncActive:!!flag,ditto:this})}))}makeDefaultTransportConfig(){const dittoHandle=Bridge.ditto.handleFor(this);return this.deferClose((()=>{const transportConfig=new TransportConfig;if(transportsBLEIsAvailable(dittoHandle.deref())){transportConfig.peerToPeer.bluetoothLE.isEnabled=true}if(transportsAWDLIsAvailable(dittoHandle.deref())){transportConfig.peerToPeer.awdl.isEnabled=true}if(transportsLANIsAvailable(dittoHandle.deref())){transportConfig.peerToPeer.lan.isEnabled=true}return transportConfig.freeze()}))}}const checkAPIs=_globalObject=>{const requiredBrowserAPIs=["BigInt","WeakRef","FinalizationRegistry"];const globalObject=_globalObject||globalThis||global||window;return requiredBrowserAPIs.every((apiName=>!!globalObject[apiName]))};const disableDeadlockTimeoutWhenDebugging=()=>{};class QueryResultItem{get value(){this.materialize();if(this.materializedValue===undefined){throw new Error("Internal Error: Materialized value is undefined")}return this.materializedValue}get isMaterialized(){return this.materializedValue!==undefined}materialize(){if(!this.isMaterialized){const cborValue=this.cborData();let materializedValue;try{materializedValue=CBOR.decode(cborValue)}catch(error){throw new Error(`Internal inconsistency: CBOR decoding error while materializing result item: ${error.message}`)}if(materializedValue===undefined){throw new Error("Internal inconsistency: Materialized value is undefined")}this.materializedValue=materializedValue}}dematerialize(){this.materializedValue=undefined}cborData(){const resultHandle=Bridge.dqlResult.handleFor(this);return dqlResultCBOR(resultHandle.deref())}jsonString(){const resultHandle=Bridge.dqlResult.handleFor(this);return dqlResultJSON(resultHandle.deref())}constructor(){}}function getBridgeLoad(){const countsByType={};Bridge.all.map((bridgeWeakRef=>{const bridge=bridgeWeakRef.deref();if(!bridge){return null}if(bridge.count===0){return null}countsByType[bridge.type.name]=bridge.count}));return countsByType}class StaticTCPClient{}class WebsocketClient{}Bridge.attachment.registerType(Attachment);Bridge.document.registerType(Document);Bridge.dqlResult.registerType(QueryResultItem);Bridge.dqlResponse.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,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,documentIDReplacer,getBridgeLoad,init,mapFFIErrors,mapFFIErrorsAsync,transportConfigFromDeserializable,transportConfigToSerializable,validateDocumentIDCBOR,validateDocumentIDValue};
|
|
1
|
+
class KeepAlive{get isActive(){return null!==this.intervalID}constructor(){this.countsByID={},this.intervalID=null}retain(t){if(void 0===this.countsByID[t]&&(this.countsByID[t]=0),this.countsByID[t]+=1,null===this.intervalID){const t=2147483647;this.intervalID=setInterval((()=>{}),t),KeepAlive.finalizationRegistry.register(this,this.intervalID,this)}}release(t){if(void 0===this.countsByID[t])throw new Error(`Internal inconsistency, trying to release a keep-alive ID that hasn't been retained before or isn't tracked anymore: ${t}`);this.countsByID[t]-=1,0===this.countsByID[t]&&delete this.countsByID[t],0===Object.keys(this.countsByID).length&&(KeepAlive.finalizationRegistry.unregister(this),clearInterval(this.intervalID),this.intervalID=null)}currentIDs(){return Object.keys(this.countsByID)}countForID(t){var e;return null!==(e=this.countsByID[t])&&void 0!==e?e:null}}KeepAlive.finalizationRegistry=new FinalizationRegistry(clearInterval);class Observer{get token(){return this._token}constructor(t,e,n={}){this.observerManager=t,this._token=e,this.options=n,n.stopsWhenFinalized&&Observer.finalizationRegistry.register(this,{observerManager:t,token:e},this)}get isStopped(){return void 0!==this.token&&this.observerManager.hasObserver(this.token)}stop(){const t=this.token;t&&(delete this._token,Observer.finalizationRegistry.unregister(this),this.observerManager.removeObserver(t))}static finalize(t){const{observerManager:e,token:n}=t;e.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"(t,e,n){const r=t?new MutableCounter(privateToken$1):new Counter;return r.mutDoc=t,r.path=e,r._value=n,r}}class MutableCounter extends Counter{increment(t){const e=this.mutDoc,n=this.path;if(!e)throw new Error("Can't increment counter, only possible within the closure of a collection's update() method.");e.at(n)["@ditto.increment"](t),this._value+=t}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(t){this["@ditto.value"]=t}static"@ditto.create"(t,e,n){const r=t?new MutableRegister(n,privateToken):new Register(n);return r["@ditto.mutableDocument"]=t,r["@ditto.path"]=e,r["@ditto.value"]=n,r}}class MutableRegister extends Register{get value(){return super.value}set value(t){this.set(t)}set(t){const e=this["@ditto.mutableDocument"],n=this["@ditto.path"];e.at(n)["@ditto.set"](t),this["@ditto.value"]=t}constructor(t){if(arguments[1]!==privateToken)throw new Error("MutableRegister constructor is for internal use only.");super(t)}}function to_string(t){return t.toString()}function is_number(t){return"number"==typeof t}function try_downsize(t){switch(typeof t){case"bigint":if(-Number.MAX_SAFE_INTEGER<=t&&t<=Number.MAX_SAFE_INTEGER)return Number(t);case"number":return t;default:throw new Error(`number or bigint expected, got \`${t}\``)}}function from_string(t){return BigInt(t)}function get_element(t,e){return t[e]}function typeof_(t){return typeof t}function mk_send_ret(){return function send_ret(t){return t}}let wasm;const heap=new Array(128).fill(void 0);function getObject(t){return heap[t]}heap.push(void 0,null,!0,!1);let heap_next=heap.length;function dropObject(t){t<132||(heap[t]=heap_next,heap_next=t)}function takeObject(t){const e=getObject(t);return dropObject(t),e}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(t,e){return t>>>=0,cachedTextDecoder.decode(getUint8Memory0().subarray(t,t+e))}function addHeapObject(t){heap_next===heap.length&&heap.push(heap.length+1);const e=heap_next;return heap_next=heap[e],heap[e]=t,e}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(t,e){return cachedTextEncoder.encodeInto(t,e)}:function(t,e){const n=cachedTextEncoder.encode(t);return e.set(n),{read:t.length,written:n.length}};function passStringToWasm0(t,e,n){if(void 0===n){const n=cachedTextEncoder.encode(t),r=e(n.length,1)>>>0;return getUint8Memory0().subarray(r,r+n.length).set(n),WASM_VECTOR_LEN=n.length,r}let r=t.length,i=e(r,1)>>>0;const o=getUint8Memory0();let a=0;for(;a<r;a++){const e=t.charCodeAt(a);if(e>127)break;o[i+a]=e}if(a!==r){0!==a&&(t=t.slice(a)),i=n(i,r,r=a+3*t.length,1)>>>0;const e=getUint8Memory0().subarray(i+a,i+r);a+=encodeString(t,e).written}return WASM_VECTOR_LEN=a,i}function isLikeNone(t){return null==t}let cachedInt32Memory0=null;function getInt32Memory0(){return null!==cachedInt32Memory0&&0!==cachedInt32Memory0.byteLength||(cachedInt32Memory0=new Int32Array(wasm.memory.buffer)),cachedInt32Memory0}function debugString(t){const e=typeof t;if("number"==e||"boolean"==e||null==t)return`${t}`;if("string"==e)return`"${t}"`;if("symbol"==e){const e=t.description;return null==e?"Symbol":`Symbol(${e})`}if("function"==e){const e=t.name;return"string"==typeof e&&e.length>0?`Function(${e})`:"Function"}if(Array.isArray(t)){const e=t.length;let n="[";e>0&&(n+=debugString(t[0]));for(let r=1;r<e;r++)n+=", "+debugString(t[r]);return n+="]",n}const n=/\[object ([^\]]+)\]/.exec(toString.call(t));let r;if(!(n.length>1))return toString.call(t);if(r=n[1],"Object"==r)try{return"Object("+JSON.stringify(t)+")"}catch(t){return"Object"}return t instanceof Error?`${t.name}: ${t.message}\n${t.stack}`:r}const CLOSURE_DTORS=new FinalizationRegistry((t=>{wasm.__wbindgen_export_2.get(t.dtor)(t.a,t.b)}));function makeMutClosure(t,e,n,r){const i={a:t,b:e,cnt:1,dtor:n},real=(...t)=>{i.cnt++;const e=i.a;i.a=0;try{return r(e,i.b,...t)}finally{0==--i.cnt?(wasm.__wbindgen_export_2.get(i.dtor)(e,i.b),CLOSURE_DTORS.unregister(i)):i.a=e}};return real.original=i,CLOSURE_DTORS.register(real,i,i),real}function __wbg_adapter_32(t,e){wasm._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h0d7def81e951aabf(t,e)}function __wbg_adapter_35(t,e,n){wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hb50f7912bc3eb535(t,e,addHeapObject(n))}function __wbg_adapter_38(t,e,n){wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__ha193016fe0ab2bbe(t,e,addHeapObject(n))}function __wbg_adapter_41(t,e){wasm._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__he55c991c4e0bd521(t,e)}function __wbg_adapter_44(t,e,n){wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h338d53cc9a4d1aef(t,e,addHeapObject(n))}function ditto_small_peer_info_get_sync_scope(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_get_sync_scope(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_sync_scope(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_sync_scope(i,addHeapObject(t),addHeapObject(e));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(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_get_is_enabled(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_enabled(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_enabled(i,addHeapObject(t),addHeapObject(e));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(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_get_metadata(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_small_peer_info_set_metadata(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_metadata(i,addHeapObject(t),addHeapObject(e));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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_small_peer_info_set_transport_config_data(i,addHeapObject(t),addHeapObject(e));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 t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_write_transaction_rollback(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction_rollback(i,addHeapObject(t),addHeapObject(e));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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction_commit(i,addHeapObject(t),addHeapObject(e));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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction(i,addHeapObject(t),addHeapObject(e));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(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_read_transaction_free(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_read_transaction(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_read_transaction(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_init_sdk_version(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_init_sdk_version(o,addHeapObject(t),addHeapObject(e),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 t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}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 t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_disable_sync_with_v3(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_disable_sync_with_v3(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_run_garbage_collection(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_run_garbage_collection(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_sync_group(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_sync_group(i,addHeapObject(t),addHeapObject(e));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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_connect_retry_interval(i,addHeapObject(t),addHeapObject(e));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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_device_name(i,addHeapObject(t),addHeapObject(e));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(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_presence_v3(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_presence_v1(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_presence_v1(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_clear_presence_v3_callback(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_clear_presence_v3_callback(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_clear_presence_callback(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_clear_presence_callback(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_free(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_free(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_shutdown(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_shutdown(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_make(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_make(o,addHeapObject(t),addHeapObject(e),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_uninitialized_ditto_make(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_uninitialized_ditto_make(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_static_websocket_clients(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_static_websocket_clients(o,addHeapObject(t),addHeapObject(e),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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_transport_condition_changed_callback(i,addHeapObject(t),addHeapObject(e));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_error_description(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_error_description(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_error_code(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_error_code(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_error_free(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_error_free(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_validate_document_id(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_validate_document_id(i,addHeapObject(t),addHeapObject(e));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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_id_query_compatible(i,addHeapObject(t),addHeapObject(e));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_dql_response_affected_document_id_at(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_dql_response_affected_document_id_at(i,addHeapObject(t),addHeapObject(e));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_dql_response_affected_document_id_count(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_dql_response_affected_document_id_count(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_dql_response_result_at(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_dql_response_result_at(i,addHeapObject(t),addHeapObject(e));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_dql_response_result_count(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_dql_response_result_count(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_dql_response_free(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_dql_response_free(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_dql_result_free(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_dql_result_free(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_result_json(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_result_json(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_result_cbor(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_result_cbor(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_experimental_remove_dql_subscription(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_experimental_remove_dql_subscription(o,addHeapObject(t),addHeapObject(e),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_experimental_add_dql_subscription(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_experimental_add_dql_subscription(o,addHeapObject(t),addHeapObject(e),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(t,e,n,r,i,o,a){try{const d=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_add_subscription(d,addHeapObject(t),addHeapObject(e),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(t,e,n,r,i,o,a){try{const d=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_remove_subscription(d,addHeapObject(t),addHeapObject(e),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_sdk_transports_awdl_is_available(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_awdl_is_available(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_sdk_transports_lan_is_available(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_awdl_is_available(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_sdk_transports_ble_is_available(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_awdl_is_available(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_sdk_transports_init(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_init(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_sdk_transports_error_free(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_error_free(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_sdk_transports_error_value(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_error_value(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_sdk_transports_error_new(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_sdk_transports_error_new(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_verify_license(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_verify_license(i,addHeapObject(t),addHeapObject(e));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(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_cancel_resolve_attachment(o,addHeapObject(t),addHeapObject(e),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(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_free_attachment_handle(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_get_complete_attachment_data(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_complete_attachment_data(i,addHeapObject(t),addHeapObject(e));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(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_new_attachment_from_bytes(o,addHeapObject(t),addHeapObject(e),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(t,e,n,r,i){try{const s=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_resolve_attachment(s,addHeapObject(t),addHeapObject(e),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 websocket_client_free_handle(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.websocket_client_free_handle(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_free(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_free(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_get_cbor_with_path_type(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_get_cbor_with_path_type(o,addHeapObject(t),addHeapObject(e),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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_remove(i,addHeapObject(t),addHeapObject(e));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(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_set_cbor_with_timestamp(a,addHeapObject(t),addHeapObject(e),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(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_set_cbor(o,addHeapObject(t),addHeapObject(e),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(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_increment_counter(o,addHeapObject(t),addHeapObject(e),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(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_id(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function dittoffi_try_experimental_exec_statement_str(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_experimental_exec_statement_str(a,addHeapObject(t),addHeapObject(e),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(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_get(a,addHeapObject(t),addHeapObject(e),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(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_remove(a,addHeapObject(t),addHeapObject(e),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(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_evict(a,addHeapObject(t),addHeapObject(e),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(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_update_multiple(a,addHeapObject(t),addHeapObject(e),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(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_update(a,addHeapObject(t),addHeapObject(e),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(t,e,n,r,i,o){try{const c=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_insert_value(c,addHeapObject(t),addHeapObject(e),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(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_collection_names(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_documents_hash(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_documents_hash(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_documents_hash_mnemonic(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_documents_hash_mnemonic(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_evict_query_str(t,e,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_evict_query_str(l,addHeapObject(t),addHeapObject(e),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(t,e,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_remove_query_str(l,addHeapObject(t),addHeapObject(e),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(t,e,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_exec_query_str(l,addHeapObject(t),addHeapObject(e),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(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.jsDocsToCDocs(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_presence_v1_callback(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_presence_v1_callback(i,addHeapObject(t),addHeapObject(e));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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_presence_v3_callback(i,addHeapObject(t),addHeapObject(e));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(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_logout(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_login_with_credentials(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_login_with_credentials(a,addHeapObject(t),addHeapObject(e),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(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_login_with_token(o,addHeapObject(t),addHeapObject(e),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(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_is_x509_valid(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_is_web_valid(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_is_web_valid(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_user_id(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_user_id(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_get_app_id(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_get_app_id(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_get_site_id(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_get_site_id(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_set_login_provider(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_set_login_provider(i,addHeapObject(t),addHeapObject(e));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(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_manual_v0(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_identity_config_make_shared_key(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_shared_key(o,addHeapObject(t),addHeapObject(e),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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_offline_playground(i,addHeapObject(t),addHeapObject(e));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(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_online_playground(o,addHeapObject(t),addHeapObject(e),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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_identity_config_make_online_with_authentication(i,addHeapObject(t),addHeapObject(e));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(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_login_provider(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_set_validity_listener(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_set_validity_listener(i,addHeapObject(t),addHeapObject(e));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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_signal_available_next(i,addHeapObject(t),addHeapObject(e));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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_stop(i,addHeapObject(t),addHeapObject(e));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_experimental_webhook_register_dql_live_query_str(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_experimental_webhook_register_dql_live_query_str(a,addHeapObject(t),addHeapObject(e),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(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_start(i,addHeapObject(t),addHeapObject(e));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(t,e,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(t),addHeapObject(e),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(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.dittoffi_try_experimental_register_change_observer_str_detached(a,addHeapObject(t),addHeapObject(e),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(t,e,n,r,i,o,a){try{const d=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_webhook_register_str(d,addHeapObject(t),addHeapObject(e),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_log(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_log(i,addHeapObject(t),addHeapObject(e));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 t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_minimum_log_level(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_minimum_log_level(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}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 t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_emoji_headings_enabled(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_emoji_headings_enabled(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}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 t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_enabled(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_enabled(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}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 t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_set_log_file(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_set_log_file(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_set_custom_log_cb(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_set_custom_log_cb(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function handleError(t,e){try{return t.apply(this,e)}catch(t){wasm.__wbindgen_exn_store(addHeapObject(t))}}function notDefined(t){return()=>{throw new Error(`${t} is not defined`)}}function getArrayU8FromWasm0(t,e){return t>>>=0,getUint8Memory0().subarray(t/1,t/1+e)}function __wbg_adapter_394(t,e,n,r){wasm.wasm_bindgen__convert__closures__invoke2_mut__h00cef82167be2335(t,e,addHeapObject(n),addHeapObject(r))}function boxCStringIntoString(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.boxCStringIntoString(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function refCStringToString(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.refCStringToString(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function boxCBytesIntoBuffer(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.boxCBytesIntoBuffer(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function withOutPtr$1(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.withOutPtr(i,addHeapObject(t),addHeapObject(e));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 withOutBoxCBytes(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.withOutBoxCBytes(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function cStringVecToStringArray(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.cStringVecToStringArray(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}async function __wbg_load(t,e){if("function"==typeof Response&&t instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(t,e)}catch(e){if("application/wasm"==t.headers.get("Content-Type"))throw e;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",e)}const n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}{const n=await WebAssembly.instantiate(t,e);return n instanceof WebAssembly.Instance?{instance:n,module:t}:n}}function __wbg_get_imports(){const t={wbg:{}};return t.wbg.__wbindgen_object_drop_ref=function(t){takeObject(t)},t.wbg.__wbindgen_string_new=function(t,e){return addHeapObject(getStringFromWasm0(t,e))},t.wbg.__wbindgen_cb_drop=function(t){const e=takeObject(t).original;if(1==e.cnt--)return e.a=0,!0;return!1},t.wbg.__wbg_log_f7c904296a5a8ff0=function(t,e){let n,r;try{n=t,r=e,console.log(getStringFromWasm0(t,e))}finally{wasm.__wbindgen_free(n,r,1)}},t.wbg.__wbg_new_abda76e883ba8a5f=function(){return addHeapObject(new Error)},t.wbg.__wbg_stack_658279fe44541cf6=function(t,e){const n=passStringToWasm0(getObject(e).stack,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_error_f851667af71bcfc6=function(t,e){let n,r;try{n=t,r=e,console.error(getStringFromWasm0(t,e))}finally{wasm.__wbindgen_free(n,r,1)}},t.wbg.__wbindgen_is_string=function(t){return"string"==typeof getObject(t)},t.wbg.__wbindgen_string_get=function(t,e){const n=getObject(e),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()[t/4+1]=o,getInt32Memory0()[t/4+0]=i},t.wbg.__wbindgen_object_clone_ref=function(t){return addHeapObject(getObject(t))},t.wbg.__wbg_fetch_57429b87be3dcc33=function(t){return addHeapObject(fetch(getObject(t)))},t.wbg.__wbg_clearTimeout_23ee6db72c0ad922="function"==typeof clearTimeout?clearTimeout:notDefined("clearTimeout"),t.wbg.__wbg_setTimeout_09074a1669d0f224=function(){return handleError((function(t,e){return setTimeout(getObject(t),e)}),arguments)},t.wbg.__wbg_clearInterval_d5655e407a861314="function"==typeof clearInterval?clearInterval:notDefined("clearInterval"),t.wbg.__wbg_setInterval_fa82463ae3f43f48=function(){return handleError((function(t,e){return setInterval(getObject(t),e)}),arguments)},t.wbg.__wbg_randomFillSync_6894564c2c334c42=function(){return handleError((function(t,e,n){getObject(t).randomFillSync(getArrayU8FromWasm0(e,n))}),arguments)},t.wbg.__wbg_getRandomValues_805f1c3d65988a5a=function(){return handleError((function(t,e){getObject(t).getRandomValues(getObject(e))}),arguments)},t.wbg.__wbg_crypto_e1d53a1d73fb10b8=function(t){return addHeapObject(getObject(t).crypto)},t.wbg.__wbindgen_is_object=function(t){const e=getObject(t);return"object"==typeof e&&null!==e},t.wbg.__wbg_process_038c26bf42b093f8=function(t){return addHeapObject(getObject(t).process)},t.wbg.__wbg_versions_ab37218d2f0b24a8=function(t){return addHeapObject(getObject(t).versions)},t.wbg.__wbg_node_080f4b19d15bc1fe=function(t){return addHeapObject(getObject(t).node)},t.wbg.__wbg_msCrypto_6e7d3e1f92610cbb=function(t){return addHeapObject(getObject(t).msCrypto)},t.wbg.__wbg_require_78a3dcfbdba9cbce=function(){return handleError((function(){return addHeapObject(module.require)}),arguments)},t.wbg.__wbindgen_is_function=function(t){return"function"==typeof getObject(t)},t.wbg.__wbindgen_number_new=function(t){return addHeapObject(t)},t.wbg.__wbg_mksendret_58e4351c0f62e857=function(){return addHeapObject(mk_send_ret())},t.wbg.__wbg_trydownsize_28e49b8073c2a2fc=function(t){return addHeapObject(try_downsize(takeObject(t)))},t.wbg.__wbg_isnumber_c97122a46d4ace09=function(t){return is_number(getObject(t))},t.wbg.__wbg_tostring_7847f1b7af649ba5=function(t,e){const n=passStringToWasm0(to_string(getObject(e)),wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_fromstring_721719aff319c1fe=function(t,e){return addHeapObject(from_string(getStringFromWasm0(t,e)))},t.wbg.__wbg_getelement_cd48f1e89008c242=function(t,e){return addHeapObject(get_element(getObject(t),e>>>0))},t.wbg.__wbg_typeof_cb5c1bc26a697ea8=function(t,e){const n=passStringToWasm0(typeof_(getObject(e)),wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},t.wbg.__wbindgen_error_new=function(t,e){return addHeapObject(new Error(getStringFromWasm0(t,e)))},t.wbg.__wbindgen_is_null=function(t){return null===getObject(t)},t.wbg.__wbindgen_is_undefined=function(t){return void 0===getObject(t)},t.wbg.__wbg_instanceof_Blob_d18d26355bccfd22=function(t){let e;try{e=getObject(t)instanceof Blob}catch{e=!1}return e},t.wbg.__wbg_newwithu8arraysequenceandoptions_b0ee96dd3232b69c=function(){return handleError((function(t,e){return addHeapObject(new Blob(getObject(t),getObject(e)))}),arguments)},t.wbg.__wbg_new_39f0e6d61fc67f0e=function(){return handleError((function(){return addHeapObject(new FormData)}),arguments)},t.wbg.__wbg_append_1b70fd81d162ab50=function(){return handleError((function(t,e,n,r){getObject(t).append(getStringFromWasm0(e,n),getObject(r))}),arguments)},t.wbg.__wbg_append_32853c33a2dd22f0=function(){return handleError((function(t,e,n,r,i,o){getObject(t).append(getStringFromWasm0(e,n),getObject(r),getStringFromWasm0(i,o))}),arguments)},t.wbg.__wbg_signal_31753ac644b25fbb=function(t){return addHeapObject(getObject(t).signal)},t.wbg.__wbg_new_6396e586b56e1dff=function(){return handleError((function(){return addHeapObject(new AbortController)}),arguments)},t.wbg.__wbg_abort_064ae59cda5cd244=function(t){getObject(t).abort()},t.wbg.__wbg_url_1f1b597f64482fd0=function(t,e){const n=passStringToWasm0(getObject(e).url,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_readyState_9c0f66433e329c9e=function(t){return getObject(t).readyState},t.wbg.__wbg_setonopen_9ce48dce57e549b5=function(t,e){getObject(t).onopen=getObject(e)},t.wbg.__wbg_setonerror_02393260b3e29972=function(t,e){getObject(t).onerror=getObject(e)},t.wbg.__wbg_setonclose_4ce49fd8fd7783fb=function(t,e){getObject(t).onclose=getObject(e)},t.wbg.__wbg_setonmessage_c5a806b62a0c5607=function(t,e){getObject(t).onmessage=getObject(e)},t.wbg.__wbg_setbinaryType_ee55743ddf4beb37=function(t,e){getObject(t).binaryType=takeObject(e)},t.wbg.__wbg_new_d29e507f6606de91=function(){return handleError((function(t,e){return addHeapObject(new WebSocket(getStringFromWasm0(t,e)))}),arguments)},t.wbg.__wbg_newwithstrsequence_7b0c4aadc1ae1635=function(){return handleError((function(t,e,n){return addHeapObject(new WebSocket(getStringFromWasm0(t,e),getObject(n)))}),arguments)},t.wbg.__wbg_close_45d053bea59e7746=function(){return handleError((function(t){getObject(t).close()}),arguments)},t.wbg.__wbg_send_80b256d87a6779e5=function(){return handleError((function(t,e,n){getObject(t).send(getStringFromWasm0(e,n))}),arguments)},t.wbg.__wbg_send_640853f8eb0f0385=function(){return handleError((function(t,e,n){getObject(t).send(getArrayU8FromWasm0(e,n))}),arguments)},t.wbg.__wbg_fetch_749a56934f95c96c=function(t,e){return addHeapObject(getObject(t).fetch(getObject(e)))},t.wbg.__wbg_new_2d0053ee81e4dd2a=function(){return handleError((function(){return addHeapObject(new Headers)}),arguments)},t.wbg.__wbg_append_de37df908812970d=function(){return handleError((function(t,e,n,r,i){getObject(t).append(getStringFromWasm0(e,n),getStringFromWasm0(r,i))}),arguments)},t.wbg.__wbg_instanceof_Response_eaa426220848a39e=function(t){let e;try{e=getObject(t)instanceof Response}catch{e=!1}return e},t.wbg.__wbg_url_74285ddf2747cb3d=function(t,e){const n=passStringToWasm0(getObject(e).url,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_status_c4ef3dd591e63435=function(t){return getObject(t).status},t.wbg.__wbg_headers_fd64ad685cf22e5d=function(t){return addHeapObject(getObject(t).headers)},t.wbg.__wbg_arrayBuffer_4c27b6f00c530232=function(){return handleError((function(t){return addHeapObject(getObject(t).arrayBuffer())}),arguments)},t.wbg.__wbg_code_b09504754e0520f1=function(t){return getObject(t).code},t.wbg.__wbg_newwithstrandinit_05d7180788420c40=function(){return handleError((function(t,e,n){return addHeapObject(new Request(getStringFromWasm0(t,e),getObject(n)))}),arguments)},t.wbg.__wbg_wasClean_2af04e6cf2076497=function(t){return getObject(t).wasClean},t.wbg.__wbg_code_24e161f043adce8a=function(t){return getObject(t).code},t.wbg.__wbg_reason_40159cc3d2fc655d=function(t,e){const n=passStringToWasm0(getObject(e).reason,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_now_8172cd917e5eda6b=function(t){return getObject(t).now()},t.wbg.__wbg_data_7b1f01f4e6a64fbe=function(t){return addHeapObject(getObject(t).data)},t.wbg.__wbg_new_898a68150f225f2e=function(){return addHeapObject(new Array)},t.wbg.__wbg_valueOf_e39b017d2100ede0=function(t){return getObject(t).valueOf()},t.wbg.__wbg_newnoargs_581967eacc0e2604=function(t,e){return addHeapObject(new Function(getStringFromWasm0(t,e)))},t.wbg.__wbg_next_526fc47e980da008=function(t){return addHeapObject(getObject(t).next)},t.wbg.__wbg_next_ddb3312ca1c4e32a=function(){return handleError((function(t){return addHeapObject(getObject(t).next())}),arguments)},t.wbg.__wbg_done_5c1f01fb660d73b5=function(t){return getObject(t).done},t.wbg.__wbg_value_1695675138684bd5=function(t){return addHeapObject(getObject(t).value)},t.wbg.__wbg_iterator_97f0c81209c6c35a=function(){return addHeapObject(Symbol.iterator)},t.wbg.__wbg_get_97b561fb56f034b5=function(){return handleError((function(t,e){return addHeapObject(Reflect.get(getObject(t),getObject(e)))}),arguments)},t.wbg.__wbg_call_cb65541d95d71282=function(){return handleError((function(t,e){return addHeapObject(getObject(t).call(getObject(e)))}),arguments)},t.wbg.__wbg_new_b51585de1b234aff=function(){return addHeapObject(new Object)},t.wbg.__wbg_self_1ff1d729e9aae938=function(){return handleError((function(){return addHeapObject(self.self)}),arguments)},t.wbg.__wbg_window_5f4faef6c12b79ec=function(){return handleError((function(){return addHeapObject(window.window)}),arguments)},t.wbg.__wbg_globalThis_1d39714405582d3c=function(){return handleError((function(){return addHeapObject(globalThis.globalThis)}),arguments)},t.wbg.__wbg_global_651f05c6a0944d1c=function(){return handleError((function(){return addHeapObject(global.global)}),arguments)},t.wbg.__wbg_push_ca1c26067ef907ac=function(t,e){return getObject(t).push(getObject(e))},t.wbg.__wbg_instanceof_ArrayBuffer_39ac22089b74fddb=function(t){let e;try{e=getObject(t)instanceof ArrayBuffer}catch{e=!1}return e},t.wbg.__wbg_apply_64be369596a02ae0=function(){return handleError((function(t,e,n){return addHeapObject(getObject(t).apply(getObject(e),getObject(n)))}),arguments)},t.wbg.__wbg_call_01734de55d61e11d=function(){return handleError((function(t,e,n){return addHeapObject(getObject(t).call(getObject(e),getObject(n)))}),arguments)},t.wbg.__wbg_valueOf_7d8df3cd4f3f583b=function(t){return getObject(t).valueOf()},t.wbg.__wbg_getTime_5e2054f832d82ec9=function(t){return getObject(t).getTime()},t.wbg.__wbg_new0_c0be7df4b6bd481f=function(){return addHeapObject(new Date)},t.wbg.__wbg_now_9c5990bda04c7e53=function(){return Date.now()},t.wbg.__wbg_instanceof_Object_3daa8298c86298be=function(t){let e;try{e=getObject(t)instanceof Object}catch{e=!1}return e},t.wbg.__wbg_new_43f1b47c28813cbd=function(t,e){try{var n={a:t,b:e};const r=new Promise(((t,e)=>{const r=n.a;n.a=0;try{return __wbg_adapter_394(r,n.b,t,e)}finally{n.a=r}}));return addHeapObject(r)}finally{n.a=n.b=0}},t.wbg.__wbg_resolve_53698b95aaf7fcf8=function(t){return addHeapObject(Promise.resolve(getObject(t)))},t.wbg.__wbg_then_f7e06ee3c11698eb=function(t,e){return addHeapObject(getObject(t).then(getObject(e)))},t.wbg.__wbg_then_b2267541e2a73865=function(t,e,n){return addHeapObject(getObject(t).then(getObject(e),getObject(n)))},t.wbg.__wbg_buffer_085ec1f694018c4f=function(t){return addHeapObject(getObject(t).buffer)},t.wbg.__wbg_newwithbyteoffsetandlength_6da8e527659b86aa=function(t,e,n){return addHeapObject(new Uint8Array(getObject(t),e>>>0,n>>>0))},t.wbg.__wbg_new_8125e318e6245eed=function(t){return addHeapObject(new Uint8Array(getObject(t)))},t.wbg.__wbg_set_5cf90238115182c3=function(t,e,n){getObject(t).set(getObject(e),n>>>0)},t.wbg.__wbg_length_72e2208bbc0efc61=function(t){return getObject(t).length},t.wbg.__wbg_instanceof_Uint8Array_d8d9cb2b8e8ac1d4=function(t){let e;try{e=getObject(t)instanceof Uint8Array}catch{e=!1}return e},t.wbg.__wbg_newwithlength_e5d69174d6984cd7=function(t){return addHeapObject(new Uint8Array(t>>>0))},t.wbg.__wbg_subarray_13db269f57aa838d=function(t,e,n){return addHeapObject(getObject(t).subarray(e>>>0,n>>>0))},t.wbg.__wbg_has_c5fcd020291e56b8=function(){return handleError((function(t,e){return Reflect.has(getObject(t),getObject(e))}),arguments)},t.wbg.__wbg_set_092e06b0f9d71865=function(){return handleError((function(t,e,n){return Reflect.set(getObject(t),getObject(e),getObject(n))}),arguments)},t.wbg.__wbg_stringify_e25465938f3f611f=function(){return handleError((function(t){return addHeapObject(JSON.stringify(getObject(t)))}),arguments)},t.wbg.__wbindgen_debug_string=function(t,e){const n=passStringToWasm0(debugString(getObject(e)),wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},t.wbg.__wbindgen_throw=function(t,e){throw new Error(getStringFromWasm0(t,e))},t.wbg.__wbindgen_memory=function(){return addHeapObject(wasm.memory)},t.wbg.__wbindgen_closure_wrapper2774=function(t,e,n){return addHeapObject(makeMutClosure(t,e,1197,__wbg_adapter_32))},t.wbg.__wbindgen_closure_wrapper2776=function(t,e,n){return addHeapObject(makeMutClosure(t,e,1197,__wbg_adapter_35))},t.wbg.__wbindgen_closure_wrapper14425=function(t,e,n){return addHeapObject(makeMutClosure(t,e,4221,__wbg_adapter_38))},t.wbg.__wbindgen_closure_wrapper22692=function(t,e,n){return addHeapObject(makeMutClosure(t,e,6357,__wbg_adapter_41))},t.wbg.__wbindgen_closure_wrapper24166=function(t,e,n){return addHeapObject(makeMutClosure(t,e,6844,__wbg_adapter_44))},t}function __wbg_finalize_init(t,e){return wasm=t.exports,init$2.__wbindgen_wasm_module=e,cachedInt32Memory0=null,cachedUint8Memory0=null,wasm}async function init$2(t){if(void 0!==wasm)return wasm;if(void 0===t)throw new Error("Can't load ditto.wasm, expected module to be provided at initialization time but got nothing.");const e=__wbg_get_imports();("string"==typeof t||"function"==typeof Request&&t instanceof Request||"function"==typeof URL&&t instanceof URL)&&(t=fetch(t));const{instance:n,module:r}=await __wbg_load(await t,e);return __wbg_finalize_init(n,r)}const isWebBuild=!0,PREFIX_REGEX=new RegExp(/^<.*?>\s*/);class DittoFFIError extends Error{constructor(t,e,n){const r=ffiErrorMessage();super(e||r||n),this.code=t}}function throwOnErrorResult(t,e){if(null!==t){let n,r;try{n=dittoffi_error_code(t),r=boxCStringIntoString(dittoffi_error_description(t)),dittoffi_error_free(t)}catch(t){throw new DittoFFIError(-1,`Failed to retrieve Ditto core error message: ${t.message}`)}throw r=null==r?`${e}() 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(t,e,n,r){ensureInitialized();const i=ditto_document_set_cbor_with_timestamp(t,bytesFromString(e),n,r);if(0!==i)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${i}`)}function documentSetCBOR(t,e,n){ensureInitialized();const r=ditto_document_set_cbor(t,bytesFromString(e),n);if(0!==r)throw new Error(errorMessage()||`ditto_document_set_cbor() failed with error code: ${r}`)}function documentID(t){ensureInitialized();return boxCBytesIntoBuffer(ditto_document_id(t))}function documentGetCBORWithPathType(t,e,n){ensureInitialized();const r=ditto_document_get_cbor_with_path_type(t,bytesFromString(e),n);return{statusCode:r.status_code,cbor:boxCBytesIntoBuffer(r.cbor)}}function documentRemove(t,e){ensureInitialized();const n=ditto_document_remove(t,bytesFromString(e));if(0!==n)throw new Error(errorMessage()||`ditto_document_remove() failed with error code: ${n}`)}function documentIncrementCounter(t,e,n){ensureInitialized();const r=ditto_document_increment_counter(t,bytesFromString(e),n);if(0!==r)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${r}`)}function documentFree(t){ensureInitialized(),ditto_document_free(t)}function documentIDQueryCompatible(t,e){ensureInitialized();return boxCStringIntoString(ditto_document_id_query_compatible(t,e))}function validateDocumentID(t){ensureInitialized();return boxCBytesIntoBuffer(withOutBoxCBytes((e=>{const n=ditto_validate_document_id(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${n}`);return e})))}async function collectionGet(t,e,n,r){ensureInitialized();const i=bytesFromString(e),{status_code:o,document:a}=await ditto_collection_get(t,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(t,e,n,r,i){ensureInitialized();const o=bytesFromString(e);let a;switch(r){case"merge":a="Merge";break;case"insertIfAbsent":a="InsertIfAbsent";break;case"insertDefaultIfAbsent":a="InsertDefaultIfAbsent";break;default:throw new Error("Invalid write strategy provided")}const{status_code:s,id:c}=await ditto_collection_insert_value(t,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(t,e,n,r){ensureInitialized();const i=bytesFromString(e),{status_code:o,bool_value:a}=await ditto_collection_remove(t,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${o}`);return a}async function collectionEvict(t,e,n,r){ensureInitialized();const i=bytesFromString(e),{status_code:o,bool_value:a}=await ditto_collection_evict(t,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${o}`);return a}async function collectionUpdate(t,e,n,r){ensureInitialized();const i=bytesFromString(e),o=await ditto_collection_update(t,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${o}`)}async function collectionUpdateMultiple(t,e,n,r){ensureInitialized();const i=bytesFromString(e),o=jsDocsToCDocs(r),a=await ditto_collection_update_multiple(t,i,n,o);if(0!==a)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${a}`)}async function collectionExecQueryStr(t,e,n,r,i,o,a,s){ensureInitialized();const c=bytesFromString(e),d=bytesFromString(r);return await ditto_collection_exec_query_str(t,c,n,d,i,o,a,s)}async function collectionRemoveQueryStr(t,e,n,r,i,o,a,s){ensureInitialized();const c=bytesFromString(e),d=bytesFromString(r);return await ditto_collection_remove_query_str(t,c,n,d,i,o,a,s)}async function collectionEvictQueryStr(t,e,n,r,i,o,a,s){ensureInitialized();const c=bytesFromString(e),d=bytesFromString(r);return await ditto_collection_evict_query_str(t,c,n,d,i,o,a,s)}async function tryExperimentalExecQueryStr(t,e,n,r){ensureInitialized();const i=bytesFromString(n),o=await dittoffi_try_experimental_exec_statement_str(t,e,i,r);return throwOnErrorResult(o.error,"dittoffi_try_experimental_exec_statement_str"),o.success}function addSubscription(t,e,n,r,i,o,a){ensureInitialized();return ditto_add_subscription(t,bytesFromString(e),bytesFromString(n),r,i,o,a)}function removeSubscription(t,e,n,r,i,o,a){ensureInitialized();return ditto_remove_subscription(t,bytesFromString(e),bytesFromString(n),r,i,o,a)}function tryExperimentalAddDQLSubscription(t,e,n){ensureInitialized();throwOnErrorResult(dittoffi_try_experimental_add_dql_subscription(t,bytesFromString(e),n).error,"dittoffi_try_experimental_add_dql_subscription")}function tryExperimentalRemoveDQLSubscription(t,e,n){ensureInitialized();throwOnErrorResult(dittoffi_try_experimental_remove_dql_subscription(t,bytesFromString(e),n).error,"dittoffi_try_experimental_remove_dql_subscription")}function dqlResponseFree(t){ensureInitialized(),ditto_dql_response_free(t)}function dqlResultFree(t){ensureInitialized(),ditto_dql_result_free(t)}function dqlResponseResults(t){ensureInitialized();const e=[],n=ditto_dql_response_result_count(t);for(let r=0;r<n;r++)e.push(ditto_dql_response_result_at(t,r));return e}function dqlMutatedDocumentIDs(t){ensureInitialized();const e=[],n=ditto_dql_response_affected_document_id_count(t);for(let r=0;r<n;r++){const n=ditto_dql_response_affected_document_id_at(t,r);e.push(boxCBytesIntoBuffer(n))}return e}function dqlResultCBOR(t){ensureInitialized();return boxCBytesIntoBuffer(ditto_result_cbor(t))}function dqlResultJSON(t){ensureInitialized();return boxCStringIntoString(ditto_result_json(t))}function liveQueryRegister(t,e,n,r,i,o,a,s,c){ensureInitialized();const d=bytesFromString(e),l=bytesFromString(n),{status_code:_,i64:u}=ditto_live_query_register_str_detached(t,d,l,r,i,o,a,wrapBackgroundCbForFFI(c,s));if(0!==_)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${_}`);return u}function tryExperimentalRegisterChangeObserver(t,e,n,r){ensureInitialized();const i=wrapBackgroundCbForFFI((t=>log("Error",`The registered store observer callback failed with ${t}`)),r),o=dittoffi_try_experimental_register_change_observer_str_detached(t,bytesFromString(e),n,i);return throwOnErrorResult(o.error,"dittoffi_try_experimental_register_change_observer_str_detached"),o.success}async function liveQueryStart(t,e){ensureInitialized();const n=await ditto_live_query_start(t,e);if(0!==n)throw new Error(errorMessage()||`\`ditto_live_query_start()\` failed with error code: ${n}`)}function liveQueryStop(t,e){ensureInitialized(),ditto_live_query_stop(t,e)}async function liveQuerySignalAvailableNext(t,e){ensureInitialized(),await ditto_live_query_signal_available_next(t,e)}async function liveQueryWebhookRegister(t,e,n,r,i,o,a){ensureInitialized();const s=bytesFromString(e),c=bytesFromString(n),d=bytesFromString(a),{status_code:l,id:_}=await ditto_live_query_webhook_register_str(t,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(_)}async function tryExperimentalWebhookRegisterDqlLiveQuery(t,e,n,r){ensureInitialized();const i=bytesFromString(e),o=bytesFromString(r),a=await dittoffi_try_experimental_webhook_register_dql_live_query_str(t,i,n,o);throwOnErrorResult(a.error,"dittoffi_try_experimental_webhook_register_dql_live_query_str");return boxCBytesIntoBuffer(a.success)}async function readTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await ditto_read_transaction(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_read_transaction()\` failed with error code: ${e}`);return n}function readTransactionFree(t){return ensureInitialized(),ditto_read_transaction_free(t)}async function writeTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await ditto_write_transaction(t,null);if(0!==e)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${e}`);return n}async function writeTransactionCommit(t,e){ensureInitialized();const n=await ditto_write_transaction_commit(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_commit() failed with error code: ${n}`)}async function writeTransactionRollback(t,e){ensureInitialized();const n=await ditto_write_transaction_rollback(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_rollback() failed with error code: ${n}`)}function staticTCPClientFreeHandle(t){(void 0)(t)}function websocketClientFreeHandle(t){ensureInitialized(),websocket_client_free_handle(t)}function loggerInit(){ensureInitialized(),ditto_logger_init()}async function loggerSetCustomLogCb(t){if(ensureInitialized(),null===t)await ditto_logger_set_custom_log_cb(null);else{const e=wrapBackgroundCbForFFI(null,((e,n)=>{try{const r=boxCStringIntoString(n);t(e,r)}catch(t){log("Error",`The registered cb in \`ditto_logger_set_custom_log_cb()\` failed with: ${t}`)}}));await ditto_logger_set_custom_log_cb(e)}}function loggerEnabled(t){ensureInitialized(),ditto_logger_enabled(!!t)}function loggerEnabledGet(){return ensureInitialized(),!!ditto_logger_enabled_get()}function loggerEmojiHeadingsEnabled(t){ensureInitialized(),ditto_logger_emoji_headings_enabled(t)}function loggerEmojiHeadingsEnabledGet(){return ensureInitialized(),ditto_logger_emoji_headings_enabled_get()}function loggerMinimumLogLevel(t){ensureInitialized(),ditto_logger_minimum_log_level(t)}function loggerMinimumLogLevelGet(){return ensureInitialized(),ditto_logger_minimum_log_level_get()}function loggerSetLogFile(t){ensureInitialized();if(0!==ditto_logger_set_log_file(t?bytesFromString(t):null))throw errorMessage(),new Error(`Can't set log file, due to error: ${errorMessage}`)}function log(t,e){ensureInitialized();ditto_log(t,bytesFromString(e))}function dittoIdentityConfigMakeOnlinePlayground(t,e,n){ensureInitialized();const r=bytesFromString(t),i=bytesFromString(e),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(t,e){ensureInitialized();const n=bytesFromString(t),r=bytesFromString(e),{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(t,e){ensureInitialized();const n=bytesFromString(t),r=Number(e),{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(t,e,n){ensureInitialized();const r=bytesFromString(t),i=bytesFromString(e),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(t){ensureInitialized();const e=bytesFromString(t),{status_code:n,identity_config:r}=ditto_identity_config_make_manual_v0(e);if(0!==n)throw new Error(errorMessage()||`ditto_identity_config_make_manual_v0() failed with error code: ${n}`);return r}function dittoAuthClientGetSiteID(t){return ensureInitialized(),ditto_auth_client_get_site_id(t)}function dittoAuthClientGetAppID(t){ensureInitialized();return boxCStringIntoString(ditto_auth_client_get_app_id(t))}function dittoAuthClientUserID(t){ensureInitialized();return boxCStringIntoString(ditto_auth_client_user_id(t))}function dittoAuthClientIsWebValid(t){return ensureInitialized(),0!==ditto_auth_client_is_web_valid(t)}function dittoAuthClientIsX509Valid(t){return ensureInitialized(),0!==ditto_auth_client_is_x509_valid(t)}async function dittoAuthClientLoginWithToken(t,e,n){ensureInitialized();const r=bytesFromString(e),i=bytesFromString(n),o=await ditto_auth_client_login_with_token(t,r,i);if(0!==o)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${o}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(t,e,n,r){ensureInitialized();const i=bytesFromString(e),o=bytesFromString(n),a=bytesFromString(r),s=await ditto_auth_client_login_with_credentials(t,i,o,a);if(0!==s)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${s}).`)}async function dittoAuthClientLogout(t){ensureInitialized();const e=await ditto_auth_client_logout(t);if(0!==e)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${e}).`)}function uninitializedDittoMake(t){ensureInitialized();return ditto_uninitialized_ditto_make(bytesFromString(t))}function dittoMake(t,e){return ensureInitialized(),ditto_make(t,e,"Disabled")}async function dittoGetCollectionNames(t){ensureInitialized();const e=await ditto_get_collection_names(t),n=e.status_code,r=e.names;if(0!==n)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${n}`);return cStringVecToStringArray(r)}function dittoFree(t){return ensureInitialized(),ditto_free(t)}async function dittoRegisterPresenceV1Callback(t,e){ensureInitialized(),ditto_register_presence_v1_callback(t,wrapBackgroundCbForFFI((t=>log("Error",`The registered presence callback v1 errored with ${t}`)),(t=>{const n=refCStringToString(t);e(n)})))}async function dittoClearPresenceCallback(t){ensureInitialized(),await ditto_clear_presence_callback(t)}async function dittoRegisterPresenceV3Callback(t,e){ensureInitialized(),ditto_register_presence_v3_callback(t,wrapBackgroundCbForFFI((t=>log("Error",`The registered presence callback v3 errored with ${t}`)),(t=>{const n=refCStringToString(t);e(n)})))}async function dittoClearPresenceV3Callback(t){ensureInitialized(),ditto_clear_presence_v3_callback(t)}function dittoSmallPeerInfoGetIsEnabled(t){return ensureInitialized(),ditto_small_peer_info_get_is_enabled(t)}async function dittoSmallPeerInfoSetEnabled(t,e){ensureInitialized(),ditto_small_peer_info_set_enabled(t,e)}async function dittoSmallPeerInfoGetSyncScope(t){return ensureInitialized(),ditto_small_peer_info_get_sync_scope(t)}async function dittoSmallPeerInfoSetSyncScope(t,e){return ensureInitialized(),ditto_small_peer_info_set_sync_scope(t,e)}function dittoSmallPeerInfoGetMetadata(t){ensureInitialized();return boxCStringIntoString(ditto_small_peer_info_get_metadata(t))}function dittoSmallPeerInfoSetMetadata(t,e){ensureInitialized();const n=ditto_small_peer_info_set_metadata(t,bytesFromString(e));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()||`'${e}' 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}`)}}async function dittoSmallPeerInfoCollectionSetTransportConfigData(t,e){ensureInitialized(),ditto_small_peer_info_set_transport_config_data(t,e)}function dittoRegisterTransportConditionChangedCallback(t,e){ensureInitialized(),ditto_register_transport_condition_changed_callback(t,e?wrapBackgroundCbForFFI((t=>log("Error",`The registered "transport condition changed" callback errored with ${t}`)),e):null)}function dittoSetDeviceName(t,e){ensureInitialized();let n=bytesFromString(e);if(n.length>64){n=bytesFromString(e.replace(/[^ -~]+/g,"").substr(0,63))}return ditto_set_device_name(t,n)}function dittoSetConnectRetryInterval(t,e){ensureInitialized();return ditto_set_connect_retry_interval(t,Math.min(Math.max(0,e),4294967295))}function dittoSetSyncGroup(t,e){return ensureInitialized(),ditto_set_sync_group(t,e)}async function dittoNewAttachmentFromBytes(t,e){ensureInitialized();const n={},r=await ditto_new_attachment_from_bytes(t,e,n);if(0!==r)throw new Error(errorMessage()||`ditto_new_attachment_from_bytes() failed with error code: ${r}`);return n}async function dittoResolveAttachment(t,e,n,r){ensureInitialized();const{onComplete:i,onProgress:o,onDelete:a}=n,{status_code:s,cancel_token:c}=await ditto_resolve_attachment(t,e,wrapBackgroundCbForFFI(r,i),wrapBackgroundCbForFFI(r,o),wrapBackgroundCbForFFI(r,a));if(0!==s)throw new Error(errorMessage()||`ditto_resolve_attachment() failed with error code: ${s}`);return c}function dittoCancelResolveAttachment(t,e,n){ensureInitialized();const r=ditto_cancel_resolve_attachment(t,e,n);if(0!==r)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${r}`)}function freeAttachmentHandle(t){ensureInitialized(),ditto_free_attachment_handle(t)}async function dittoGetCompleteAttachmentData(t,e){ensureInitialized();const{status:n,data:r}=await ditto_get_complete_attachment_data(t,e);if(0!==n)throw new Error(errorMessage()||`\`ditto_get_complete_attachment_data()\` failed with error code: ${n}`);return boxCBytesIntoBuffer(r)}function dittoGetSDKVersion(t){ensureInitialized();return boxCStringIntoString(ditto_get_sdk_version())}function dittoGetSDKSemver(){ensureInitialized();return boxCStringIntoString(dittoffi_get_sdk_semver())}function dittoPresenceV1(t){ensureInitialized();return boxCStringIntoString(ditto_presence_v1(t))}function dittoPresenceV3(t){ensureInitialized();return boxCStringIntoString(ditto_presence_v3(t))}function dittoStartTCPServer(t,e){ensureInitialized();return(void 0)(t,bytesFromString(e))}function dittoStopTCPServer(t){return ensureInitialized(),(void 0)(t)}async function dittoShutdown(t){return ensureInitialized(),await ditto_shutdown(t)}function dittoStartHTTPServer(t,e,n,r,i,o){ensureInitialized();return(void 0)(t,bytesFromString(e),bytesFromString(n),r,bytesFromString(i),bytesFromString(o))}function dittoStopHTTPServer(t){return ensureInitialized(),(void 0)(t)}function dittoRunGarbageCollection(t){return ensureInitialized(),ditto_run_garbage_collection(t)}async function dittoDisableSyncWithV3(t){ensureInitialized();const e=await ditto_disable_sync_with_v3(t);if(0!==e)throw new Error(errorMessage()||`ditto_disable_sync_with_v3() failed with error code: ${e}`)}function dittoSetStaticTCPClients(t,e){if(ensureInitialized(),e.length>0)throw new Error(`Web variant of Ditto does not support connecting to TCP servers: ${e.join(", ")}`)}function dittoSetStaticWebsocketClients(t,e,n){ensureInitialized();ditto_set_static_websocket_clients(t,e.map((t=>bytesFromString(t))),n)}function documentsHash(t){ensureInitialized();const{status_code:e,u64:n}=ditto_documents_hash(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash()\` failed with error code: ${e}`);return BigInt(n)}function documentsHashMnemonic(t){ensureInitialized();const{status_code:e,c_string:n}=ditto_documents_hash_mnemonic(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash_mnemonic()\` failed with error code: ${e}`);return boxCStringIntoString(n)}async function dittoAuthSetLoginProvider(t,e){return ensureInitialized(),await ditto_auth_set_login_provider(t,e)}function dittoAuthClientMakeLoginProvider(t,e){return ensureInitialized(),ditto_auth_client_make_login_provider(wrapBackgroundCbForFFI(e,t))}function dittoAuthClientSetValidityListener(t,e,n){ensureInitialized();return ditto_auth_client_set_validity_listener(t,wrapBackgroundCbForFFI(n,(function(t,n){return e(1===t,1===n)})))}function transportsInit(){ensureInitialized();const t=ditto_sdk_transports_error_new(),e=ditto_sdk_transports_init(t),n=ditto_sdk_transports_error_value(t);if(ditto_sdk_transports_error_free(t),!1===e)throw new Error(`Failed to initialize transports (${n} error)`)}function transportsBLEIsAvailable(t){return ensureInitialized(),ditto_sdk_transports_ble_is_available(t)}function transportsLANIsAvailable(t){return ensureInitialized(),ditto_sdk_transports_lan_is_available(t)}function transportsAWDLIsAvailable(t){return ensureInitialized(),ditto_sdk_transports_awdl_is_available(t)}!function(t){t[t.counter=0]="counter",t[t.register=1]="register",t[t.attachment=2]="attachment",t[t.rga=3]="rga",t[t.rwMap=4]="rwMap"}(DittoCRDTType||(DittoCRDTType={}));let withOutPtr,isInitialized$1=!1;async function init$1(t){t?await init$2(t):await init$2(),isInitialized$1=!0,withOutPtr=wrapFFIOutFunction(withOutPtr$1)}function initSDKVersion(t,e,n){ensureInitialized(),bytesFromString(t),bytesFromString(e);const r=ditto_init_sdk_version(t,e,bytesFromString(n));if(void 0!==r&&0!==r)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${r}`)}function verifyLicense(t){ensureInitialized();const e=bytesFromString(t);let n;const r=boxCStringIntoString(withOutPtr("char *",(t=>(n=ditto_verify_license(e,t),t))));return{result:n,errorMessage:r}}const NOT_FOUND_ERROR_CODE=-30798;function wrapBackgroundCbForFFI(t,e){return void 0===t&&(t=t=>log("Error",`The registered callback failed with ${t}`)),(n,...r)=>{let i;try{i=e(...r)}catch(e){try{t(e)}catch(t){log("Error",`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${t}`)}}return n(i)}}function wrapFFIOutFunction(t){return function(...e){let n,r,i=!1;const o=e[e.length-1],a=e.splice(0,e.length-1),s=t(...a,(t=>{try{r=o(t),i=r===t}catch(t){n=t}}));if(n)throw n;return i?s:r}}function bytesFromString(t){if(void 0===t)return;if(null===t)return null;if("string"!=typeof t)throw new Error(`Can't convert string to Uint8Array, not a string: ${t}`);return(new TextEncoder).encode(`${t}\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.")}class AttachmentToken{constructor(t){if(t[DittoCRDTTypeKey]!==DittoCRDTType.attachment)throw new Error("Invalid attachment token");const e=t._id;if(!(e instanceof Uint8Array))throw new Error("Invalid attachment token id");const n=t._len;if("number"!=typeof n||n<0)throw new Error("Invalid attachment token length");const r=t._meta;if("object"!=typeof r)throw new Error("Invalid attachment token meta");this.id=e,this.len=n,this.metadata=r}}const fullBuildVersionString="4.5.4-alpha.1",defaultDittoWasmFileURL="https://software.ditto.live/js/Ditto/4.5.4-alpha.1/ditto.wasm";let isInitialized=!1;async function init(t={}){if(!isInitialized){{const e=t.webAssemblyModule||defaultDittoWasmFileURL;await init$1(e),initSDKVersion("Web","JavaScript","4.5.4-alpha.1"),loggerInit()}isInitialized=!0}}class Logger{static get logFile(){return this._logFile}static setLogFile(t){t?(loggerSetLogFile(t),this._logFile=t):(loggerSetLogFile(void 0),delete this._logFile)}static setLogFileURL(t){var e;this.setLogFile(null!==(e=null==t?void 0:t.pathname)&&void 0!==e?e:null)}static get enabled(){return loggerEnabledGet()}static set enabled(t){loggerEnabled(t)}static get emojiLogLevelHeadingsEnabled(){return loggerEmojiHeadingsEnabledGet()}static set emojiLogLevelHeadingsEnabled(t){loggerEmojiHeadingsEnabled(t)}static get minimumLogLevel(){return loggerMinimumLogLevelGet()}static set minimumLogLevel(t){loggerMinimumLogLevel(t)}static get customLogCallback(){return this._customLogCallback}static async setCustomLogCallback(t){t?(await loggerSetCustomLogCb(t),this._customLogCallback=t):(await loggerSetCustomLogCb(null),delete this._customLogCallback)}static log(t,e){log(t,e)}static error(t){this.log("Error",t)}static warning(t){this.log("Warning",t)}static info(t){this.log("Info",t)}static debug(t){this.log("Debug",t)}static verbose(t){this.log("Verbose",t)}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(t,e){return"function"==typeof Object.is?Object.is(t,e):t===e?0!==t||1/t==1/e:t!=t&&e!=e}function options(t){const e={...CBOR_OPTIONS};return"object"==typeof t&&(e.dictionary=function isDictionary(t){return"string"==typeof t&&["object","map"].includes(t)}(t.dictionary)?t.dictionary:CBOR_OPTIONS.dictionary,e.mode=function isMode(t){return"string"==typeof t&&["loose","strict","sequence"].includes(t)}(t.mode)?t.mode:CBOR_OPTIONS.mode),Object.freeze(e)}function lexicographicalCompare(t,e){const n=Math.min(t.byteLength,e.byteLength);for(let r=0;r<n;r++){const n=t[r]-e[r];if(0!==n)return n}return t.byteLength-e.byteLength}var _Sequence_instances,_Sequence_toInspectString,__classPrivateFieldGet=function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)};class Sequence{static from(t){return new Sequence(Array.from(t))}constructor(t){_Sequence_instances.add(this),Object.defineProperty(this,"_data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._data=t||[]}add(t){return this._data.push(t)-1}remove(t){return this._data.splice(t,1)[0]}get(t){return this._data[t]}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(t){return`${this[Symbol.toStringTag]()}(${this.size}) ${t(this._data)}`},Symbol.for("Deno.customInspect"))](t){return __classPrivateFieldGet(this,_Sequence_instances,"m",_Sequence_toInspectString).call(this,t)}[Symbol.for("nodejs.util.inspect.custom")](t,e,n){return __classPrivateFieldGet(this,_Sequence_instances,"m",_Sequence_toInspectString).call(this,n)}}class SimpleValue{static create(t){if(void 0===t)return new SimpleValue(23);if(null===t)return new SimpleValue(22);if(!0===t)return new SimpleValue(21);if(!1===t)return new SimpleValue(20);if("number"==typeof t&&t>=0&&t<=255)return new SimpleValue(t);throw new Error("CBORError: Value out of range or not a simple value.")}constructor(t){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===t:this.semantic="false";break;case 21===t:this.semantic="true";break;case 22===t:this.semantic="null";break;case 23===t:this.semantic="undefined";break;case t>23&&t<32:this.semantic="reserved";break;default:this.semantic="unassigned"}this.value=t}toPrimitive(){switch(this.semantic){case"false":return!1;case"true":return!0;case"null":return null;default:return}}}class TaggedValue{constructor(t,e){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=t,this.tag=e}}function decode(t,e,n={}){const{dictionary:r,mode:i}=options(n),o="sequence"===i||"strict"===i,a=new DataView(t),s=new Uint8Array(t);let c=0,reviverFunction=function(t,e){return e};function commitRead(t,e){return c+=t,e}function readArrayBuffer(e){return commitRead(e,new Uint8Array(t,c,e))}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(t){if(t<24)return t;if(24===t)return readUint8();if(25===t)return readUint16();if(26===t)return function readUint32(){return commitRead(4,a.getUint32(c))}();if(27===t){const t=function readUint64(){return commitRead(8,a.getBigUint64(c))}();return t<POW_2_53?Number(t):t}if(31===t)return-1;throw new Error("CBORError: Invalid length encoding")}function readIndefiniteStringLength(t){const e=readUint8();if(255===e)return-1;const n=readLength(31&e);if(n<0||e>>5!==t)throw new Error("CBORError: Invalid indefinite length element");return Number(n)}function appendUtf16Data(t,e){for(let n=0;n<e;++n){let n=readUint8();128&n&&(n<224?(n=(31&n)<<6|63&readUint8(),e-=1):n<240?(n=(15&n)<<12|(63&readUint8())<<6|63&readUint8(),e-=2):(n=(15&n)<<18|(63&readUint8())<<12|(63&readUint8())<<6|63&readUint8(),e-=3)),n<65536?t.push(n):(n-=65536,t.push(55296|n>>10),t.push(56320|1023&n))}}function decodeItem(){const t=readUint8(),e=t>>5,n=31&t;let i,s;if(7===e)switch(n){case 25:return function readFloat16(){const t=new ArrayBuffer(4),e=new DataView(t),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 e.setUint32(0,r<<16|i<<13|o<<13),e.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&&(e<2||6<e))throw new Error("CBORError: Invalid length");switch(e){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 t=[];let n=0;for(;(s=readIndefiniteStringLength(e))>=0;)n+=s,t.push(readArrayBuffer(s));const r=new Uint8Array(n);let o=0;for(i=0;i<t.length;++i)r.set(t[i],o),o+=t[i].length;return reviverFunction(EMPTY_KEY,r)}return reviverFunction(EMPTY_KEY,readArrayBuffer(s));case 3:{const t=[];if(s<0)for(;(s=readIndefiniteStringLength(e))>=0;)appendUtf16Data(t,s);else appendUtf16Data(t,s);let n="";for(i=0;i<t.length;i+=DECODE_CHUNK_SIZE)n+=String.fromCharCode.apply(null,t.slice(i,i+DECODE_CHUNK_SIZE));return reviverFunction(EMPTY_KEY,n)}case 4:{let t;if(s<0){t=[];let e=0;for(;!readBreak();)t.push(reviverFunction(e++,decodeItem()))}else for(t=new Array(s),i=0;i<s;++i)t[i]=reviverFunction(i,decodeItem());return reviverFunction(EMPTY_KEY,t)}case 5:{if("map"===r){const t=new Map;for(i=0;i<s||s<0&&!readBreak();++i){const e=decodeItem();if(o&&t.has(e))throw new Error("CBORError: Duplicate key encountered");t.set(e,reviverFunction(e,decodeItem()))}return reviverFunction(EMPTY_KEY,t)}const t={};for(i=0;i<s||s<0&&!readBreak();++i){const e=decodeItem();if(o&&Object.prototype.hasOwnProperty.call(t,e))throw new Error("CBORError: Duplicate key encountered");t[e]=reviverFunction(e,decodeItem())}return reviverFunction(EMPTY_KEY,t)}case 6:{const t=decodeItem(),e=s;if(t instanceof Uint8Array){const n=t.buffer.slice(t.byteOffset,t.byteLength+t.byteOffset);switch(e){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(t,e))}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 e&&(reviverFunction=e);const d=decodeItem();if(c!==t.byteLength){if("sequence"!==i)throw new Error("CBORError: Remaining bytes");const e=new Sequence([d]);for(;c<t.byteLength;)e.add(reviverFunction(EMPTY_KEY,decodeItem()));return e}return"sequence"===i?new Sequence([d]):d}function parse(t,e,n){return decode(t,e,n)}function encode(t,e){let n,r=new ArrayBuffer(256),i=new DataView(r),o=new Uint8Array(r),a=0,replacerFunction=(t,e)=>e;if("function"==typeof e&&(replacerFunction=e),Array.isArray(e)){const t=e.slice();replacerFunction=(e,n)=>e===EMPTY_KEY||t.includes(e)?n:OMIT_VALUE}function prepareWrite(t){let e=r.byteLength;const s=a+t;for(;e<s;)e<<=1;if(e!==r.byteLength){const t=i;r=new ArrayBuffer(e),i=new DataView(r),o=new Uint8Array(r);const n=a+3>>2;for(let e=0;e<n;++e)i.setUint32(e<<2,t.getUint32(e<<2))}return n=t,i}function commitWrite(...t){a+=n}function writeUint8(t){commitWrite(prepareWrite(1).setUint8(a,t))}function writeUint8Array(t){prepareWrite(t.length),o.set(t,a),commitWrite()}function writeUint16(t){commitWrite(prepareWrite(2).setUint16(a,t))}function writeUint32(t){commitWrite(prepareWrite(4).setUint32(a,t))}function writeUint64(t){const e=t%POW_2_32,n=(t-e)/POW_2_32,r=prepareWrite(8);r.setUint32(a,n),r.setUint32(a+4,e),commitWrite()}function writeBigUint64(t){commitWrite(prepareWrite(8).setBigUint64(a,t))}function writeVarUint(t,e){t<=255?t<24?writeUint8(Number(t)|e):(writeUint8(24|e),writeUint8(Number(t))):t<=65535?(writeUint8(25|e),writeUint16(Number(t))):t<=4294967295?(writeUint8(26|e),writeUint32(Number(t))):(writeUint8(27|e),"number"==typeof t?writeUint64(t):writeBigUint64(t))}function writeTypeAndLength(t,e){e<24?writeUint8(t<<5|e):e<256?(writeUint8(t<<5|24),writeUint8(e)):e<65536?(writeUint8(t<<5|25),writeUint16(e)):e<4294967296?(writeUint8(t<<5|26),writeUint32(e)):(writeUint8(t<<5|27),writeUint64(e))}function encodeItem(t){if(t!==OMIT_VALUE){if(!1===t)return writeUint8(244);if(!0===t)return writeUint8(245);if(null===t)return writeUint8(246);if(void 0===t)return writeUint8(247);if(objectIs(t,-0))return writeUint8Array([249,128,0]);switch(typeof t){case"bigint":return function writeBigInteger(t){let e=0;if(0<=t&&t<=MAX_SAFE_INTEGER)e=0;else{if(!(-MAX_SAFE_INTEGER<=t&&t<0))throw new Error("CBORError: Encountered unsafe integer outside of valid CBOR range.");e=1,t=-(t+1n)}if(t<0x100000000n)return writeTypeAndLength(e,Number(t));writeUint8(e<<5|27),writeBigUint64(t)}(t);case"number":if(Math.floor(t)===t){if(0<=t&&t<=POW_2_53)return writeTypeAndLength(0,t);if(-POW_2_53<=t&&t<0)return writeTypeAndLength(1,-(t+1))}return writeUint8(251),function writeFloat64(t){commitWrite(prepareWrite(8).setFloat64(a,t))}(t);case"string":{const e=[],n=t.length;for(let r=0;r<n;++r){let n=t.charCodeAt(r);n<128?e.push(n):n<2048?(e.push(192|n>>6),e.push(128|63&n)):n<55296||n>=57344?(e.push(224|n>>12),e.push(128|n>>6&63),e.push(128|63&n)):(n=(1023&n)<<10,n|=1023&t.charCodeAt(++r),n+=65536,e.push(240|n>>18),e.push(128|n>>12&63),e.push(128|n>>6&63),e.push(128|63&n))}return writeTypeAndLength(3,e.length),writeUint8Array(e)}default:{let e;if(Array.isArray(t))!function writeArray(t){const e=a,n=t.length;let r=0;writeTypeAndLength(4,n);const i=a;for(let e=0;e<n;e+=1){const n=replacerFunction(e,t[e]);n!==OMIT_VALUE&&(encodeItem(n),r+=1)}if(n>r){const t=o.slice(i,a);a=e,writeTypeAndLength(4,r),writeUint8Array(t)}}(t);else if(t instanceof Uint8Array)writeVarUint(kCborTagUint8,kCborTag<<5),writeTypeAndLength(2,t.length),writeUint8Array(t);else if(t instanceof Int8Array)writeVarUint(kCborTagInt8,kCborTag<<5),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Uint16Array)writeVarUint(kCborTagUint16,kCborTag<<5),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Int16Array)writeVarUint(kCborTagInt16,kCborTag<<5),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Uint32Array)writeVarUint(kCborTagUint32,kCborTag<<5),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Int32Array)writeVarUint(kCborTagInt32,kCborTag<<5),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Float32Array)writeVarUint(kCborTagFloat32,kCborTag<<5),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(t instanceof Float64Array)writeVarUint(kCborTagFloat64,kCborTag<<5),writeTypeAndLength(2,t.byteLength),writeUint8Array(new Uint8Array(t.buffer));else if(ArrayBuffer.isView(t))e=new Uint8Array(t.buffer),writeTypeAndLength(2,e.length),writeUint8Array(e);else if(t instanceof ArrayBuffer||"function"==typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer)e=new Uint8Array(t),writeTypeAndLength(2,e.length),writeUint8Array(e);else if(t instanceof TaggedValue)writeVarUint(t.tag,192),encodeItem(t.value);else if(t instanceof SimpleValue)writeTypeAndLength(7,t.value);else if(t instanceof Sequence){if(0!==a)throw new Error("CBORError: A CBOR Sequence may not be nested.");const e=t.size;for(let n=0;n<e;n+=1)encodeItem(t.get(n))}else!function writeDictionary(t){const e=[],n=a;let r=a,i=0,s=0;if(t instanceof Map){i=t.size,writeTypeAndLength(5,i),r=a;for(const[n,r]of t.entries()){const t=replacerFunction(n,r);if(t===OMIT_VALUE)continue;let i=a;encodeItem(n);const c=o.slice(i,a);i=a,encodeItem(t);const d=o.slice(i,a);s+=1,e.push([c,d])}}else{const n=Object.keys(t);i=n.length,writeTypeAndLength(5,i),r=a;for(let r=0;r<i;r+=1){const i=n[r],c=replacerFunction(i,t[i]);if(c===OMIT_VALUE)continue;let d=a;encodeItem(i);const l=o.slice(d,a);d=a,encodeItem(c);const _=o.slice(d,a);s+=1,e.push([l,_])}}function sortEncodedKeys(t){a=n,writeTypeAndLength(5,s),e.sort((([t],[e])=>lexicographicalCompare(t,e)));for(let n=0;n<t;n+=1){const[t,r]=e[n];writeUint8Array(t),writeUint8Array(r)}}if(i>s){const t=e.length;if(t>1)sortEncodedKeys(t);else{const t=o.slice(r,a);a=n,writeTypeAndLength(5,s),writeUint8Array(t)}}else{const t=e.length;t>1&&sortEncodedKeys(t)}}(t)}}}}if(encodeItem(replacerFunction(EMPTY_KEY,t)),"slice"in r)return r.slice(0,a);const s=new ArrayBuffer(a),c=new DataView(s);for(let t=0;t<a;++t)c.setUint8(t,i.getUint8(t));return s}function binarify(t,e){return encode(t,e)}const CBOR$1={binarify:binarify,decode:decode,encode:encode,parse:parse};class CBOR{static encode(t,e){const n=CBOR$1.encode(t,e);return new Uint8Array(n)}static decode(t,e){const n=t.buffer;return CBOR$1.decode(n,e)}}function documentIDReplacer(t,e){return e instanceof DocumentID?e.toString():e}class DocumentID{get value(){let t=this["@ditto.value"];return void 0===t&&(t=CBOR.decode(this["@ditto.cbor"]),this["@ditto.value"]=t),t}constructor(t,e=!1,n=!1){const r=e?t:CBOR.encode(t),i=n?r:validateDocumentIDCBOR(r);if(!i)throw new Error(`Can't create DocumentID, passed in value is not valid: ${t}`);this.isValidated=!n,this["@ditto.cbor"]=i}equals(t){const e=this["@ditto.cbor"],n=t["@ditto.cbor"];if(e===n)return!0;if(!(e instanceof Uint8Array))return!1;if(!(n instanceof Uint8Array))return!1;if(e.length!==n.length)return!1;for(let t=0;t<e.length;t+=1)if(e[t]!==n[t])return!1;return!0}toString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithoutQuotes")}toBase64String(){const t=this["@ditto.cbor"];return btoa(String.fromCharCode.apply(null,t))}toQueryCompatibleString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithQuotes")}toCBOR(){return this["@ditto.cbor"]}}function validateDocumentIDValue(t){if(void 0===t)throw new Error(`Invalid document ID: ${t}`);return t}function validateDocumentIDCBOR(t){const e=validateDocumentID(t);return null!=e?e:t}const DEBUG_TYPE_NAMES=[],DEBUG_ALL_TYPES=!1;class Handle{constructor(t,e,n){this.isClosed=!1,this.isFinalized=!1,this.isUnregistered=!1,this.bridge=t,this.objectWeakRef=new WeakRef(e),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 t;return this.isClosed||this.isFinalized||this.isUnregistered?null:null!==(t=this.pointer)&&void 0!==t?t:null}object(){const t=this.objectWeakRef.deref();if(null==t)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 t}objectOrNull(){var t;return null!==(t=this.objectWeakRef.deref())&&void 0!==t?t:null}toString(){const t=this.derefOrNull();return`{ Handle | type: ${this.bridge.type}, object: ${this.objectWeakRef.deref()}, FFI address: ${null==t?void 0:t.addr}, FFI type: ${null==t?void 0:t.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(t,e){this.handles=e.map((e=>t.handleFor(e)))}deref(){return this.handles.map((t=>t.deref()))}}class Bridge{constructor(t){this.internalType=null,this.release=t,this.handlesByAddress={},this.handlesByObject=new WeakMap,this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this)),Bridge.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(t){if(this.internalType!==t){if(this.internalType)throw new Error(`Can't register bridged type '${t.name}', another type was already registered: ${this.internalType}`);this.internalType=t}}handleFor(t){const e=this.handlesByObject.get(t);if(null==e)throw new Error(`Bridging error: ${this.type.name} object is not currently registered in this bridge.`);return e}handlesFor(t){return new Handles(this,t)}objectFor(t){const e=this.handlesByAddress[t.addr];if(e){if(e.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${e.type} but this bridge is configured for ${this.type}`);return e.object()}}bridge(t,e){const n=this.objectFor(t);if(n)return n;let r;if(e||(e=()=>Reflect.construct(this.type,[])),"function"==typeof e){if(r=e(),!(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=e;return this.register(r,t),r}register(t,e){const n=t.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(t),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} ${t}`);const o=new Handle(this,t,e);this.handlesByAddress[e.addr]=o,this.handlesByObject.set(t,o),this.finalizationRegistry.register(t,o,t),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(t){const e=t.constructor,n=this.type;if(e!==n)throw new Error(`Can't unregister, bridge is configured for type ${n.name} but passed in object is of type ${e.name}`);const r=this.handlesByObject.get(t);if(null==r)throw new Error(`Can't unregister, object has not been registered before: ${t}`);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()!==t)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: ${t}`);if(r.isFinalized)throw new Error(`Can't unregister, object has been finalized before: ${t}`);if(r.isUnregistered)throw new Error(`Can't unregister, object has been unregistered already: ${t}`);r.bridgeWillUnregister(),this.finalizationRegistry.unregister(t),delete this.handlesByAddress[r.pointer.addr],this.handlesByObject.delete(t),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 t of Object.values(this.handlesByAddress)){const e=t.object();e&&this.unregister(e)}}async close(t){const e=t.constructor,n=this.type;if(e!==n)throw new Error(`Can't close, bridge is configured for type ${n.name} but passed in object is of type ${e.name}`);const r=this.handlesByObject.get(t);if(null==r)throw new Error(`Can't close an object that has not been registered before: ${t}`);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(t){if(t.isFinalized)throw new Error("Internal inconsistency, trying to finalize an object that has already been finalized.");if(t.isUnregistered)throw new Error("Internal inconsistency, trying to finalize an object that has been unregistered before.");if(t.bridgeWillFinalize(),!t.isClosed){const e=t.pointer;if(!e)throw new Error("Internal inconsistency, trying to finalize an object whose pointer is null.");delete this.handlesByAddress[e.addr],await this.release(e)}t.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}`)}}Bridge.all=[],Bridge.attachment=new Bridge(freeAttachmentHandle),Bridge.document=new Bridge(documentFree),Bridge.mutableDocument=new Bridge(documentFree),Bridge.dqlResponse=new Bridge(dqlResponseFree),Bridge.dqlResult=new Bridge(dqlResultFree),Bridge.staticTCPClient=new Bridge(staticTCPClientFreeHandle),Bridge.websocketClient=new Bridge(websocketClientFreeHandle),Bridge.ditto=new Bridge((async t=>{dittoClearPresenceCallback(t),await dittoShutdown(t),dittoFree(t)}));class UpdateResult{static set(t,e,n){return new UpdateResult("set",t,e,n,void 0)}static incremented(t,e,n){return new UpdateResult("incremented",t,e,void 0,n)}static removed(t,e){return new UpdateResult("removed",t,e,void 0,void 0)}constructor(t,e,n,r,i){this.type=t,this.docID=e,this.path=n,void 0!==r&&(this.value=r),void 0!==i&&(this.amount=i)}}class Attachment{get metadata(){return this.token.metadata}getData(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return this.ditto.deferCloseAsync((async()=>{{const t=Bridge.attachment.handleFor(this);return await dittoGetCompleteAttachmentData(e.deref(),t.deref())}}))}copyToPath(t){const e=this.ditto;return Bridge.ditto.handleFor(e),this.ditto.deferCloseAsync((async()=>{throw new Error("Can't copy attachment to path, not available when running in the browser.")}))}constructor(t,e){this.ditto=t,this.token=e}}function augmentJSONValue(t,e,n){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,r)=>augmentJSONValue(t,e,`${n}[${r}]`)));if(t[DittoCRDTTypeKey]===DittoCRDTType.counter)return Counter["@ditto.create"](e,n,t._value);if(t[DittoCRDTTypeKey]===DittoCRDTType.register)return Register["@ditto.create"](e,n,t._value);if(t[DittoCRDTTypeKey]===DittoCRDTType.attachment)return new AttachmentToken(t);for(const[r,i]of Object.entries(t))t[r]=augmentJSONValue(i,e,`${n}['${r}']`);return t}return t}function desugarJSObject(t,e=!1){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,e)=>desugarJSObject(t,!1)));if(t instanceof DocumentID)return t.value;if(t instanceof Counter){const e={};return e[DittoCRDTTypeKey]=DittoCRDTType.counter,e._value=t.value,e}if(t instanceof Register){const e={};return e[DittoCRDTTypeKey]=DittoCRDTType.register,e._value=t.value,e}if(t instanceof Attachment){const e={_id:t.token.id,_len:t.token.len,_meta:t.token.metadata};return e[DittoCRDTTypeKey]=DittoCRDTType.attachment,e}for(const[e,n]of Object.entries(t))t[e]=desugarJSObject(n,!1);return t}return checkForUnsupportedValues(t),t}function checkForUnsupportedValues(t){if(Number.isNaN(t)||t===1/0||t===-1/0)throw new Error("Non-finite float values are not supported")}const defaultDittoCloudDomain="cloud.ditto.live";function defaultAuthURL(t){return`https://${t}.${defaultDittoCloudDomain}`}function defaultDittoCloudURL(t){return`wss://${t}.${defaultDittoCloudDomain}`}function validateNumber(t,e={}){var n;const r=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Number validation failed:",i=!!e.integer,o=e.min,a=e.max,s=e.minX,c=e.maxX;if("number"!=typeof t)throw new Error(`${r} '${t}' is not a number.`);if(i&&Math.floor(t)!==t)throw new Error(`${r} '${t}' is not an integer.`);if(void 0!==o&&t<o)throw new Error(`${r} '${t}' must be >= ${o}.`);if(void 0!==a&&t>a)throw new Error(`${r} '${t}' must be <= ${a}.`);if(void 0!==s&&t<=s)throw new Error(`${r} '${t}' must be > ${s}.`);if(void 0!==c&&t>=c)throw new Error(`${r} '${t}' must be < ${c}.`);return t}function validateQuery(t,e={}){var n;const r=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Query validation failed,";if("string"!=typeof t)throw new Error(`${r} query is not a string: ${t}`);if(""===t)throw new Error(`${r} query is an empty string.`);const i=t.trim();if(""===i)throw new Error(`${r} query contains only whitespace characters.`);return i}function generateEphemeralToken(){let t,e=new Uint16Array(16);t=crypto,t.getRandomValues(e);return Array.from(e).map((t=>t.toString(16))).join("")}function sleep(t){return new Promise(((e,n)=>{setTimeout(e,t)}))}async function step(t){return await sleep(0),t()}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(t){if("number"==typeof t)return t;if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);return"string"==typeof t&&!!t.match(/^[A-Za-z_]/)?`.${t}`:t}static withoutLeadingDot(t){if("number"==typeof t)return t;if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);return"string"==typeof t&&!!t.match(/^\./)?t.slice(1):t}static validate(t,e={}){var n;const r=null!==(n=e.isInitial)&&void 0!==n&&n;if("number"==typeof t)return Math.floor(Math.abs(t));if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);const i=this.withLeadingDot(t);if(!validKeyPathRegExp.test(i))throw new Error(`Key-path is not valid: ${t}`);return r?t:i}static evaluate(t,e,n={}){var r;const i=null!==(r=n.stopAtLastContainer)&&void 0!==r&&r,o={keyPath:t,object:e,options:{...n},coveredPath:null,nextPathComponent:null,remainingPath:t,value:e};return function recurse(t,e){if(""===e)return o.value=t,o;const{nextPathComponentRaw:n,nextPathComponent:r,remainingPath:a}=function advance(t){if("number"==typeof t)return{nextPathComponentRaw:t,nextPathComponent:t,remainingPath:""};if("string"!=typeof t)throw new Error(`Can't return value at given keyPath, expected keyPath to be a string or a number but got ${typeof t}: ${t}`);const e=t.match(regularKeyRegExp);if(null!==e){const n=e[0],r=e[1];return{nextPathComponentRaw:n,nextPathComponent:r,remainingPath:t.slice(r.length+1)}}const n=t.match(subscriptIndexRegExp);if(null!==n){const e=n[0],r=n[1];return{nextPathComponentRaw:e,nextPathComponent:parseInt(r),remainingPath:t.slice(r.length+2)}}const r=t.match(subscriptSingleQuoteKeyRegExp);if(null!==r){const e=r[0],n=r[1];return{nextPathComponentRaw:e,nextPathComponent:n,remainingPath:t.slice(n.length+4)}}const i=t.match(subscriptDoubleQuoteKeyRegExp);if(null!==i){const e=i[0],n=i[1];return{nextPathComponentRaw:e,nextPathComponent:n,remainingPath:t.slice(n.length+4)}}throw new Error(`Can't return value at keyPath because the following part of the keyPath is invalid: ${t}`)}(e);return o.nextPathComponent=r,o.remainingPath=a,null===o.coveredPath||"number"==typeof n?o.coveredPath=n:o.coveredPath+=n,""===a&&i?(o.value=t,o):recurse(t[r],a)}(e,this.withLeadingDot(t))}constructor(){}}class DocumentPath{at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e),r=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new DocumentPath(this.document,r,!1)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"DocumentPath.at() validation failed index:"});return new DocumentPath(this.document,`${this.path}[${e.toString()}]`,!1)}throw new Error(`Can't return document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const t=this.underlyingValueForPathType("Counter");return void 0!==t?Counter["@ditto.create"](null,this.path,t):null}get register(){const t=this.underlyingValueForPathType("Register");return void 0!==t?Register["@ditto.create"](null,this.path,t):null}get attachmentToken(){const t=this.underlyingValueForPathType("Attachment");return void 0!==t?new AttachmentToken(t):null}constructor(t,e,n){this.document=t,this.path=n?KeyPath.validate(e,{isInitial:!0}):e}underlyingValueForPathType(t){const e=this.path,n=this.document,r=documentGetCBORWithPathType(Bridge.document.handleFor(n).deref(),e,t);return null!==r.cbor?CBOR.decode(r.cbor):void 0}}class MutableDocumentPath{at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e),r=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new MutableDocumentPath(this.mutableDocument,r,!1)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"MutableDocumentPath.at() validation failed index:"});return new MutableDocumentPath(this.mutableDocument,`${this.path}[${e.toString()}]`,!1)}throw new Error(`Can't return mutable document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const t=this.underlyingValueForPathType("Counter");return void 0!==t?Counter["@ditto.create"](this.mutableDocument,this.path,t):null}get register(){const t=this.underlyingValueForPathType("Register");return void 0!==t?Register["@ditto.create"](this.mutableDocument,this.path,t):null}get attachmentToken(){const t=this.underlyingValueForPathType("Attachment");return void 0!==t?new AttachmentToken(t):null}set(t,e){return this["@ditto.set"](t,e)}remove(){return this["@ditto.remove"]()}constructor(t,e,n){this.mutableDocument=t,this.path=n?KeyPath.validate(e,{isInitial:!0}):e}underlyingValueForPathType(t){const e=this.path,n=this.mutableDocument,r=documentGetCBORWithPathType(Bridge.mutableDocument.handleFor(n).deref(),e,t);return null!==r.cbor?CBOR.decode(r.cbor):void 0}"@ditto.increment"(t){documentIncrementCounter(Bridge.mutableDocument.handleFor(this.mutableDocument).deref(),this.path,t);const e=UpdateResult.incremented(this.mutableDocument.id,this.path,t);this.recordUpdateResult(e)}"@ditto.set"(t,e){const n=Bridge.mutableDocument.handleFor(this.mutableDocument),r=desugarJSObject(t,!1),i=CBOR.encode(r);e?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(((t,e)=>{Array.isArray(t)&&"number"==typeof e?t.splice(e,1):delete t[e]}));const t=UpdateResult.removed(this.mutableDocument.id,this.path);this.recordUpdateResult(t)}updateInMemory(t){const e=this.mutableDocument.value,n=KeyPath.evaluate(this.path,e,{stopAtLastContainer:!0});t(n.value,n.nextPathComponent)}recordUpdateResult(t){const e=this.mutableDocument["@ditto.updateResults"].slice();e.push(t),Object.freeze(e),this.mutableDocument["@ditto.updateResults"]=e}}class Document{static hash(t){return documentsHash(documentsFrom(t).map((t=>Bridge.document.handleFor(t))).map((t=>t.deref())))}static hashMnemonic(t){const e=documentsFrom(t);return documentsHashMnemonic(Bridge.document.handlesFor(e).deref())}get id(){let t=this["@ditto.id"];if(void 0===t){const e=documentID(Bridge.document.handleFor(this).deref());t=new DocumentID(e,!0),this["@ditto.id"]=t}return t}get path(){return new DocumentPath(this,"",!1)}get value(){let t=this["@ditto.value"];return void 0===t&&(t=this.path.value,this["@ditto.value"]=t),t}at(t){return this.path.at(t)}constructor(){}static idCBOR(t){return documentID(Bridge.document.handleFor(t).deref())}static canonicalizedIDCBOR(t){return validateDocumentIDCBOR(t)}static isIDCBORCanonical(t){return t===this.canonicalizedIDCBOR(t)}}class MutableDocument{get id(){let t=this["@ditto.id"];if(void 0===t){const e=documentID(Bridge.mutableDocument.handleFor(this).deref());t=new DocumentID(e,!0),this["@ditto.id"]=t}return t}get path(){return new MutableDocumentPath(this,"",!1)}get value(){return this.path.value}at(t){return this.path.at(t)}constructor(){this["@ditto.updateResults"]=[]}static idCBOR(t){return documentID(Bridge.mutableDocument.handleFor(t).deref())}}function documentsFrom(t){if(!t)return[];if(t instanceof Document)return[t];if(t instanceof Array)return t;throw new Error(`Expected null, a single document, or an array of documents but got value of type ${typeof t}: ${t}`)}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR,MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;class UpdateResultsMap{get(t){const e=(t instanceof DocumentID?t:new DocumentID(t)).toString();return this.updateResultsByDocumentIDString[e]}keys(){return this.documentIDs.slice()}constructor(t,e){const n=t.map((t=>t.toString())).sort().join(", ");if(n!==Object.keys(e).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=t.slice(),this.updateResultsByDocumentIDString={...e}}}class BasePendingCursorOperation{sort(t,e="ascending"){return this.orderBys.push({query:t,direction:"ascending"===e?"Ascending":"Descending"}),this}offset(t){if(t<0)throw new Error(`Can't offset by '${t}', offset must be >= 0`);if(!Number.isFinite(t))throw new Error(`Can't offset by '${t}', offset must be a finite number`);if(Number.isNaN(t))throw new Error(`Can't offset by '${t}', offset must be a valid number`);if(t!==Math.round(t))throw new Error(`Can't offset by '${t}', offset must be an integer number`);return this.currentOffset=t,this}limit(t){if(t<-1)throw new Error(`Can't limit to '${t}', limit must be >= -1 (where -1 means unlimited)`);if(!Number.isFinite(t))throw new Error(`Can't limit to '${t}', limit must be a finite number`);if(Number.isNaN(t))throw new Error(`Can't limit to '${t}', limit must be a valid number`);if(t!==Math.round(t))throw new Error(`Can't limit to '${t}', limit must be an integer number`);return this.currentLimit=t,this}async exec(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query;return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionExecQueryStr(e.deref(),this.collection.name,null,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((t=>Bridge.document.bridge(t)))}))}async updateWithTransaction(t,e){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,e,n,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset),o=i.map((t=>Bridge.mutableDocument.bridge(t,(()=>new MutableDocument))));t(o);const a=[],s={};for(const t of o){const e=t.id,n=e.toString(),r=t["@ditto.updateResults"];if(s[n])throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${n}`);a.push(e),s[n]=r,Bridge.mutableDocument.unregister(t)}return await collectionUpdateMultiple(r.deref(),this.collection.name,e,i),new UpdateResultsMap(a,s)}))))}constructor(t,e,n){this.currentLimit=-1,this.currentOffset=0,this.orderBys=[],this.query=validateQuery(t),this.queryArgs=e?Object.freeze({...e}):null,this.collection=n,this.queryArgsCBOR=e?CBOR.encode(e):null}then(t,e){return this.exec().then(t,e)}}class BasePendingIDSpecificOperation{async exec(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const t=await readTransaction(e.deref()),n=await collectionGet(e.deref(),this.collection.name,this.documentIDCBOR,t);let r;return n&&(r=Bridge.document.bridge(n)),readTransactionFree(t),r}))))}constructor(t,e){this.documentID=t,this.collection=e,this.documentIDCBOR=t.toCBOR()}then(t,e){return this.exec().then(t,e)}get query(){return`_id == ${this.documentID.toQueryCompatibleString()}`}}class ObserverManager{constructor(t,e={}){var n,r,i,o;const a=null!==(n=e.keepAlive)&&void 0!==n?n:null,s=null!==(r=e.register)&&void 0!==r?r:null,c=null!==(i=e.unregister)&&void 0!==i?i:null,d=null!==(o=e.process)&&void 0!==o?o:null;this.id=t,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(t){var e;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]=t,null===(e=this.keepAlive)||void 0===e||e.retain(`${this.id}.${n}`),n}removeObserver(t){var e;const n=this.callbacksByToken[t];if(void 0===n)throw new Error(`Can't remove '${this.id}' observer, token '${t}' has never been registered before.`);null!==n&&(this.callbacksByToken[t]=null,null===(e=this.keepAlive)||void 0===e||e.release(`${this.id}.${t}`),this.unregisterIfNeeded())}hasObserver(t){return void 0!==this.callbacksByToken[t]}notify(...t){if(this.isClosed)return;const e=this.process(...t);for(const t in this.callbacksByToken){const n=this.callbacksByToken[t];n&&n(...e)}}close(){this.isClosed=!0;for(const t in this.callbacksByToken)this.removeObserver(t)}register(t){}unregister(){}process(...t){return t}hasObservers(){return Object.keys(this.callbacksByToken).length>0}registerIfNeeded(){if(!this.isRegistered){const t=new WeakRef(this);this.isRegistered=!0,this.register((function(...e){const n=t.deref();n&&n.notify(...e)}))}}unregisterIfNeeded(){!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,this.unregister())}}class Authenticator{get status(){return this._status}loginWithToken(t,e){throw new Error("Authenticator.loginWithToken() is abstract and must be implemented by subclasses.")}loginWithUsernameAndPassword(t,e,n){throw new Error("Authenticator.loginWithUsernameAndPassword() is abstract and must be implemented by subclasses.")}logout(t){throw new Error("Authenticator.logout() is abstract and must be implemented by subclasses.")}observeStatus(t){const e=this.observerManager.addObserver(t);return new Observer(this.observerManager,e,{stopsWhenFinalized:!0})}constructor(t){this.keepAlive=t,this._status={isAuthenticated:!1,userID:null},this.loginSupported=!1,this.observerManager=new ObserverManager("AuthenticationStatusObservation",{keepAlive:t})}"@ditto.authenticationExpiring"(t){throw new Error("Authenticator['@ditto.authenticationExpiring']() is abstract and must be implemented by subclasses.")}"@ditto.authClientValidityChanged"(t,e){throw new Error("Authenticator['@ditto.authClientValidityChanged']() is abstract and must be implemented by subclasses.")}close(){this.observerManager.close()}}class OnlineAuthenticator extends Authenticator{async loginWithToken(t,e){const n=this.ditto.deref();if(!n)return;const r=Bridge.ditto.handleFor(n).derefOrNull();return r?n.deferCloseAsync((async()=>{await dittoAuthClientLoginWithToken(r,t,e)})):void 0}async loginWithUsernameAndPassword(t,e,n){const r=this.ditto.deref();if(!r)return;const i=Bridge.ditto.handleFor(r).derefOrNull();return i?r.deferCloseAsync((async()=>{await dittoAuthClientLoginWithUsernameAndPassword(i,t,e,n)})):void 0}async logout(t){const e=this.ditto.deref();if(!e)return;const n=Bridge.ditto.handleFor(e).derefOrNull();return n?e.deferCloseAsync((async()=>{await dittoAuthClientLogout(n),e.stopSync(),null==t||t(e)})):void 0}constructor(t,e,n){super(t),this.loginSupported=!0,this._status={isAuthenticated:!1,userID:null},this.ditto=new WeakRef(e),this.authenticationHandler=n,this.updateAndNotify(!1)}"@ditto.authenticationExpiring"(t){const e=this.authenticationHandler;t>0?e.authenticationExpiringSoon(this,t):e.authenticationRequired(this)}"@ditto.authClientValidityChanged"(t,e){this.updateAndNotify(!0)}updateAndNotify(t){var e;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,t){!!i==!!a&&o===s||(null===(e=this.authenticationHandler.authenticationStatusDidChange)||void 0===e||e.call(this.authenticationHandler,this),this.observerManager.notify(c))}}}class NotAvailableAuthenticator extends Authenticator{async loginWithToken(t,e){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}async loginWithUsernameAndPassword(t,e,n){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}logout(t){throw new Error("Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}"@ditto.authenticationExpiring"(t){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${this}`)}"@ditto.authClientValidityChanged"(t,e){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(t){const e=t.peer_to_peer,n=e.bluetooth_le.enabled,r=e.awdl.enabled,i=e.lan,o=i.enabled,a=i.mdns_enabled,s=i.multicast_enabled,c=t.connect,d=c.tcp_servers,l=c.websocket_urls,_=c.retry_interval,u=t.listen,g=u.tcp,h=g.enabled,b=g.interface_ip,f=g.port,m=u.http,w=m.enabled,y=m.interface_ip,p=m.port,I=m.static_content_path,v=m.websocket_sync,O=m.tls_key_path,k=m.tls_certificate_path,j=t.global,C=j.sync_group,E=j.routing_hint,M=new TransportConfig;return M.peerToPeer.bluetoothLE.isEnabled=n,M.peerToPeer.awdl.isEnabled=r,M.peerToPeer.lan.isEnabled=o,M.peerToPeer.lan.isMdnsEnabled=a,M.peerToPeer.lan.isMulticastEnabled=s,M.connect.tcpServers=d,M.connect.websocketURLs=l,M.connect.retryInterval=_,M.listen.tcp.isEnabled=h,M.listen.tcp.interfaceIP=b,M.listen.tcp.port=f,M.listen.http.isEnabled=w,M.listen.http.interfaceIP=y,M.listen.http.port=p,M.listen.http.staticContentPath=I,M.listen.http.websocketSync=v,M.listen.http.tlsKeyPath=O,M.listen.http.tlsCertificatePath=k,M.global.syncGroup=C,M.global.routingHint=E,M}function transportConfigToSerializable(t){const e=t.peerToPeer,n=t.connect,r=t.listen,i=t.global,o={peer_to_peer:{bluetooth_le:{enabled:e.bluetoothLE.isEnabled},awdl:{enabled:e.awdl.isEnabled},lan:{enabled:e.lan.isEnabled,mdns_enabled:e.lan.isMdnsEnabled,multicast_enabled:e.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:"0.0.0.0",port:4040},http:{isEnabled:!1,interfaceIP:"0.0.0.0",port:80,websocketSync:!0}},this.global={syncGroup:0,routingHint:0}}setAllPeerToPeerEnabled(t){this.peerToPeer.bluetoothLE.isEnabled=t,this.peerToPeer.lan.isEnabled=t,this.peerToPeer.awdl.isEnabled=t}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 t=new TransportConfig;return t.peerToPeer.bluetoothLE.isEnabled=this.peerToPeer.bluetoothLE.isEnabled,t.peerToPeer.awdl.isEnabled=this.peerToPeer.awdl.isEnabled,t.peerToPeer.lan.isEnabled=this.peerToPeer.lan.isEnabled,t.peerToPeer.lan.isMdnsEnabled=this.peerToPeer.lan.isMdnsEnabled,t.peerToPeer.lan.isMulticastEnabled=this.peerToPeer.lan.isMulticastEnabled,t.connect.tcpServers=this.connect.tcpServers.slice(),t.connect.websocketURLs=this.connect.websocketURLs.slice(),t.connect.retryInterval=this.connect.retryInterval,t.listen.tcp={...this.listen.tcp},t.listen.http={...this.listen.http},t.global.syncGroup=this.global.syncGroup,t.global.routingHint=this.global.routingHint,t}static areListenTCPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port}static areListenHTTPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port&&t.staticContentPath===e.staticContentPath&&t.websocketSync===e.websocketSync&&t.tlsKeyPath===e.tlsKeyPath&&t.tlsCertificatePath===e.tlsCertificatePath}}class Subscription{get isCancelled(){return this._isCancelled}get collectionName(){return this.collection.name}cancel(){this.isCancelled||(this._isCancelled=!0,this.manager.remove(this))}constructor(t,e,n,r,i,o){this._isCancelled=!1,this.query=e,this.queryArgsCBOR=n,this.collection=t,this.contextInfo={id:generateEphemeralToken(),collectionName:t.name,query:e,queryArgsCBOR:n,orderBys:r,limit:i,offset:o},this.manager=t.store.ditto.subscriptionManager,this.manager.add(this)}}class LiveQueryEventInitial{constructor(){this.isInitial=!0}hash(t){Logger.warning("LiveQueryEventInitial.hash() is deprecated, use Document.hash() instead");return documentsHash(Bridge.document.handlesFor(t).deref())}hashMnemonic(t){Logger.warning("LiveQueryEventInitial.hashMnemonic() is deprecated, use Document.hashMnemonic() instead");return documentsHashMnemonic(Bridge.document.handlesFor(t).deref())}}class LiveQueryEventUpdate{hash(t){Logger.warning("LiveQueryEventUpdate.hash() is deprecated, use Document.hash() instead");return documentsHash(Bridge.document.handlesFor(t).deref())}hashMnemonic(t){Logger.warning("LiveQueryEventUpdate.hashMnemonic() is deprecated, use Document.hashMnemonic() instead");return documentsHashMnemonic(Bridge.document.handlesFor(t).deref())}constructor(t){this.isInitial=!1,this.oldDocuments=t.oldDocuments,this.insertions=t.insertions,this.deletions=t.deletions,this.updates=t.updates,this.moves=t.moves}}class SingleDocumentLiveQueryEvent{hash(t){Logger.warning("SingleDocumentLiveQueryEvent.hash() is deprecated, use Document.hash() instead");return documentsHash(Bridge.document.handlesFor(null==t?[]:[t]).deref())}hashMnemonic(t){Logger.warning("SingleDocumentLiveQueryEvent.hashMnemonic() is deprecated, use Document.hashMnemonic() instead");return documentsHashMnemonic(Bridge.document.handlesFor(null==t?[]:[t]).deref())}constructor(t,e){this.isInitial=t,this.oldDocument=e}}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(t,e,n,r,i,o,a,s){this.query=t,this.queryArgs=e?Object.freeze({...e}):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 t=d.deref();if(!t)return;const e=Bridge.ditto.handleFor(t).derefOrNull();return e?t.deferCloseAsync((async()=>{await liveQuerySignalAvailableNext(e,l)})):void 0},_=a.store.ditto,u=Bridge.ditto.handleFor(_);if(_.deferClose((()=>{l=liveQueryRegister(u.deref(),c,t,n,this.orderBys,i,o,(t=>{const e=t.documents.map((t=>Bridge.document.bridge(t)));let n;n=t.is_initial?new LiveQueryEventInitial:new LiveQueryEventUpdate({oldDocuments:t.old_documents.map((t=>Bridge.document.bridge(t))),insertions:t.insertions,deletions:t.deletions,updates:t.updates,moves:t.moves.map((t=>({from:t[0],to:t[1]})))}),s(e,n,signalNext)}))})),!l)throw new Error("Internal inconsistency, couldn't create a valid live query ID.");this._liveQueryID=l}async signalNext(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);if(e.derefOrNull())return t.deferCloseAsync((async()=>{await liveQuerySignalAvailableNext(e.deref(),this.liveQueryID)}))}}class PendingCursorOperation extends BasePendingCursorOperation{sort(t,e="ascending"){return super.sort(t,e)}offset(t){return super.offset(t)}limit(t){return super.limit(t)}async remove(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query;return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const n=await writeTransaction(e.deref()),r=await collectionRemoveQueryStr(e.deref(),this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e.deref(),n),r}))).map((t=>new DocumentID(t,!0)))}))}async evict(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query;return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const n=await writeTransaction(e.deref()),r=await collectionEvictQueryStr(e.deref(),this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e.deref(),n),r}))).map((t=>new DocumentID(t,!0)))}))}async update(t){const e=this.collection.store.ditto,n=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await writeTransaction(n.deref()),r=await super.updateWithTransaction(t,e);return await writeTransactionCommit(n.deref(),e),r}))))}subscribe(){const t=new Subscription(this.collection,this.query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return this.collection.store.ditto.subscriptionManager.add(t),t}observeLocal(t){return this._observe(t,!1)}observeLocalWithNextSignal(t){return this._observe(t,!0)}constructor(t,e,n){super(t,e,n)}_observe(t,e){const n=e?t:function wrappedHandler(e,n,r){try{return t.call(this,e,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 t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const t=await writeTransaction(e.deref()),n=await collectionRemove(e.deref(),this.collection.name,t,this.documentIDCBOR);return await writeTransactionCommit(e.deref(),t),n}))))}async evict(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const t=await writeTransaction(e.deref()),n=await collectionEvict(e.deref(),this.collection.name,t,this.documentIDCBOR);return await writeTransactionCommit(e.deref(),t),n}))))}async update(t){const e=this.collection.store.ditto,n=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=await readTransaction(n.deref()),r=await collectionGet(n.deref(),this.collection.name,this.documentIDCBOR,e);if(readTransactionFree(e),!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));t(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 t=new Subscription(this.collection,this.query,null,[],-1,0);return this.collection.store.ditto.subscriptionManager.add(t),t}observeLocal(t){return this._observe(t,!1)}observeLocalWithNextSignal(t){return this._observe(t,!0)}constructor(t,e){super(t,e)}_observe(t,e){const n=new LiveQuery(this.query,null,null,[],-1,0,this.collection,((n,r,i)=>{if(n.length>1){const t=n.map((t=>t.id.toBase64String()));throw new Error(`Internal inconsistency, single document live query returned more than one document. Query: ${this.query}, documentIDs: ${t.join(", ")}.`)}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(e)t(o,s,i);else try{t(o,s)}finally{i()}}));return this.collection.store.ditto.liveQueryManager.startLiveQuery(n),n}}class Collection{find(t,e){return new PendingCursorOperation(t,null!=e?e:null,this)}findAll(){return this.find("true")}findByID(t){const e=t instanceof DocumentID?t:new DocumentID(t);return new PendingIDSpecificOperation(e,this)}async upsert(t,e={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{var n;const i=null!==(n=e.writeStrategy)&&void 0!==n?n:"merge",o=desugarJSObject(t,!0),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(t,e={}){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 t)throw new Error("Can't create attachment from file when running in the browser. Please pass the raw data (as a Uint8Array) instead.");if(t instanceof Uint8Array)return await dittoNewAttachmentFromBytes(r.deref(),t);throw new Error(`Can't create new attachment, only file path as string or raw data as Uint8Array are supported, but got: ${typeof t}, ${t}`)})(),s={_id:i,_len:o,_meta:{...e}};s[DittoCRDTTypeKey]=DittoCRDTType.attachment;const c=new AttachmentToken(s),d=new Attachment(n,c);return Bridge.attachment.bridge(a,(()=>d))}))}fetchAttachment(t,e){if(null==t||!(t instanceof AttachmentToken))throw new Error(`Invalid attachment token: ${t}`);const n=this.store.ditto;return n.deferClose((()=>n.attachmentFetcherManager.startAttachmentFetcher(t,e)))}constructor(t,e){this.name=t,this.store=e}findByIDCBOR(t){const e=new DocumentID(t,!0,!0);return new PendingIDSpecificOperation(e,this)}}const ERROR_CODES={internal:"An unexpected internal error occured. Please get in touch with Ditto customer service to report this incident.","internal/unknown-error":"An unexpected internal error occured. Please get in touch with Ditto customer service to report this incident.","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.","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."},DEFAULT_STATUS_CODE_MAPPING={JsFloatingStoreOperation:["internal","Internal inconsistency, an outstanding store operation was not awaited."],DqlQueryCompilation:["query/invalid"],DqlInvalidQueryArgs:["query/arguments-invalid"],DqlUnsupported:["query/unsupported"],StoreQuery:["query/execution"],StoreDocumentNotFound:["store/document-not-found"],StoreDatabase:["store/backend"],Crdt:["store/crdt"],default:["internal/unknown-error"]};class DittoError extends Error{constructor(t,e,n={}){if(null==ERROR_CODES[t])throw new DittoError("internal",`Invalid error code: ${t}`);super(`<${t}> ${e||ERROR_CODES[t]}`),this.code="internal",this.code=t,this.context=Object.freeze({...n})}static fromFFIError(t,e,n,r){const i=n||t.message,o={coreError:t.code,coreErrorMessage:t.message,...r};return new DittoError(e,i,o)}}function mapFFIErrors(t,e,n){try{return t()}catch(t){if(t instanceof DittoFFIError)throw translateFFIError(t,e,n);throw t}}async function mapFFIErrorsAsync(t,e,n){try{return await t()}catch(t){if(t instanceof DittoFFIError)throw translateFFIError(t,e,n);throw t}}const translateFFIError=(t,e,n)=>{var r;const i=t.code.toString();let o,a;return null!=e&&null!=e[i]?[o,a]=e[i]:[o,a]=null!==(r=DEFAULT_STATUS_CODE_MAPPING[i])&&void 0!==r?r:DEFAULT_STATUS_CODE_MAPPING.default,DittoError.fromFFIError(t,o,a,n)};class QueryResult{mutatedDocumentIDs(){return dqlMutatedDocumentIDs(Bridge.dqlResponse.handleFor(this).deref()).map((t=>new DocumentID(t,!0)))}constructor(t){if(null==t)throw new Error("Internal inconsistency, failed to initialize query result without a response pointer");const e=dqlResponseResults(t);this.items=e.map((t=>Bridge.dqlResult.bridge(t)))}}class StoreObserver{get isCancelled(){return this._isCancelled}cancel(){this._isCancelled||(this._isCancelled=!0,this.ditto.store.unregisterObserver(this))}constructor(t,e,n,r){this._isCancelled=!1,this.queryString=e,this.queryArguments=n?Object.freeze({...n}):void 0,this.ditto=t;let i,o=null;if(null!=n)try{o=CBOR.encode(n,documentIDReplacer)}catch(t){throw new DittoError("query/arguments-invalid")}const a=Bridge.ditto.handleFor(t);if(this.ditto.deferClose((()=>{const t=new WeakRef(this);function wrappedObservationHandler(e){const n=t.deref();if(null==n)return void Logger.debug(`Ignoring change event received by store observer ${i} after it was cancelled`);const o=Bridge.dqlResponse.bridge(e.query_result,(()=>new QueryResult(e.query_result)));Logger.debug(`Invoking user event handler with new event for store observer ${i}`),r(o,(()=>{n.signalNext()}))}mapFFIErrors((()=>{i=tryExperimentalRegisterChangeObserver(a.deref(),e,o,wrappedObservationHandler)}),void 0,{query:e,queryArguments:n})})),null==i)throw new DittoError("internal","Internal inconsistency, store observer ID is undefined after registering");this.liveQueryID=i}signalNext(){const t=this.ditto;if(!t||t.isClosed)return;const e=Bridge.ditto.handleFor(t).derefOrNull();if(e){if(null==this.liveQueryID)throw new Error("live query ID is null while signaling ready for next event");return t.deferCloseAsync((async()=>{Logger.debug(`Signaling availability for live query ${this.liveQueryID}`),await liveQuerySignalAvailableNext(e,this.liveQueryID)}))}}}class CollectionsEvent{static initial(t){return new CollectionsEvent({isInitial:!0,collections:t,oldCollections:[],insertions:[],deletions:[],updates:[],moves:[]})}constructor(t){this.isInitial=t.isInitial,this.collections=t.collections,this.oldCollections=t.oldCollections,this.insertions=t.insertions,this.deletions=t.deletions,this.updates=t.updates,this.moves=t.moves}}class PendingCollectionsOperation{sort(t,e="ascending"){return this.pendingCursorOperation.sort(t,e),this}offset(t){return this.pendingCursorOperation.offset(t),this}limit(t){return this.pendingCursorOperation.limit(t),this}subscribe(){return this.pendingCursorOperation.subscribe()}observeLocal(t){return this._observe(t,!1)}observeLocalWithNextSignal(t){return this._observe(t,!0)}async exec(){return collectionsFromDocuments(await this.pendingCursorOperation.exec(),this.store)}constructor(t){this.store=t,this.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",t))}then(t,e){return this.exec().then(t,e)}_observe(t,e){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 t=collectionsFromDocuments(i.oldDocuments,a);c=new CollectionsEvent({isInitial:!1,collections:s,oldCollections:t,insertions:i.insertions,deletions:i.deletions,updates:i.updates,moves:i.moves})}e?t(c,o):t(c)}),e)}}function collectionsFromDocuments(t,e){const n=[];for(const r of t){const t=r.at("name").value;void 0!==t&&"string"==typeof t&&n.push(new Collection(t,e))}return n}class WriteTransactionPendingCursorOperation extends BasePendingCursorOperation{sort(t,e="ascending"){return super.sort(t,e)}offset(t){return super.offset(t)}limit(t){return super.limit(t)}async remove(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query,n=this.collection.writeTransaction,r=(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>collectionRemoveQueryStr(e.deref(),this.collection.name,n.writeTransactionPointer,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((t=>new DocumentID(t,!0)));return r.forEach((t=>{n.addResult("removed",t,this.collection.name)})),r}))}async evict(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.query,n=this.collection.writeTransaction,r=(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>collectionEvictQueryStr(e.deref(),this.collection.name,n.writeTransactionPointer,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((t=>new DocumentID(t,!0)));return r.forEach((t=>{n.addResult("evicted",t,this.collection.name)})),r}))}async update(t){const e=this.collection.writeTransaction,n=await super.updateWithTransaction(t,e.writeTransactionPointer);return n.keys().forEach((t=>{e.addResult("updated",t,this.collection.name)})),n}constructor(t,e,n){super(t,e,n)}}class WriteTransactionPendingIDSpecificOperation extends BasePendingIDSpecificOperation{async remove(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.collection.writeTransaction,n=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>collectionRemove(e.deref(),this.collection.name,t.writeTransactionPointer,this.documentIDCBOR)));return t.addResult("removed",this.documentID,this.collection.name),n}))}async evict(){const t=this.collection.store.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>{const t=this.collection.writeTransaction,n=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionEvict(e.deref(),this.collection.name,t.writeTransactionPointer,this.documentIDCBOR)));return t.addResult("evicted",this.documentID,this.collection.name),n}))}async update(t){const e=this.collection.store.ditto,n=Bridge.ditto.handleFor(e);return e.deferCloseAsync((async()=>{const e=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 t(o),Bridge.mutableDocument.unregister(o),await collectionUpdate(n.deref(),this.collection.name,e.writeTransactionPointer,i),e.addResult("updated",this.documentID,this.collection.name),o["@ditto.updateResults"].slice()}))}constructor(t,e){super(t,e)}}class WriteTransactionCollection{find(t,e){return new WriteTransactionPendingCursorOperation(t,null!=e?e:null,this)}findAll(){return this.find("true")}findByID(t){const e=t instanceof DocumentID?t:new DocumentID(t);return new WriteTransactionPendingIDSpecificOperation(e,this)}async upsert(t,e={}){const n=this.store.ditto,r=Bridge.ditto.handleFor(n);return n.deferCloseAsync((async()=>{var n;const i=null!==(n=e.writeStrategy)&&void 0!==n?n:"merge",o=desugarJSObject(t,!0),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(t){const e=new DocumentID(t,!0,!0);return new WriteTransactionPendingIDSpecificOperation(e,this)}constructor(t,e,n){this.name=t,this.store=e,this.writeTransaction=n}}class WriteTransaction{static async init(t){return t.deferCloseAsync((async()=>{const e=Bridge.ditto.handleFor(t),n=await writeTransaction(e.deref());return new WriteTransaction(t,n)}))}scoped(t){if("string"!=typeof t)throw new Error("Collection name must be a string");return new WriteTransactionCollection(t,this.ditto.store,this)}async commit(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>writeTransactionCommit(e.deref(),this.writeTransactionPointer)))}async rollback(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferCloseAsync((async()=>writeTransactionRollback(e.deref(),this.writeTransactionPointer)))}addResult(t,e,n){this.results.push({type:t,docID:e,collectionName:n})}constructor(t,e){this.writeTransactionPointer=e,this.ditto=t,this.results=[]}}class Store{registerObserver(t,e,n){return this.registerObserverWithSignalNext(t,((t,n)=>{try{e(t)}finally{n()}}),n)}registerObserverWithSignalNext(t,e,n){if("string"!=typeof t)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof t);const r=new StoreObserver(this.ditto,t,null!=n?n:null,e);this.observers=Object.freeze([...this.observers,r]);const i=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>new Promise((t=>{step((async()=>{try{await mapFFIErrorsAsync((async()=>await liveQueryStart(i.deref(),r.liveQueryID)))}catch(t){Logger.error(`Failed to start live query: ${t.message}`)}t()}))})))),r}collection(t){return new Collection(t,this)}collections(){return new PendingCollectionsOperation(this)}collectionNames(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferClose((()=>mapFFIErrors((()=>dittoGetCollectionNames(e.deref())))))}async execute(t,e){if("string"!=typeof t)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof t);const n=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{let r=null;if(null!=e)try{r=CBOR.encode(e,documentIDReplacer)}catch(t){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${t.message}`)}const i={query:t,queryArguments:e},o=await mapFFIErrorsAsync((async()=>await performAsyncToWorkaroundNonAsyncFFIAPI((()=>tryExperimentalExecQueryStr(n.deref(),null,t,r)))),void 0,i);return Bridge.dqlResponse.bridge(o,(()=>new QueryResult(o)))}))}async write(t){return this.ditto.deferCloseAsync((async()=>{const e=await WriteTransaction.init(this.ditto);try{await t(e)}catch(t){throw await e.rollback(),Logger.warning(`Transaction rolled back due to an error: ${null==t?void 0:t.message}`),t}return await e.commit(),e.results}))}constructor(t){this.observers=Object.freeze([]),this.ditto=t}async registerObserverWebhook(t,e,n){let r=null;if(null!=n)try{r=CBOR.encode(n,documentIDReplacer)}catch(t){throw new DittoError("query/arguments-invalid",`Invalid query arguments: ${t.message}`)}const i={query:t,queryArguments:n},o=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{const n=await mapFFIErrorsAsync((async()=>await tryExperimentalWebhookRegisterDqlLiveQuery(o.deref(),t,r,e)),void 0,i);return new DocumentID(n,!0)}))}unregisterObserver(t){if(t.ditto!==this.ditto)throw new DittoError("internal","Internal inconsistency, can't remove store observer that does not belong to this store");if(!t.isCancelled)throw new DittoError("internal","Internal inconsistency, can't remove store observer that has not been cancelled");const e=this.observers.findIndex((e=>e===t));if(-1===e)return!1;const n=[...this.observers];n.splice(e,1),this.observers=Object.freeze(n);const r=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>{mapFFIErrors((()=>liveQueryStop(r.deref(),t.liveQueryID)))})),!0}close(){for(const t of this.observers)t.cancel()}async registerLiveQueryWebhook(t,e,n){const r=this.ditto,i=Bridge.ditto.handleFor(r);return r.deferCloseAsync((async()=>{const r=validateQuery(e),o=await liveQueryWebhookRegister(i.deref(),t,r,[],0,0,n);return new DocumentID(o,!0)}))}}function addressToString(t){return`${t.siteId}-${t.pubkey}`}class Presence{get graph(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferClose((()=>{const t=dittoPresenceV3(e.deref());return JSON.parse(t)}))}observe(t){const e=this.observerManager.addObserver(t),n=new Observer(this.observerManager,e,{stopsWhenFinalized:!0});return t(this.graph),n}constructor(t){this.ditto=t,this.observerManager=new ObserverManager("PresenceObservation",{keepAlive:t.keepAlive,register:t=>{const e=this.ditto,n=Bridge.ditto.handleFor(e);e.deferClose((()=>{dittoRegisterPresenceV3Callback(n.deref(),t)}))},unregister:()=>{const t=this.ditto,e=Bridge.ditto.handleFor(t);t.deferClose((()=>{dittoClearPresenceV3Callback(e.deref())}))},process:t=>[JSON.parse(t)]})}close(){this.observerManager.close()}}class LiveQueryManager{constructor(t,e){this.finalizationRegistry=new FinalizationRegistry(this.finalize),this.ditto=t,this.keepAlive=e,this.liveQueriesByID={}}startLiveQuery(t){const e=this.ditto,n=Bridge.ditto.handleFor(e);e.deferCloseAsync((async()=>{const r=t.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(t);return this.liveQueriesByID[r]=i,this.finalizationRegistry.register(t,r,this.finalize),t.liveQueryManager=this,e.keepAlive.retain(`LiveQuery.${r}`),new Promise(((t,e)=>{step((async()=>{await liveQueryStart(n.deref(),r),t()}))}))}))}stopLiveQuery(t){this.finalizationRegistry.unregister(t);const e=t.liveQueryID;if(!e)throw new Error("Internal inconsistency, tried to remove a live query that doesn't have a live query ID (probably stopped).");t.liveQueryManager=null,this.stopLiveQueryWithID(e)}close(){for(const t in this.liveQueriesByID){const e=this.liveQueriesByID[t].deref();e&&this.stopLiveQuery(e)}}stopLiveQueryWithID(t){const e=this.ditto,n=Bridge.ditto.handleFor(e);e.deferClose((()=>{liveQueryStop(n.deref(),t),this.keepAlive.release(`LiveQuery.${t}`),delete this.liveQueriesByID[t]}))}finalize(t){this.stopLiveQueryWithID(t)}}class PresenceManager{constructor(t){this.ditto=t,this.isClosed=!1,this.isRegistered=!1,this.currentRemotePeers=[],this.callbacksByPresenceToken={}}addObserver(t){if(this.isClosed)throw new Error("Internal inconsistency, can't add presence observer, observer mananger close()-ed.");this.registerIfNeeded();const e=generateEphemeralToken();return this.callbacksByPresenceToken[e]=t,this.ditto.keepAlive.retain(`PresenceObservation.${e}`),t(this.currentRemotePeers),e}removeObserver(t){const e=this.callbacksByPresenceToken[t];if(void 0===e)throw new Error(`Can't remove presence observer, token '${t}' has never been registered before.`);null!==e&&void 0!==this.callbacksByPresenceToken[t]&&(this.ditto.keepAlive.release(`PresenceObservation.${t}`),this.callbacksByPresenceToken[t]=null,this.unregisterIfNeeded())}hasObserver(t){return void 0!==this.callbacksByPresenceToken[t]}close(){this.isClosed=!0;for(const t in this.callbacksByPresenceToken)this.removeObserver(t)}hasObservers(){return Object.keys(this.callbacksByPresenceToken).length>0}registerIfNeeded(){const t=this.ditto,e=Bridge.ditto.handleFor(this.ditto);t.deferClose((()=>{if(!this.isRegistered){this.isRegistered=!0;const t=dittoPresenceV1(e.deref());this.currentRemotePeers=this.decode(t).sort(this.compareRemotePeers),dittoRegisterPresenceV1Callback(e.deref(),this.handlePresenceV1Callback.bind(this))}}))}unregisterIfNeeded(){const t=this.ditto,e=Bridge.ditto.handleFor(t);t.deferClose((()=>{!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,dittoClearPresenceCallback(e.deref()),this.currentRemotePeers=[])}))}handlePresenceV1Callback(t){const e=this.decode(t).sort(this.compareRemotePeers);this.currentRemotePeers=e,this.notify()}notify(){if(!this.isClosed)for(const t in this.callbacksByPresenceToken){const e=this.callbacksByPresenceToken[t];e&&e(this.currentRemotePeers)}}decode(t){return JSON.parse(t).map((t=>{var e,n;return{networkID:t.network_id,deviceName:t.device_name,rssi:null!==(e=t.rssi)&&void 0!==e?e:void 0,approximateDistanceInMeters:null!==(n=t.approximate_distance_in_meters)&&void 0!==n?n:void 0,connections:t.connections}}))}compareRemotePeers(t,e){return 0===t.connections.length&&e.connections.length>0?1:t.connections.length>0&&0===e.connections.length||t.deviceName<e.deviceName?-1:t.deviceName>e.deviceName?1:0}}class TransportConditionsManager extends ObserverManager{constructor(t){super("TransportConditionsObservation",{keepAlive:t.keepAlive}),this.ditto=t}register(t){const e=this.ditto,n=Bridge.ditto.handleFor(e);return e.deferClose((()=>dittoRegisterTransportConditionChangedCallback(n.deref(),t)))}unregister(){const t=this.ditto,e=Bridge.ditto.handleFor(t);return t.deferClose((()=>dittoRegisterTransportConditionChangedCallback(e.deref(),null)))}process(t,e){let n,r;switch(t){case"Bluetooth":n="BLE";break;case"Tcp":n="TCP";break;case"Awdl":n="AWDL";break;case"Mdns":n="MDNS"}switch(e){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(t,e,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=t,this.queryString=e,this.queryArguments=n?Object.freeze({...n}):void 0,this.queryArgumentsCBOR=r}}class Sync{registerSubscription(t,e){if("string"!=typeof t)throw new DittoError("query/invalid","Expected parameter 'query' to be of type 'string', found: "+typeof t);let n=null;if(null!=e)try{n=CBOR.encode(e,documentIDReplacer)}catch(t){throw new DittoError("query/arguments-invalid",`Unable to encode query arguments: ${t.message}`)}const r={query:t,queryArguments:e},i=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{mapFFIErrors((()=>tryExperimentalAddDQLSubscription(i.deref(),t,n)),void 0,r)}));const o=new SyncSubscription(this.ditto,t,e||null,n);return this.subscriptions=Object.freeze([...this.subscriptions,o]),o}get parameters(){return this.state.underlyingSyncParameters}constructor(t){this.subscriptions=Object.freeze([]),this.bluetoothLETransportPointer=null,this.awdlTransportPointer=null,this.lanTransportPointer=null,this.mdnsClientTransportPointer=null,this.mdnsServerAdvertiserPointer=null;const e={identity:t.identity,transportConfig:new TransportConfig,ditto:t,isWebValid:!1,isX509Valid:!1,isSyncActive:!1};this.ditto=t,this.state=stateFrom(e),transportsInit()}unregisterSubscription(t){if(t.ditto!==this.ditto)throw new DittoError("internal","Can't remove replication subscription that does not belong to this store");if(!t.isCancelled)throw new DittoError("internal","Internal inconsistency, can't remove replication subscription that has not been cancelled");const e=this.subscriptions.findIndex((e=>e===t));if(-1===e)return!1;const n=[...this.subscriptions];n.splice(e,1),this.subscriptions=Object.freeze(n);const r=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>{mapFFIErrors((()=>tryExperimentalRemoveDQLSubscription(r.deref(),t.queryString,t.queryArgumentsCBOR)))})),!0}update(t){const e=this.state,n=stateFrom(t);this.updatePeerToPeerBluetoothLE(e,n),this.updatePeerToPeerAWDL(e,n),this.updatePeerToPeerLAN(e,n),this.updateListenTCP(e,n),this.updateListenHTTP(e,n),this.updateConnectTCPServers(e,n),this.updateConnectWebsocketURLs(e,n),this.updateGlobal(e,n),this.updateConnectRetryInterval(e,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 t of this.subscriptions)t.cancel()}updatePeerToPeerBluetoothLE(t,e){}updatePeerToPeerAWDL(t,e){}updatePeerToPeerLAN(t,e){}updateListenTCP(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=t.effectiveTransportConfig.listen.tcp,i=e.effectiveTransportConfig.listen.tcp;TransportConfig.areListenTCPsEqual(i,n)||(n.isEnabled&&dittoStopTCPServer(r.deref()),i.isEnabled&&dittoStartTCPServer(r.deref(),`${i.interfaceIP}:${i.port}`))}))}updateListenHTTP(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const n=t.effectiveTransportConfig.listen.http,i=e.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(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const t=e.effectiveTransportConfig.connect.tcpServers;dittoSetStaticTCPClients(r.deref(),t)}))}updateConnectWebsocketURLs(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{const t=e.effectiveTransportConfig.connect.websocketURLs,n=e.effectiveTransportConfig.global.routingHint;dittoSetStaticWebsocketClients(r.deref(),t,n)}))}updateGlobal(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{t.effectiveTransportConfig.global.syncGroup!==e.effectiveTransportConfig.global.syncGroup&&dittoSetSyncGroup(r.deref(),e.effectiveTransportConfig.global.syncGroup)}))}updateConnectRetryInterval(t,e){const n=this.ditto,r=Bridge.ditto.handleFor(n);n.deferClose((()=>{dittoSetConnectRetryInterval(r.deref(),e.effectiveTransportConfig.connect.retryInterval)}))}}function stateFrom(t){var e,n;const r=t.identity,i=t.isSyncActive,o=t.isX509Valid,a=t.isWebValid;let s,c,d=!1;"onlinePlayground"!==r.type&&"onlineWithAuthentication"!==r.type||(s=r.appID,c=null!==(e=r.customDittoCloudURL)&&void 0!==e?e:null,d=null===(n=r.enableDittoCloudSync)||void 0===n||n),validateEnabledTransportsAvailable(t.ditto,t.transportConfig);const l=t.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 t=null!=c?c:defaultDittoCloudURL(s);l.connect.websocketURLs.push(t)}return{underlyingSyncParameters:t,effectiveTransportConfig:l.freeze()}}function validateEnabledTransportsAvailable(t,e){const n=Bridge.ditto.handleFor(t);return t.deferClose((()=>{const t=[],r=transportsBLEIsAvailable(n.deref()),i=transportsAWDLIsAvailable(n.deref()),o=transportsLANIsAvailable(n.deref());if(e.peerToPeer.bluetoothLE.isEnabled&&!r&&t.push("BluetoothLE"),e.peerToPeer.awdl.isEnabled&&!i&&t.push("AWDL"),e.peerToPeer.lan.isEnabled&&!o&&t.push("LAN"),t.length>0)throw new Error(`The following P2P transports are enabled in the transport config but are not supported in the current environment: ${t.join(", ")}`);if(e.connect.tcpServers.length>0&&isWebBuild)throw new Error("The transport config contains TCP servers, but this transport is not supported in web environments");if(e.listen.http.isEnabled&&isWebBuild)throw new Error("The transport config contains an HTTP listener, which is not supported in web environments");if(e.listen.tcp.isEnabled&&isWebBuild)throw new Error("The transport config contains a TCP listener, which is not supported in web environments")}))}class SubscriptionManager{constructor(t){this.ditto=t,this.subscriptions={},this.finalizationRegistry=new FinalizationRegistry(this.removeWithContextInfo.bind(this))}add(t){const e=this.ditto,n=Bridge.ditto.handleFor(e),r=t.contextInfo;e.deferClose((async()=>{this.subscriptions[r.id]=new WeakRef(t),this.finalizationRegistry.register(t,t.contextInfo,t),addSubscription(n.deref(),r.collectionName,r.query,r.queryArgsCBOR,r.orderBys,r.limit,r.offset)}))}remove(t){if(null==this.subscriptions[t.contextInfo.id])throw new Error(`Internal inconsistency, tried to remove a subscription that is not tracked: ${t.contextInfo.id}`);this.finalizationRegistry.unregister(t),this.removeWithContextInfo(t.contextInfo)}close(){this.ditto.deferClose((async()=>{for(const t in this.subscriptions){const e=this.subscriptions[t].deref();null!=e&&this.remove(e)}}))}removeWithContextInfo(t){const e=this.ditto,n=Bridge.ditto.handleFor(e);e.deferClose((()=>{delete this.subscriptions[t.id],removeSubscription(n.deref(),t.collectionName,t.query,t.queryArgsCBOR,t.orderBys,t.limit,t.offset)}))}}class AttachmentFetcher{stop(){step((async()=>{await this.manager.stopAttachmentFetcher(this),null!=this.rejectPendingFetch&&this.rejectPendingFetch()}))}then(t,e){return this.attachment.then(t,e)}constructor(t,e,n,r){this.cancelTokenPromise=null,this.rejectPendingFetch=null,this.ditto=t,this.token=e,this.manager=n,this.id=generateEphemeralToken();const i=r||function(){},o=Bridge.ditto.handleFor(t);this.attachment=new Promise(((t,n)=>{this.rejectPendingFetch=()=>{n(new Error("Attachment fetch was canceled"))},this.cancelTokenPromise=dittoResolveAttachment(o.deref(),e.id,{onComplete:e=>{const n=new Attachment(this.ditto,this.token);Bridge.attachment.bridge(e,(()=>n)),i({type:"Completed",attachment:n}),this.rejectPendingFetch=null,t(n)},onProgress:(t,e)=>{i({type:"Progress",totalBytes:e,downloadedBytes:t})},onDelete:()=>{i({type:"Deleted"}),this.rejectPendingFetch=null,t(null)}},(()=>{}))}))}}class AttachmentFetcherManager{constructor(t){this.contextInfoByID={},this.finalizationRegistry=new FinalizationRegistry(this.stopWithContextInfo),this.ditto=t}startAttachmentFetcher(t,e){return this.ditto.deferClose((()=>{const n=new AttachmentFetcher(this.ditto,t,this,e),r={id:n.id,attachmentTokenID:t.id,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((t=>(resetCancelToken(),t)),(t=>(resetCancelToken(),t))),this.ditto.keepAlive.retain(`AttachmentFetcher.${n.id})`),n}))}async stopAttachmentFetcher(t){this.finalizationRegistry.unregister(t);const e=this.contextInfoByID[t.id];if(null==e)throw new Error(`Internal inconsistency: cannot stop attachment fetcher ${t.id}, which is not registered.`);await this.stopWithContextInfo(e)}close(){this.ditto.deferCloseAsync((async()=>{const t=Object.values(this.contextInfoByID).map((async t=>{const e=t.attachmentFetcher.deref();null!=e&&await this.stopAttachmentFetcher(e)}));await Promise.all(t)}))}stopWithContextInfo(t){const e=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>{if(null==this.contextInfoByID[t.id])throw new Error(`Internal inconsistency: attachment fetcher ${t.id} not found in active attachment fetchers.`);delete this.contextInfoByID[t.id],this.ditto.keepAlive.release(`AttachmentFetcher.${t.id})`);const n=await t.cancelTokenPromise;n&&dittoCancelResolveAttachment(e.deref(),t.attachmentTokenID,n)}))}}class SmallPeerInfo{get isEnabled(){const t=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>dittoSmallPeerInfoGetIsEnabled(t.deref())))}set isEnabled(t){if("boolean"!=typeof t)throw new TypeError("Expected boolean, got "+typeof t);const e=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{dittoSmallPeerInfoSetEnabled(e.deref(),t)}))}get metadata(){return JSON.parse(this.metadataJSONString)}set metadata(t){this.metadataJSONString=JSON.stringify(t)}get metadataJSONString(){const t=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferClose((()=>dittoSmallPeerInfoGetMetadata(t.deref())))}set metadataJSONString(t){if("string"!=typeof t)throw new TypeError("Expected string, got "+typeof t);const e=Bridge.ditto.handleFor(this.ditto);this.ditto.deferClose((()=>{dittoSmallPeerInfoSetMetadata(e.deref(),t)}))}async getSyncScope(){const t=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>dittoSmallPeerInfoGetSyncScope(t.deref())))}async setSyncScope(t){const e=Bridge.ditto.handleFor(this.ditto);return this.ditto.deferCloseAsync((async()=>dittoSmallPeerInfoSetSyncScope(e.deref(),t)))}constructor(t){this.ditto=t}}const DEFAULT_PERSISTENCE_DIRECTORY="ditto";class Ditto{static get VERSION(){return dittoGetSDKSemver()}get sdkVersion(){const t=Bridge.ditto.handleFor(this);return this.deferClose((()=>dittoGetSDKVersion(t.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 t;return null!==(t=this._isActivated)&&void 0!==t&&t}get isClosed(){var t;return null!==(t=this._isClosed)&&void 0!==t&&t}get isSyncActive(){var t;return null!==(t=this._isSyncActive)&&void 0!==t&&t}constructor(t,e){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(e);const n=null!=t?t:{type:"offlinePlayground",appID:""},r=Object.freeze(this.validateIdentity(n));this.identity=Object.freeze(r),this.deviceName=navigator.userAgent,this.keepAlive=new KeepAlive;const i=uninitializedDittoMake(this.persistenceDirectory);let o=null;const a=new WeakRef(this),s=dittoMake(i,(()=>{var t,e,n;if("offlinePlayground"===r.type)return dittoIdentityConfigMakeOfflinePlayground(r.appID,null!==(t=r.siteID)&&void 0!==t?t: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 t=null!==(e=r.customAuthURL)&&void 0!==e?e:defaultAuthURL(r.appID);return dittoIdentityConfigMakeOnlinePlayground(r.appID,r.token,t)}if("onlineWithAuthentication"===r.type){const t=null!==(n=r.customAuthURL)&&void 0!==n?n:defaultAuthURL(r.appID);return dittoIdentityConfigMakeOnlineWithAuthentication(r.appID,t)}throw new Error(`Can't create Ditto, unsupported identity type: ${r}`)})());dittoAuthClientSetValidityListener(s,(function(...t){const e=a.deref();null==e||e.isClosed?Logger.info("Ditto is closed, ignoring auth client validity change"):e.authClientValidityChanged(...t)}));const c=dittoAuthClientIsWebValid(s),d=dittoAuthClientIsX509Valid(s),l=dittoAuthClientGetAppID(s),_=dittoAuthClientGetSiteID(s);if(Bridge.ditto.bridge(s,this),"onlineWithAuthentication"===r.type){this.auth=new OnlineAuthenticator(this.keepAlive,this,r.authHandler);dittoAuthSetLoginProvider(s,dittoAuthClientMakeLoginProvider((function(t){const e=a.deref();e?e.auth?e.auth["@ditto.authenticationExpiring"](t):o=t: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(t){},authenticationExpiringSoon:function(t,e){}}):this.auth=new NotAvailableAuthenticator(this.keepAlive);const u=this.makeDefaultTransportConfig().freeze();this.appID=l,this.siteID=_,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:u}),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!=o&&this.auth["@ditto.authenticationExpiring"](o)}static disableDeadlockDetection(){}static hasDeadlockDetection(){return!1}static isEnvironmentSupported(){let t,e=!1;"undefined"!=typeof window&&window.navigator&&window.navigator.userAgent&&window.navigator.appVersion&&(e=-1!==window.navigator.userAgent.indexOf("MSIE")||window.navigator.appVersion.indexOf("Trident/")>-1);try{t=checkAPIs()}catch(t){throw new Error(`Error checking environment support: ${t}`)}return!e&&t}static initPersistenceDirectory(t){let e;if(null==t)e="ditto";else{if(0===t.trim().length)throw new Error(`Invalid argument for path parameter: '${t}'`);e=t}return e}setOfflineOnlyLicenseToken(t){if(Logger.info("Offline license token are ignored on web builds. Token validation will be skipped."),!IdentityTypesRequiringOfflineLicenseToken.includes(this.identity.type))throw new Error("Offline license tokens should only be used for manual, sharedKey or offlinePlayground identities");{const{result:e,errorMessage:n}=verifyLicense(t);if("LicenseOk"!==e)throw this._isActivated=!1,new Error(n);this._isActivated=!0}}get transportConfig(){return this.sync.parameters.transportConfig}setTransportConfig(t){const e=t.copy().freeze(),n=this.identity,r=this.isWebValid,i=this.isX509Valid;this.sync.update({transportConfig:e,identity:n,isWebValid:r,isX509Valid:i,isSyncActive:this.isSyncActive,ditto:this});const o=transportConfigToSerializable(e),a=CBOR.encode(o),s=Bridge.ditto.handleFor(this);this.deferClose((()=>{dittoSmallPeerInfoCollectionSetTransportConfigData(s.deref(),a)}))}updateTransportConfig(t){const e=this.transportConfig.copy();return t(e),this.setTransportConfig(e),this}startSync(){this.setSyncActive(!0)}stopSync(){this.setSyncActive(!1)}observePeers(t){Logger.warning("`ditto.observePeers()` is deprecated, please use `ditto.presence.observe()` instead.");const e=this.presenceManager.addObserver(t);return new Observer(this.presenceManager,e,{stopsWhenFinalized:!0})}observeTransportConditions(t){const e=this.transportConditionsManager.addObserver(t);return new Observer(this.transportConditionsManager,e,{stopsWhenFinalized:!0})}runGarbageCollection(){const t=Bridge.ditto.handleFor(this);return this.deferClose((()=>{dittoRunGarbageCollection(t.deref())}))}async disableSyncWithV3(){const t=Bridge.ditto.handleFor(this);return this.deferCloseAsync((async()=>{await dittoDisableSyncWithV3(t.deref())}))}async close(){if(!this.isClosed){if(this._isClosed=!0,this.stopSync(),this.store.close(),this.presence.close(),this.auth.close(),this.sync.close(),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(t){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");return t()}async deferCloseAsync(t){if(!this.deferCloseAllowed)throw new Error("Can't perform operation using a Ditto instance that has been closed.");const e=t();let n;this.pendingOperations.add(e);try{n=await e}finally{this.pendingOperations.delete(e)}return n}authClientValidityChanged(t,e){const n=this.transportConfig,r=this.identity,i=this.isSyncActive;this.isX509Valid,this.isWebValid,this.isX509Valid=e,this.isWebValid=t,this.auth["@ditto.authClientValidityChanged"](t,e),this.sync.update({transportConfig:n,identity:r,isWebValid:t,isX509Valid:e,isSyncActive:i,ditto:this})}validateIdentity(t){const e={...t},n=t.appID;if(!["offlinePlayground","sharedKey","manual","onlinePlayground","onlineWithAuthentication"].includes(t.type))throw new Error(`Can't create Ditto instance, unknown identity type: ${t.type}`);if(("offlinePlayground"===t.type||"sharedKey"===t.type||"onlinePlayground"===t.type||"onlineWithAuthentication"===t.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"===t.type||"sharedKey"===t.type)&&void 0!==t.siteID){const e=t.siteID;if(!("number"==typeof e||"bigint"==typeof e))throw new Error("Can't create Ditto instance, siteID must be a number or BigInt");if(e<0)throw new Error("Can't create Ditto instance, siteID must be >= 0");if(e>BigInt("0xffffffffffffffff"))throw new Error("Can't create Ditto instance, siteID must be < 2^64")}if(t.type,t.type,"onlinePlayground"===t.type){const e=t.token;if(void 0===e)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!==e&&"string"!=typeof e)throw new Error(`Property .token of identity must be be of type string, but is of type '${typeof e}': ${e}`)}return t.type,e}setSyncActive(t){const e=Bridge.ditto.handleFor(this);this.deferClose((()=>{if(t&&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&&t&&this.keepAlive.retain("sync"),this.isSyncActive&&!t&&this.keepAlive.release("sync"),this._isSyncActive=t;const n=this.isWebValid,r=this.isX509Valid,i=this.identity,o=this.transportConfig;dittoSetDeviceName(e.deref(),this.deviceName),this.sync.update({identity:i,transportConfig:o,isWebValid:n,isX509Valid:r,isSyncActive:!!t,ditto:this})}))}makeDefaultTransportConfig(){const t=Bridge.ditto.handleFor(this);return this.deferClose((()=>{const e=new TransportConfig;return transportsBLEIsAvailable(t.deref())&&(e.peerToPeer.bluetoothLE.isEnabled=!0),transportsAWDLIsAvailable(t.deref())&&(e.peerToPeer.awdl.isEnabled=!0),transportsLANIsAvailable(t.deref())&&(e.peerToPeer.lan.isEnabled=!0),e.freeze()}))}}const checkAPIs=t=>{const e=t||globalThis||global||window;return["BigInt","WeakRef","FinalizationRegistry"].every((t=>!!e[t]))},disableDeadlockTimeoutWhenDebugging=()=>{};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 t=this.cborData();let e;try{e=CBOR.decode(t)}catch(t){throw new Error(`Internal inconsistency: CBOR decoding error while materializing result item: ${t.message}`)}if(void 0===e)throw new Error("Internal inconsistency: Materialized value is undefined");this.materializedValue=e}}dematerialize(){this.materializedValue=void 0}cborData(){return dqlResultCBOR(Bridge.dqlResult.handleFor(this).deref())}jsonString(){return dqlResultJSON(Bridge.dqlResult.handleFor(this).deref())}constructor(){}}function getBridgeLoad(){const t={};return Bridge.all.map((e=>{const n=e.deref();return n?0===n.count?null:void(t[n.type.name]=n.count):null})),t}class StaticTCPClient{}class WebsocketClient{}Bridge.attachment.registerType(Attachment),Bridge.document.registerType(Document),Bridge.dqlResult.registerType(QueryResultItem),Bridge.dqlResponse.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,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,documentIDReplacer,getBridgeLoad,init,mapFFIErrors,mapFFIErrorsAsync,transportConfigFromDeserializable,transportConfigToSerializable,validateDocumentIDCBOR,validateDocumentIDValue};
|
|
2
2
|
//# sourceMappingURL=ditto.es6.js.map
|