@dittolive/ditto 4.5.2 → 4.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DittoReactNative.podspec +1 -1
- package/README.md +2 -2
- package/node/ditto.cjs.js +1 -1
- package/node/ditto.cjs.pretty.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 +1 -9
- package/react-native/android/build.gradle +1 -1
- package/react-native/lib/commonjs/ditto.rn.js +40 -39
- package/react-native/lib/module/ditto.rn.js +30 -29
- package/web/ditto.es6.js +1 -1
- package/web/ditto.es6.pretty.js +2 -2
- package/web/ditto.umd.js +1 -1
- package/web/ditto.umd.pretty.js +2 -2
- package/web/ditto.wasm +0 -0
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.2";const defaultDittoWasmFileURL="https://software.ditto.live/js/Ditto/4.5.2/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 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};
|
|
2
2
|
//# sourceMappingURL=ditto.es6.js.map
|