@dittolive/ditto 3.0.6-experimental.node-loading-issues.2.linux-x64 → 3.0.6-experimental.node-loading-issues.3.linux-x64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/node/ditto.cjs.js +1 -1
- package/node/ditto.linux-x64.node +0 -0
- package/package.json +1 -1
- package/web/ditto.es6.js +1 -1
- package/web/ditto.umd.js +1 -1
- package/web/ditto.wasm +0 -0
- package/node/ditto.cjs.js.map +0 -1
- package/node/ditto.cjs.pretty.js +0 -6068
- package/node/ditto.cjs.pretty.js.map +0 -1
- package/types/ditto.d.ts.map +0 -1
- package/web/ditto.es6.js.map +0 -1
- package/web/ditto.es6.pretty.js +0 -8552
- package/web/ditto.es6.pretty.js.map +0 -1
- package/web/ditto.umd.js.map +0 -1
- package/web/ditto.umd.pretty.js +0 -8605
- package/web/ditto.umd.pretty.js.map +0 -1
package/web/ditto.es6.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const debugTypeNames=[];const debugAllTypes=false;class Meta{constructor(type,object,pointer){this.type=type;this.object=object;this.pointer=pointer}toString(){return`{ Meta | type: ${this.type.name}, object: ${this.object.deref()}, FFI address: ${this.pointer.addr}, FFI type: ${this.pointer.type} }`}}class Bridge{constructor(type,release,options={}){this.type=type;this.release=release;this.metaByAddrMap={};this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this));Bridge.all.push(new WeakRef(this))}pointerFor(object){return object["@ditto.ptr"]}objectFor(pointer){const meta=this.metaByAddrMap[pointer.addr];if(!meta)return undefined;if(meta.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${meta.type} but this bridge is configured for ${this.type}`);const object=meta.object.deref();if(!object)throw new Error(`Internal inconsistency, found a meta entry for an object whose object is undefined (garbage collected): ${pointer}`);return object}bridge(pointer,objectOrCreate,options={}){const throwIfAlreadyBridged=options["throwIfAlreadyBridged"];const existingObject=this.objectFor(pointer);if(existingObject&&throwIfAlreadyBridged){throw new Error(`Can't bridge, pointer has already been bridged: ${JSON.stringify(pointer)}`)}if(existingObject){return existingObject}if(!objectOrCreate){objectOrCreate=()=>Reflect.construct(this.type,[])}let object;if(typeof objectOrCreate==="function"){object=objectOrCreate();if(!object){throw new Error(`Can't bridge, expected passed in create function to return an object but got: ${object}`)}}else{object=objectOrCreate}this.register(object,pointer);return object}register(object,pointer){const objectType=object.constructor;const bridgeType=this.type;if(objectType!==bridgeType)throw new Error(`Can't register, bridge is configured for type ${bridgeType.name} but passed in object is of type ${objectType.name}`);const existingPointer=this.pointerFor(object);const existingMeta=this.metaByAddrMap[pointer.addr];if(existingPointer&&existingMeta)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${existingMeta.pointer}`);if(existingPointer&&!existingMeta)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no meta entry: ${object}`);if(!existingPointer&&existingMeta)throw new Error(`Internal inconsistency, trying to register an object which has a meta entry but no associated pointer: ${object}`);const meta=new Meta(objectType,new WeakRef(object),pointer);object["@ditto.ptr"]=pointer;this.metaByAddrMap[meta.pointer.addr]=meta;this.finalizationRegistry.register(object,pointer,object);if(debugTypeNames.includes(this.type.name)||debugAllTypes){console.log(`[VERBOSE] Bridge REGISTERED a new instance of ${this.type.name}, current count: ${Object.keys(this.metaByAddrMap).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 pointer=this.pointerFor(object);if(!pointer)throw new Error(`Can't unregister, object that has not been registered before: ${object}`);const meta=this.metaByAddrMap[pointer.addr];if(!meta)throw new Error(`Internal inconsistency, trying to unregister an object which has an associated pointer but no meta entry: ${object}`);if(meta.type!==bridgeType)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry with a different type than that of the bridge: ${meta}`);if(!meta.object.deref())throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry whose object is undfined (garbage collected): ${meta}`);if(meta.object.deref()!==object)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry holding a different object: ${meta}`);this.finalizationRegistry.unregister(object);delete this.metaByAddrMap[pointer.addr];delete object["@ditto.ptr"];if(debugTypeNames.includes(this.type.name)||debugAllTypes){console.log(`[VERBOSE] Bridge UNREGISTERED an instance of ${this.type.name}, current count: ${Object.keys(this.metaByAddrMap).length}`)}}unregisterAll(){if(debugTypeNames.includes(this.type.name)||debugAllTypes){console.log(`[VERBOSE] Unregistering ALL bridged instances of type ${this.type.name}.`)}for(const meta of Object.values(this.metaByAddrMap)){const object=meta.object.deref();if(object){this.unregister(object)}}}get count(){return Object.keys(this.metaByAddrMap).length}finalize(pointer){const meta=this.metaByAddrMap[pointer.addr];if(!meta)throw new Error(`Internal inconsistency, tried to finalize an instance for a pointer, that has no meta entry: ${pointer}`);delete this.metaByAddrMap[pointer.addr];this.release(pointer);if(debugTypeNames.includes(this.type.name)||debugAllTypes){console.log(`[VERBOSE] Bridge FINALIZED an instance of ${this.type.name}, current count: ${Object.keys(this.metaByAddrMap).length}`)}}}Bridge.all=[];const isWebBuild=function(){{return true}}();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}class StaticTCPClient{}class WebsocketClient{}const staticTCPClientBridge=new Bridge(StaticTCPClient,staticTCPClientFreeHandle);const websocketClientBridge=new Bridge(WebsocketClient,websocketClientFreeHandle);function generateEphemeralToken(){let webcrypto=undefined;{webcrypto=crypto}const data=new Uint16Array(16);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(block){await sleep(0);return block()}const performAsyncToWorkaroundNonAsyncFFIAPI=step;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 cachedTextDecoder=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true});cachedTextDecoder.decode();let cachedUint8Memory0=new Uint8Array;function getUint8Memory0(){if(cachedUint8Memory0.byteLength===0){cachedUint8Memory0=new Uint8Array(wasm.memory.buffer)}return cachedUint8Memory0}function getStringFromWasm0(ptr,len){return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr,ptr+len))}const heap=new Array(32).fill(undefined);heap.push(undefined,null,true,false);let heap_next=heap.length;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}function getObject(idx){return heap[idx]}function dropObject(idx){if(idx<36)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")}}let WASM_VECTOR_LEN=0;const cachedTextEncoder=new TextEncoder("utf-8");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);getUint8Memory0().subarray(ptr,ptr+buf.length).set(buf);WASM_VECTOR_LEN=buf.length;return ptr}let len=arg.length;let ptr=malloc(len);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);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=new Int32Array;function getInt32Memory0(){if(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_30(arg0,arg1,arg2){_assertNum(arg0);_assertNum(arg1);wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hb31d743bd7fd8ba7(arg0,arg1,addHeapObject(arg2))}function __wbg_adapter_33(arg0,arg1,arg2){_assertNum(arg0);_assertNum(arg1);wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hb0e6198416fd2c02(arg0,arg1,addHeapObject(arg2))}function __wbg_adapter_36(arg0,arg1){_assertNum(arg0);_assertNum(arg1);wasm._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h14ad0cecc3697bcd(arg0,arg1)}function __wbg_adapter_39(arg0,arg1,arg2){_assertNum(arg0);_assertNum(arg1);wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h2333fcfa0c754e12(arg0,arg1,addHeapObject(arg2))}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,doc_id,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(doc_id),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_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,create_path,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(create_path),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,create_path){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_set_cbor(retptr,addHeapObject(document),addHeapObject(pointer),addHeapObject(cbor),addHeapObject(create_path));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];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 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_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 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 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_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_auth_client_logout(auth_client){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_logout(retptr,addHeapObject(auth_client));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];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(auth_client,username,password,provider){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_login_with_credentials(retptr,addHeapObject(auth_client),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(auth_client,token,provider){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_login_with_token(retptr,addHeapObject(auth_client),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(auth_client){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_is_x509_valid(retptr,addHeapObject(auth_client));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];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(auth_client){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_user_id(retptr,addHeapObject(auth_client));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];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(auth_client){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_is_web_valid(retptr,addHeapObject(auth_client));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];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(auth_client){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_get_site_id(retptr,addHeapObject(auth_client));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];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_free(auth_client){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_free(retptr,addHeapObject(auth_client));var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];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_with_static_x509(config_cbor_b64){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_with_static_x509(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_auth_client_make_with_shared_key(working_dir,app_id,key_der_b64,site_id){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_with_shared_key(retptr,addHeapObject(working_dir),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_auth_client_make_anonymous_client(working_dir,app_id,shared_token,base_url){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_anonymous_client(retptr,addHeapObject(working_dir),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_auth_client_make_for_development(working_dir,app_id,site_id){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_for_development(retptr,addHeapObject(working_dir),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_auth_client_make_with_web(working_dir,app_id,base_url,login_provider){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_with_web(retptr,addHeapObject(working_dir),addHeapObject(app_id),addHeapObject(base_url),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_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(auth_client,js_validity_update_cb){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_set_validity_listener(retptr,addHeapObject(auth_client),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_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 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 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_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_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 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_v2(ditto){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_disable_sync_with_v2(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_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_add_websocket_client(ditto,address,routing_hint){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_add_websocket_client(retptr,addHeapObject(ditto),addHeapObject(address),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_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_make(uninit_ditto,auth_client,history_tracking){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_make(retptr,addHeapObject(uninit_ditto),addHeapObject(auth_client),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 uninitialized_ditto_make(working_dir){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.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_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_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 verify_license(license,out_err_msg){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.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 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 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){return getUint8Memory0().subarray(ptr/1,ptr/1+len)}function __wbg_adapter_323(arg0,arg1,arg2,arg3){_assertNum(arg0);_assertNum(arg1);wasm.wasm_bindgen__convert__closures__invoke2_mut__h29e4cee75463f5e2(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 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 getImports(){const imports={};imports.wbg={};imports.wbg.__wbg_log_c6f7064ce12c2dfa=function(){return logError((function(arg0,arg1){try{console.log(getStringFromWasm0(arg0,arg1))}finally{wasm.__wbindgen_free(arg0,arg1)}}),arguments)};imports.wbg.__wbindgen_string_new=function(arg0,arg1){const ret=getStringFromWasm0(arg0,arg1);return addHeapObject(ret)};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.__wbg_error_f851667af71bcfc6=function(){return logError((function(arg0,arg1){try{console.error(getStringFromWasm0(arg0,arg1))}finally{wasm.__wbindgen_free(arg0,arg1)}}),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 ptr0=passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len0=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len0;getInt32Memory0()[arg0/4+0]=ptr0}),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 ptr0=isLikeNone(ret)?0:passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);var len0=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len0;getInt32Memory0()[arg0/4+0]=ptr0};imports.wbg.__wbindgen_is_string=function(arg0){const ret=typeof getObject(arg0)==="string";_assertBoolean(ret);return ret};imports.wbg.__wbindgen_object_clone_ref=function(arg0){const ret=getObject(arg0);return addHeapObject(ret)};imports.wbg.__wbg_fetch_3894579f6e2af3be=function(){return logError((function(arg0){const ret=fetch(getObject(arg0));return addHeapObject(ret)}),arguments)};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_0b638c0dafde2c36=function(){return logError((function(){const ret=mk_send_ret();return addHeapObject(ret)}),arguments)};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 ptr0=passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len0=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len0;getInt32Memory0()[arg0/4+0]=ptr0}),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 ptr0=passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len0=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len0;getInt32Memory0()[arg0/4+0]=ptr0}),arguments)};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_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_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_code_b09504754e0520f1=function(){return logError((function(arg0){const ret=getObject(arg0).code;_assertNum(ret);return ret}),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 ptr0=passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len0=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len0;getInt32Memory0()[arg0/4+0]=ptr0}),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_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 ptr0=passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len0=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len0;getInt32Memory0()[arg0/4+0]=ptr0}),arguments)};imports.wbg.__wbg_now_8172cd917e5eda6b=function(){return logError((function(arg0){const ret=getObject(arg0).now();return ret}),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_fetch_749a56934f95c96c=function(){return logError((function(arg0,arg1){const ret=getObject(arg0).fetch(getObject(arg1));return addHeapObject(ret)}),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_new_1d9a920c6bfc44a8=function(){return logError((function(){const ret=new Array;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_push_740e4b286702d964=function(){return logError((function(arg0,arg1){const ret=getObject(arg0).push(getObject(arg1));_assertNum(ret);return ret}),arguments)};imports.wbg.__wbg_instanceof_ArrayBuffer_e5e48f4762c5610b=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_8404142eb850b917=function(){return logError((function(arg0){const ret=getObject(arg0).valueOf();_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbg_newnoargs_b5b063fc6c2f0376=function(){return logError((function(arg0,arg1){const ret=new Function(getStringFromWasm0(arg0,arg1));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_apply_22a3220d244124da=function(){return handleError((function(arg0,arg1,arg2){const ret=getObject(arg0).apply(getObject(arg1),getObject(arg2));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_call_97ae9d8645dc388b=function(){return handleError((function(arg0,arg1){const ret=getObject(arg0).call(getObject(arg1));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_call_168da88779e35f61=function(){return handleError((function(arg0,arg1,arg2){const ret=getObject(arg0).call(getObject(arg1),getObject(arg2));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_next_aaef7c8aa5e212ac=function(){return handleError((function(arg0){const ret=getObject(arg0).next();return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_next_579e583d33566a86=function(){return logError((function(arg0){const ret=getObject(arg0).next;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_done_1b73b0672e15f234=function(){return logError((function(arg0){const ret=getObject(arg0).done;_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbg_value_1ccc36bc03462d71=function(){return logError((function(arg0){const ret=getObject(arg0).value;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_valueOf_6b6effad03e5c546=function(){return logError((function(arg0){const ret=getObject(arg0).valueOf();return ret}),arguments)};imports.wbg.__wbg_getTime_cb82adb2556ed13e=function(){return logError((function(arg0){const ret=getObject(arg0).getTime();return ret}),arguments)};imports.wbg.__wbg_new0_a57059d72c5b7aee=function(){return logError((function(){const ret=new Date;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_now_58886682b7e790d7=function(){return logError((function(){const ret=Date.now();return ret}),arguments)};imports.wbg.__wbg_instanceof_Object_595a1007518cbea3=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_0b9bfdd97583284e=function(){return logError((function(){const ret=new Object;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_iterator_6f9d4f28845f426c=function(){return logError((function(){const ret=Symbol.iterator;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_new_9962f939219f1820=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_323(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_99fe17964f31ffc0=function(){return logError((function(arg0){const ret=Promise.resolve(getObject(arg0));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_then_11f7a54d67b4bfad=function(){return logError((function(arg0,arg1){const ret=getObject(arg0).then(getObject(arg1));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_then_cedad20fbbd9418a=function(){return logError((function(arg0,arg1,arg2){const ret=getObject(arg0).then(getObject(arg1),getObject(arg2));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_globalThis_7f206bda628d5286=function(){return handleError((function(){const ret=globalThis.globalThis;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_self_6d479506f72c6a71=function(){return handleError((function(){const ret=self.self;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_window_f2557cc78490aceb=function(){return handleError((function(){const ret=window.window;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_global_ba75c50d1cf384f4=function(){return handleError((function(){const ret=global.global;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_instanceof_Uint8Array_971eeda69eb75003=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_8c3f0052272a457a=function(){return logError((function(arg0){const ret=new Uint8Array(getObject(arg0));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_newwithlength_f5933855e4f48a19=function(){return logError((function(arg0){const ret=new Uint8Array(arg0>>>0);return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_newwithbyteoffsetandlength_d9aa266703cb98be=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_58ad4efbb5bcb886=function(){return logError((function(arg0,arg1,arg2){const ret=getObject(arg0).subarray(arg1>>>0,arg2>>>0);return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_length_9e1ae1900cb0fbd5=function(){return logError((function(arg0){const ret=getObject(arg0).length;_assertNum(ret);return ret}),arguments)};imports.wbg.__wbg_set_83db9690f9353e79=function(){return logError((function(arg0,arg1,arg2){getObject(arg0).set(getObject(arg1),arg2>>>0)}),arguments)};imports.wbg.__wbindgen_is_function=function(arg0){const ret=typeof getObject(arg0)==="function";_assertBoolean(ret);return ret};imports.wbg.__wbg_parse_e23be3fecd886e2a=function(){return handleError((function(arg0,arg1){const ret=JSON.parse(getStringFromWasm0(arg0,arg1));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_stringify_d6471d300ded9b68=function(){return handleError((function(arg0){const ret=JSON.stringify(getObject(arg0));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_buffer_3f3d764d4747d564=function(){return logError((function(arg0){const ret=getObject(arg0).buffer;return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_get_765201544a2b6869=function(){return handleError((function(arg0,arg1){const ret=Reflect.get(getObject(arg0),getObject(arg1));return addHeapObject(ret)}),arguments)};imports.wbg.__wbg_has_8359f114ce042f5a=function(){return handleError((function(arg0,arg1){const ret=Reflect.has(getObject(arg0),getObject(arg1));_assertBoolean(ret);return ret}),arguments)};imports.wbg.__wbg_set_bf3f89b92d5a34bf=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_debug_string=function(arg0,arg1){const ret=debugString(getObject(arg1));const ptr0=passStringToWasm0(ret,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len0=WASM_VECTOR_LEN;getInt32Memory0()[arg0/4+1]=len0;getInt32Memory0()[arg0/4+0]=ptr0};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_wrapper36747=function(){return logError((function(arg0,arg1,arg2){const ret=makeMutClosure(arg0,arg1,743,__wbg_adapter_30);return addHeapObject(ret)}),arguments)};imports.wbg.__wbindgen_closure_wrapper76618=function(){return logError((function(arg0,arg1,arg2){const ret=makeMutClosure(arg0,arg1,3971,__wbg_adapter_33);return addHeapObject(ret)}),arguments)};imports.wbg.__wbindgen_closure_wrapper109907=function(){return logError((function(arg0,arg1,arg2){const ret=makeMutClosure(arg0,arg1,5571,__wbg_adapter_36);return addHeapObject(ret)}),arguments)};imports.wbg.__wbindgen_closure_wrapper120236=function(){return logError((function(arg0,arg1,arg2){const ret=makeMutClosure(arg0,arg1,6182,__wbg_adapter_39);return addHeapObject(ret)}),arguments)};return imports}function finalizeInit(instance,module){wasm=instance.exports;init$3.__wbindgen_wasm_module=module;cachedInt32Memory0=new Int32Array;cachedUint8Memory0=new Uint8Array;return wasm}async function init$3(input){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=getImports();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 load(await input,imports);return finalizeInit(instance,module)}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,createPath,timestamp){ensureInitialized();const pathX=bytesFromString(path);const errorCode=ditto_document_set_cbor_with_timestamp(document,pathX,cbor,createPath,timestamp);if(errorCode!==0)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${errorCode}`)}function documentSetCBOR(document,path,cbor,createPath){ensureInitialized();const pathX=bytesFromString(path);const errorCode=ditto_document_set_cbor(document,pathX,cbor,createPath);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,doc_id,writeStrategy){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,doc_id,strategy,null,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)}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 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}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 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}`)}function addStaticTCPClient(ditto,address){ensureInitialized();const addressBuffer=bytesFromString(address);return undefined(ditto,addressBuffer)}function staticTCPClientFreeHandle(self){undefined(self)}function addWebsocketClient(ditto,address,routingHint){ensureInitialized();const addressBuffer=bytesFromString(address);return ditto_add_websocket_client(ditto,addressBuffer,routingHint)}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){console.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();bytesFromString(level);const messageBuffer=bytesFromString(message);ditto_log(level,messageBuffer)}function dittoAuthClientMakeAnonymousClient(path,appID,sharedToken,baseURL){ensureInitialized();const pathX=bytesFromString(path);const appIDX=bytesFromString(appID);const sharedTokenX=bytesFromString(sharedToken);const baseURLX=bytesFromString(baseURL);const{status_code:errorCode,auth_client:authClient}=ditto_auth_client_make_anonymous_client(pathX,appIDX,sharedTokenX,baseURLX);if(errorCode!==0)throw new Error(errorMessage()||`ditto_auth_client_make_anonymous_client() failed with error code: ${errorCode}`);return authClient}function dittoAuthClientMakeWithWeb(path,appID,baseURL,loginProvider){ensureInitialized();const pathX=bytesFromString(path);const appIDX=bytesFromString(appID);const baseURLX=bytesFromString(baseURL);const{status_code:errorCode,auth_client:authClient}=ditto_auth_client_make_with_web(pathX,appIDX,baseURLX,loginProvider);if(errorCode!==0)throw new Error(errorMessage()||`ditto_auth_client_make_with_web() failed with error code: ${errorCode}`);return authClient}function dittoAuthClientMakeForDevelopment(path,appId,siteID){ensureInitialized();const pathX=bytesFromString(path);const appIdX=bytesFromString(appId);const siteIDX=Number(siteID);const{status_code:errorCode,auth_client:authClient}=ditto_auth_client_make_for_development(pathX,appIdX,siteIDX);if(errorCode!==0)throw new Error(errorMessage()||`ditto_auth_client_make_for_development() failed with error code: ${errorCode}`);return authClient}function dittoAuthClientMakeWithSharedKey(path,appId,sharedKey,siteID){ensureInitialized();const pathX=bytesFromString(path);const appIdX=bytesFromString(appId);const sharedKeyX=bytesFromString(sharedKey);const siteIDX=Number(siteID);const{status_code:errorCode,auth_client:authClient}=ditto_auth_client_make_with_shared_key(pathX,appIdX,sharedKeyX,siteIDX);if(errorCode!==0)throw new Error(errorMessage()||`ditto_auth_client_make_with_shared_key() failed with error code: ${errorCode}`);return authClient}function dittoAuthClientMakeWithStaticX509(configCBORBase64){ensureInitialized();const configCBORBase64X=bytesFromString(configCBORBase64);const{status_code:errorCode,auth_client:authClient}=ditto_auth_client_make_with_static_x509(configCBORBase64X);if(errorCode!==0)throw new Error(errorMessage()||`ditto_auth_client_make_with_static_x509() failed with error code: ${errorCode}`);return authClient}function dittoAuthClientGetSiteID(authClient){ensureInitialized();return ditto_auth_client_get_site_id(authClient)}function dittoAuthClientFree(authClient){ensureInitialized();return ditto_auth_client_free(authClient)}function dittoAuthClientIsWebValid(authClient){ensureInitialized();return ditto_auth_client_is_web_valid(authClient)!==0}function dittoAuthClientUserID(authClient){ensureInitialized();const cStr=ditto_auth_client_user_id(authClient);return boxCStringIntoString(cStr)}function dittoAuthClientIsX509Valid(authClient){ensureInitialized();return ditto_auth_client_is_x509_valid(authClient)!==0}async function dittoAuthClientLoginWithToken(authClient,token,provider){ensureInitialized();const tokenBytes=bytesFromString(token);const providerBytes=bytesFromString(provider);const errorCode=await ditto_auth_client_login_with_token(authClient,tokenBytes,providerBytes);if(errorCode!==0)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${errorCode}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(authClient,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(authClient,usernameBytes,passwordBytes,providerBytes);if(errorCode!==0)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${errorCode}).`)}async function dittoAuthClientLogout(authClient){ensureInitialized();const errorCode=await ditto_auth_client_logout(authClient);if(errorCode!==0)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${errorCode}).`)}function uninitializedDittoMake(path){ensureInitialized();const pathX=bytesFromString(path);return uninitialized_ditto_make(pathX)}function dittoMake(uninitializedDitto,authClient){ensureInitialized();return ditto_make(uninitializedDitto,authClient,"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();if(cb){ditto_register_presence_v1_callback(self,wrapBackgroundCbForFFI((err=>console.error(`The registered presence callback errored with ${err}`)),(cJsonStr=>{const jsonStr=refCStringToString(cJsonStr);cb(jsonStr)})))}else{await ditto_clear_presence_callback(self)}}async function dittoRegisterPresenceV3Callback(self,cb){ensureInitialized();ditto_register_presence_v3_callback(self,wrapBackgroundCbForFFI((err=>console.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)}async function dittoClearPresenceCallback(self){ensureInitialized();await ditto_clear_presence_callback(self)}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=>console.error(`The registered "transport condition changed" callback errored with ${err}`)),cb))}}function dittoSetDeviceName(dittoPointer,deviceName){ensureInitialized();let deviceNameCString=bytesFromString(deviceName);if(isWebBuild&&deviceNameCString.length>64){const sanitizedDeviceName=deviceName.replace(/[^ -~]+/g,"");deviceNameCString=bytesFromString(sanitizedDeviceName.substr(0,63))}return ditto_set_device_name(dittoPointer,deviceNameCString)}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 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)}function dittoAddMulticastTransport(dittoPointer){ensureInitialized();return undefined(dittoPointer)}function dittoRemoveMulticastTransport(dittoPointer){ensureInitialized();return undefined(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 dittoDisableSyncWithV2(dittoPointer){ensureInitialized();const errorCode=await ditto_disable_sync_with_v2(dittoPointer);if(errorCode!==0)throw new Error(errorMessage()||`ditto_disable_sync_with_v2() failed with error code: ${errorCode}`)}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)}function dittoAuthClientMakeLoginProvider(expiringCb,onError){ensureInitialized();return ditto_auth_client_make_login_provider(wrapBackgroundCbForFFI(onError,expiringCb))}function dittoAuthClientSetValidityListener(authClient,validityUpdateCb,onError){ensureInitialized();const validityUpdateRawCb=wrapBackgroundCbForFFI(onError,(function(isWebValidInt,isX509ValidInt){return validityUpdateCb(isWebValidInt===1,isX509ValidInt===1)}));return ditto_auth_client_set_validity_listener(authClient,validityUpdateRawCb)}let isInitialized$1=false;let withOutPtr;async function init$2(webAssemblyModule){{if(webAssemblyModule){await init$3(webAssemblyModule)}else{await init$3()}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=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=console.error}return(ret_sender,...args)=>{let ret;try{ret=cb(...args)}catch(err){try{onError(err)}catch(nested_error){console.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.")}}async function init$1(){}function bleIsAvailable(ditto){{return false}}function bleCreate(ditto){{throw new Error("Can't create BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}}function bleDestroy(ble){{throw new Error("Can't destroy BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}}function lanIsAvailable(ditto){{return false}}function lanCreate(ditto){{throw new Error("Can't create LAN handle, P2P LAN transport is not supported on this platform.")}}function lanDestroy(lan){{throw new Error("Can't destroy LAN handle, P2P LAN transport is not supported on this platform.")}}function awdlIsAvailable(ditto){{return false}}function awdlCreate(ditto){{throw new Error("Can't create AWDL handle, P2P AWDL transport is not supported on this platform.")}}function awdlDestroy(awdl){{throw new Error("Can't destroy AWDL handle, P2P AWDL transport is not supported on this platform.")}}const fullBuildVersionString="3.0.6-experimental.node-loading-issues.2.linux-x64";const defaultDittoWasmFileURL="https://software.ditto.live/js/Ditto/3.0.6-experimental.node-loading-issues.2.linux-x64/ditto.wasm";let isInitialized=false;async function init(options={}){if(!isInitialized){{const webAssemblyModule=options.webAssemblyModule||defaultDittoWasmFileURL;await init$2(webAssemblyModule);await init$1();initSDKVersion("Web","JavaScript",fullBuildVersionString);loggerInit()}isInitialized=true}}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 Logger{static setLogFile(path){if(path){loggerSetLogFile(path);this["logFile"]=path}else{loggerSetLogFile(null);delete this["logFile"]}}static setLogFileURL(url){this.setLogFile(url===null||url===void 0?void 0:url.pathname)}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 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 it's static properties & methods directly instead.")}}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.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;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;delete this.callbacksByToken[token];(_a=this.keepAlive)===null||_a===void 0?void 0:_a.release(`${this.id}.${token}`);this.unregisterIfNeeded()}notify(...args){const processedArgs=this.process(...args);for(const token in this.callbacksByToken){const callback=this.callbacksByToken[token];callback(...processedArgs)}}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()}}async finalize(token){await this.removeObserver(token)}}class Observer{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 typeof this.token==="undefined"}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);class Authenticator{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.`)}}class OnlineAuthenticator extends Authenticator{async loginWithToken(token,provider){await dittoAuthClientLoginWithToken(this.authClientPointer,token,provider)}async loginWithUsernameAndPassword(username,password,provider){await dittoAuthClientLoginWithUsernameAndPassword(this.authClientPointer,username,password,provider)}async logout(cleanupFn){const ditto=this.ditto.deref();if(ditto){await dittoAuthClientLogout(this.authClientPointer);ditto.stopSync();cleanupFn===null||cleanupFn===void 0?void 0:cleanupFn(this.ditto)}else{Logger.warning("Unable to logout, related Ditto object does not exist anymore.")}}constructor(keepAlive,authClientPointer,ditto,authenticationHandler){super(keepAlive);this["loginSupported"]=true;this["status"]={isAuthenticated:false,userID:null};this.authClientPointer=authClientPointer;this.ditto=new WeakRef(ditto);this.authenticationHandler=authenticationHandler;this.updateAndNotify(false);OnlineAuthenticator.finalizationRegistry.register(this,authClientPointer)}"@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 wasAuthenticated=this.status.isAuthenticated;const previousUserID=this.status.userID;const isAuthenticated=dittoAuthClientIsWebValid(this.authClientPointer);const userID=dittoAuthClientUserID(this.authClientPointer);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)}}}static finalize(authClientPointer){dittoAuthClientFree(authClientPointer)}}OnlineAuthenticator.finalizationRegistry=new FinalizationRegistry(OnlineAuthenticator.finalize);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"];const NO_PREFERRED_ROUTE_HINT=0;class TransportConfig{constructor(){this.peerToPeer={bluetoothLE:{isEnabled:false},awdl:{isEnabled:false},lan:{isEnabled:false,isMdnsEnabled:true,isMulticastEnabled:true}};this.connect={tcpServers:[],websocketURLs:[]};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}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.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}}const POW_2_24=5.960464477539063e-8;const POW_2_32=4294967296;const POW_2_53=9007199254740992;const DECODE_CHUNK_SIZE=8192;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}class TaggedValue{constructor(value,tag){this.value=value;this.tag=tag}}function decode(data,tagger,simpleValue){let dataView=new DataView(data);let ta=new Uint8Array(data);let offset=0;let tagValueFunction=function(value,tag){return new TaggedValue(value,tag)};let simpleValFunction=function(value){return undefined};if(typeof tagger==="function")tagValueFunction=tagger;if(typeof simpleValue==="function")simpleValFunction=simpleValue;function commitRead(length,value){offset+=length;return value}function readArrayBuffer(length){return commitRead(length,new Uint8Array(data,offset,length))}function readFloat16(){let tempArrayBuffer=new ArrayBuffer(4);let tempDataView=new DataView(tempArrayBuffer);let value=readUint16();let sign=value&32768;let exponent=value&31744;let 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 readUint32()*POW_2_32+readUint32()}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)return readUint64();if(additionalInformation===31)return-1;throw new Error("Invalid length encoding")}function readIndefiniteStringLength(majorType){let initialByte=readUint8();if(initialByte===255)return-1;let length=readLength(initialByte&31);if(length<0||initialByte>>5!==majorType)throw new Error("Invalid indefinite length element");return 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(){let initialByte=readUint8();let majorType=initialByte>>5;let 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("Invalid length");switch(majorType){case 0:return length;case 1:return-1-length;case 2:if(length<0){let elements=[];let fullArrayLength=0;while((length=readIndefiniteStringLength(majorType))>=0){fullArrayLength+=length;elements.push(readArrayBuffer(length))}let fullArray=new Uint8Array(fullArrayLength);let fullArrayOffset=0;for(i=0;i<elements.length;++i){fullArray.set(elements[i],fullArrayOffset);fullArrayOffset+=elements[i].length}return fullArray}return readArrayBuffer(length);case 3:let 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 string;case 4:let retArray;if(length<0){retArray=[];while(!readBreak())retArray.push(decodeItem())}else{retArray=new Array(length);for(i=0;i<length;++i)retArray[i]=decodeItem()}return retArray;case 5:let retObject={};for(i=0;i<length||length<0&&!readBreak();++i){let key=decodeItem();retObject[key]=decodeItem()}return retObject;case 6:return tagValueFunction(decodeItem(),length);case 7:switch(length){case 20:return false;case 21:return true;case 22:return null;case 23:return undefined;default:return simpleValFunction(length)}}}let ret=decodeItem();if(offset!==data.byteLength)throw new Error("Remaining bytes");return ret}function encode(value){let data=new ArrayBuffer(256);let dataView=new DataView(data);let byteView=new Uint8Array(data);let lastLength;let offset=0;function prepareWrite(length){let newByteLength=data.byteLength;let requiredLength=offset+length;while(newByteLength<requiredLength)newByteLength<<=1;if(newByteLength!==data.byteLength){let oldDataView=dataView;data=new ArrayBuffer(newByteLength);dataView=new DataView(data);byteView=new Uint8Array(data);let 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){let low=val%POW_2_32;let high=(val-low)/POW_2_32;let view=prepareWrite(8);view.setUint32(offset,high);view.setUint32(offset+4,low);commitWrite()}function writeVarUint(val,mod){if(val<=255){if(val<24){writeUint8(val|mod)}else{writeUint8(24|mod);writeUint8(val)}}else if(val<=65535){writeUint8(25|mod);writeUint16(val)}else if(val<=4294967295){writeUint8(26|mod);writeUint32(val)}else{writeUint8(27|mod);writeUint64(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 encodeItem(val){let i;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"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":let utf8data=[];for(i=0;i<val.length;++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 length;let converted;if(Array.isArray(val)){length=val.length;writeTypeAndLength(4,length);for(i=0;i<length;i+=1)encodeItem(val[i])}else if(val instanceof Uint8Array){writeTypeAndLength(2,val.length);writeUint8Array(val)}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{let keys=Object.keys(val);length=keys.length;writeTypeAndLength(5,length);for(i=0;i<length;i+=1){let key=keys[i];encodeItem(key);encodeItem(val[key])}}}}encodeItem(value);if("slice"in data)return data.slice(0,offset);let ret=new ArrayBuffer(offset);let retView=new DataView(ret);for(let i=0;i<offset;++i)retView.setUint8(i,dataView.getUint8(i));return ret}const CBOR$1={decode:decode,encode:encode};class CBOR{static encode(data){const arrayBuffer=CBOR$1.encode(data);return new Uint8Array(arrayBuffer)}static decode(data){const arrayBuffer=data.buffer;return CBOR$1.decode(arrayBuffer)}}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}class Attachment{get metadata(){return this.token.metadata}getData(){{const dittoPointer=dittoBridge.pointerFor(this.ditto);const attachmentHandlePointer=attachmentBridge.pointerFor(this);return dittoGetCompleteAttachmentData(dittoPointer,attachmentHandlePointer)}}copyToPath(path){{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}}const attachmentBridge=new Bridge(Attachment,freeAttachmentHandle);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}}class AttachmentFetcher{stop(){AttachmentFetcher.stopWithContextInfo({ditto:this.ditto,attachmentTokenID:this.token.id,cancelTokenPromise:this.cancelTokenPromise})}then(onfulfilled,onrejected){return this.attachment.then(onfulfilled,onrejected)}constructor(ditto,token,eventHandler){this.ditto=ditto;this.token=token;this.eventHandler=eventHandler||null;this.cancelTokenPromise=null;const eventHandlerOrNoOp=eventHandler||function(){};this.attachment=new Promise(((resolve,reject)=>{const dittoPointer=dittoBridge.pointerFor(ditto);this.cancelTokenPromise=dittoResolveAttachment(dittoPointer,token.id,{onComplete:attachmentHandlePointer=>{this["eventHandler"]=null;this["cancelTokenPromise"]=null;const attachment=new Attachment(this.ditto,this.token);attachmentBridge.bridge(attachmentHandlePointer,(()=>attachment),{throwIfAlreadyBridged:true});eventHandlerOrNoOp({type:"Completed",attachment:attachment});resolve(attachment)},onProgress:(downloaded,toDownload)=>{eventHandlerOrNoOp({type:"Progress",totalBytes:toDownload,downloadedBytes:downloaded})},onDelete:()=>{this["eventHandler"]=null;this["cancelTokenPromise"]=null;eventHandlerOrNoOp({type:"Deleted"});resolve(null)}},(err=>{this["eventHandler"]=null;this["cancelTokenPromise"]=null;reject(err)}))}));const contextInfo={ditto:ditto,attachmentTokenID:token.id,cancelTokenPromise:this.cancelTokenPromise};AttachmentFetcher.finalizationRegistry.register(this,contextInfo,contextInfo)}static stopWithContextInfo(contextInfo){step((async()=>{const cancelToken=await contextInfo.cancelTokenPromise;if(cancelToken){const dittoPointer=dittoBridge.pointerFor(contextInfo.ditto);dittoCancelResolveAttachment(dittoPointer,contextInfo.attachmentTokenID,cancelToken)}}))}}AttachmentFetcher.finalizationRegistry=new FinalizationRegistry(AttachmentFetcher.stopWithContextInfo);class Subscription{get collectionName(){return this.collection.name}cancel(){if(!this.isCancelled){this["isCancelled"]=true;Subscription.remove(this,this.contextInfo)}}constructor(collection,query,queryArgsCBOR,orderBys,limit,offset){this.isCancelled=false;this.query=query;this.queryArgsCBOR=queryArgsCBOR;this.collection=collection;this.contextInfo={ditto:collection.store.ditto,collectionName:collection.name,query:query,queryArgsCBOR:queryArgsCBOR,orderBys:orderBys,limit:limit,offset:offset};Subscription.add(this,this.contextInfo)}static add(subscription,contextInfo){const dittoX=dittoBridge.pointerFor(contextInfo.ditto);addSubscription(dittoX,contextInfo.collectionName,contextInfo.query,contextInfo.queryArgsCBOR,contextInfo.orderBys,contextInfo.limit,contextInfo.offset);this.finalizationRegistry.register(subscription,contextInfo,contextInfo)}static remove(subscription,contextInfo){const dittoX=dittoBridge.pointerFor(contextInfo.ditto);removeSubscription(dittoX,contextInfo.collectionName,contextInfo.query,contextInfo.queryArgsCBOR,contextInfo.orderBys,contextInfo.limit,contextInfo.offset);if(subscription)this.finalizationRegistry.unregister(contextInfo)}}Subscription.finalizationRegistry=new FinalizationRegistry((contextInfo=>{Subscription.remove(null,contextInfo)}));const privateToken$1="@ditto.64d129224a5377b63e9727479ec987d9";class Counter{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.`)}}}class RGA{get value(){return this["@ditto.value"]}constructor(array=[]){this["@ditto.value"]=array}static"@ditto.create"(path,value){const rga=new RGA(value);rga["@ditto.path"]=path;rga["@ditto.value"]=value;return rga}}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}}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.rga){const augmentedValue=augmentJSONValue(json[DittoCRDTValueKey],mutDoc,workingPath);return RGA["@ditto.create"](workingPath,augmentedValue)}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 RGA){const rgaJSON={};rgaJSON[DittoCRDTTypeKey]=DittoCRDTType.rga;rgaJSON[DittoCRDTValueKey]=desugarJSObject(jsObj.value);return rgaJSON}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{return jsObj}}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 rga(){const underlyingValue=this.underlyingValueForPathType("Rga");return typeof underlyingValue!=="undefined"?RGA["@ditto.create"](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 documentX=documentBridge.pointerFor(document);const cborPathResult=documentGetCBORWithPathType(documentX,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 rga(){const underlyingValue=this.underlyingValueForPathType("Rga");return typeof underlyingValue!=="undefined"?RGA["@ditto.create"](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 documentX=mutableDocumentBridge.pointerFor(document);const cborPathResult=documentGetCBORWithPathType(documentX,path,pathType);return cborPathResult.cbor!==null?CBOR.decode(cborPathResult.cbor):undefined}"@ditto.increment"(amount){const documentPointer=mutableDocumentBridge.pointerFor(this.mutableDocument);documentIncrementCounter(documentPointer,this.path,amount);const updateResult=UpdateResult.incremented(this.mutableDocument.id,this.path,amount);this.recordUpdateResult(updateResult)}"@ditto.set"(value,isDefault){const documentX=mutableDocumentBridge.pointerFor(this.mutableDocument);const valueJSON=desugarJSObject(value,false);const valueCBOR=CBOR.encode(valueJSON);if(isDefault){documentSetCBORWithTimestamp(documentX,this.path,valueCBOR,true,0)}else{documentSetCBOR(documentX,this.path,valueCBOR,true)}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 documentPointer=mutableDocumentBridge.pointerFor(this.mutableDocument);documentRemove(documentPointer,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 documentPointers=documents.map((doc=>documentBridge.pointerFor(doc)));return documentsHash(documentPointers)}static hashMnemonic(documentOrMany){const documents=documentsFrom(documentOrMany);const documentPointers=documents.map((doc=>documentBridge.pointerFor(doc)));return documentsHashMnemonic(documentPointers)}get id(){let id=this["@ditto.id"];if(typeof id==="undefined"){const documentX=documentBridge.pointerFor(this);const documentIDCBOR=documentID(documentX);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 documentX=documentBridge.pointerFor(document);return documentID(documentX)}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 documentX=mutableDocumentBridge.pointerFor(this);const documentIDCBOR=documentID(documentX);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 documentX=mutableDocumentBridge.pointerFor(mutableDocument);return documentID(documentX)}}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR;MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;const documentBridge=new Bridge(Document,documentFree);const mutableDocumentBridge=new Bridge(MutableDocument,documentFree);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 LiveQueryEventInitial{constructor(){this.isInitial=true}hash(documents){return documentsHash(documents.map((doc=>documentBridge.pointerFor(doc))))}hashMnemonic(documents){return documentsHashMnemonic(documents.map((doc=>documentBridge.pointerFor(doc))))}}class LiveQueryEventUpdate{hash(documents){return documentsHash(documents.map((doc=>documentBridge.pointerFor(doc))))}hashMnemonic(documents){return documentsHashMnemonic(documents.map((doc=>documentBridge.pointerFor(doc))))}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){return documentsHash(document===null?[]:[documentBridge.pointerFor(document)])}hashMnemonic(document){return documentsHashMnemonic(document===null?[]:[documentBridge.pointerFor(document)])}constructor(isInitial,oldDocument){this.isInitial=isInitial;this.oldDocument=oldDocument}}class LiveQuery{get collectionName(){return this.collection.name}get isStopped(){return this.liveQueryID===null}stop(){var _a;const liveQueryID=this.liveQueryID;if(liveQueryID!==null){this.collection.store.ditto.keepAlive.release(`LiveQuery.${liveQueryID}`);this.liveQueryID=null;const dittoPointer=dittoBridge.pointerFor(this.collection.store.ditto);(_a=this.subscription)===null||_a===void 0?void 0:_a.cancel();liveQueryStop(dittoPointer,liveQueryID)}}constructor(query,queryArgs,queryArgsCBOR,orderBys,limit,offset,collection,subscription,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;if(subscription){this.subscription=subscription}const collectionName=collection.name;const weakDitto=new WeakRef(collection.store.ditto);let liveQueryID=undefined;const signalNext=async()=>{const ditto=weakDitto.deref();if(ditto){const dittoPointer=dittoBridge.pointerFor(ditto);await liveQuerySignalAvailableNext(dittoPointer,liveQueryID)}};const dittoPointer=dittoBridge.pointerFor(collection.store.ditto);liveQueryID=liveQueryRegister(dittoPointer,collectionName,query,queryArgsCBOR,this.orderBys,limit,offset,(cCBParams=>{const documents=cCBParams.documents.map((ptr=>documentBridge.bridge(ptr)));let event;if(cCBParams.is_initial){event=new LiveQueryEventInitial}else{event=new LiveQueryEventUpdate({oldDocuments:cCBParams.old_documents.map((ptr=>documentBridge.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;step((async()=>await liveQueryStart(dittoPointer,liveQueryID)));collection.store.ditto.keepAlive.retain(`LiveQuery.${liveQueryID}`)}async signalNext(){const dittoPointer=dittoBridge.pointerFor(this.collection.store.ditto);await liveQuerySignalAvailableNext(dittoPointer,this.liveQueryID)}}class PendingCursorOperation{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}subscribe(){return new Subscription(this.collection,this.query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)}observeLocal(handler){return this._observe(handler,false,false)}observeLocalWithNextSignal(handler){return this._observe(handler,false,true)}async remove(){const query=this.query;const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);const documentsX=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const writeTransactionX=await writeTransaction(dittoX);const documentsX=await collectionRemoveQueryStr(dittoX,this.collection.name,writeTransactionX,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);await writeTransactionCommit(dittoX,writeTransactionX);return documentsX}));return documentsX.map((idCBOR=>new DocumentID(idCBOR,true)))}async evict(){const query=this.query;const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);const documentsX=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const writeTransactionX=await writeTransaction(dittoX);const documentsX=await collectionEvictQueryStr(dittoX,this.collection.name,writeTransactionX,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);await writeTransactionCommit(dittoX,writeTransactionX);return documentsX}));return documentsX.map((idCBOR=>new DocumentID(idCBOR,true)))}async exec(){const query=this.query;const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);const documentsX=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionExecQueryStr(dittoX,this.collection.name,null,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)));return documentsX.map((documentX=>documentBridge.bridge(documentX)))}async update(closure){return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const query=this.query;const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);const writeTransactionX=await writeTransaction(dittoX);const documentsX=await collectionExecQueryStr(dittoX,this.collection.name,writeTransactionX,query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);const mutableDocuments=documentsX.map((documentX=>mutableDocumentBridge.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;mutableDocumentBridge.pointerFor(mutableDocument);mutableDocumentBridge.unregister(mutableDocument)}await collectionUpdateMultiple(dittoX,this.collection.name,writeTransactionX,documentsX);await writeTransactionCommit(dittoX,writeTransactionX);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}_observe(handler,createSubscription,waitForNextSignal){const subscription=createSubscription?this.subscribe():null;function wrappedHandler(documents,event,nextSignal){try{return handler.call(this,documents,event)}finally{nextSignal()}}const handlerOrWrapped=waitForNextSignal?handler:wrappedHandler;return new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,subscription,handlerOrWrapped)}then(onfulfilled,onrejected){return this.exec().then(onfulfilled,onrejected)}}class PendingIDSpecificOperation{subscribe(){return new Subscription(this.collection,this.query,null,[],-1,0)}observeLocal(handler){return this._observe(handler,false,false)}observeLocalWithNextSignal(handler){return this._observe(handler,false,true)}async remove(){const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const writeTransactionX=await writeTransaction(dittoX);const didRemove=await collectionRemove(dittoX,this.collection.name,writeTransactionX,this.documentIDCBOR);await writeTransactionCommit(dittoX,writeTransactionX);return didRemove}))}async evict(){const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const writeTransactionX=await writeTransaction(dittoX);const didEvict=await collectionEvict(dittoX,this.collection.name,writeTransactionX,this.documentIDCBOR);await writeTransactionCommit(dittoX,writeTransactionX);return didEvict}))}async exec(){const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const readTransactionX=await readTransaction(dittoX);const documentX=await collectionGet(dittoX,this.collection.name,this.documentIDCBOR,readTransactionX);let document=undefined;if(documentX)document=documentBridge.bridge(documentX);readTransactionFree(readTransactionX);return document}))}async update(closure){const dittoX=dittoBridge.pointerFor(this.collection.store.ditto);const readTransactionX=await readTransaction(dittoX);const documentX=await collectionGet(dittoX,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=mutableDocumentBridge.bridge(documentX,(()=>new MutableDocument));closure(mutableDocument);mutableDocumentBridge.unregister(mutableDocument);const writeTransactionX=await writeTransaction(dittoX);await collectionUpdate(dittoX,this.collection.name,writeTransactionX,documentX);await writeTransactionCommit(dittoX,writeTransactionX);return mutableDocument["@ditto.updateResults"].slice()}constructor(documentID,collection){this.documentID=documentID;this.collection=collection;this.documentIDCBOR=documentID.toCBOR()}_observe(handler,createSubscription,waitForNextSignal){const subscription=createSubscription?this.subscribe():null;return new LiveQuery(this.query,null,null,[],-1,0,this.collection,subscription,((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()}}}))}then(onfulfilled,onrejected){return this.exec().then(onfulfilled,onrejected)}get query(){return`_id == ${this.documentID.toQueryCompatibleString()}`}}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={}){var _a;const writeStrategy=(_a=options.writeStrategy)!==null&&_a!==void 0?_a:"merge";const ditto=this.store.ditto;const dittoPointer=dittoBridge.pointerFor(ditto);const id=value._id;let documentID;if(typeof id==="undefined"){documentID=undefined}else if(id instanceof DocumentID){documentID=id}else{documentID=new DocumentID(id)}const documentIDCBOR=typeof documentID==="undefined"?null:documentID.toCBOR();const documentValueJSON=desugarJSObject(value,true);const documentValueCBOR=CBOR.encode(documentValueJSON);const idCBOR=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionInsertValue(dittoPointer,this.name,documentValueCBOR,documentIDCBOR,writeStrategy)));return new DocumentID(idCBOR,true)}async newAttachment(pathOrData,metadata={}){const ditto=this.store.ditto;const dittoPointer=dittoBridge.pointerFor(ditto);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(dittoPointer,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 attachmentBridge.bridge(handle,(()=>attachment),{throwIfAlreadyBridged:true})}fetchAttachment(token,eventHandler){const ditto=this.store.ditto;return new AttachmentFetcher(ditto,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)}}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,false)}observeLocalWithNextSignal(handler){return this._observe(handler,false,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,createSubscription,waitForNextSignal){const weakThis=new WeakRef(this);const collectionsObservationHandler=function(documents,event,nextSignal){const strongThis=weakThis.deref();if(strongThis===null)return;const collections=collectionsFromDocuments(documents,strongThis.store);let collEvent;if(event.isInitial===true){collEvent=CollectionsEvent.initial(collections)}else{const oldCollections=collectionsFromDocuments(event.oldDocuments,strongThis.store);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,createSubscription,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 Store{collection(name){return new Collection(name,this)}collections(){return new PendingCollectionsOperation(this.ditto.store)}collectionNames(){return dittoGetCollectionNames(dittoBridge.pointerFor(this.ditto))}constructor(ditto){this.ditto=ditto}async registerLiveQueryWebhook(collectionName,query,url){const validatedQuery=validateQuery(query);const idCBOR=await liveQueryWebhookRegister(dittoBridge.pointerFor(this.ditto),collectionName,validatedQuery,[],0,0,url);return new DocumentID(idCBOR,true)}}function addressToString(address){return`${address.siteId}-${address.pubkey}`}class Presence{get graph(){const dittoPointer=dittoBridge.pointerFor(this.ditto);const graphJSONString=dittoPresenceV3(dittoPointer);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 dittoPointer=dittoBridge.pointerFor(this.ditto);dittoRegisterPresenceV3Callback(dittoPointer,callback)},unregister:()=>{const dittoPointer=dittoBridge.pointerFor(this.ditto);dittoClearPresenceV3Callback(dittoPointer)},process:presenceGraphJSONString=>{const presenceGraph=JSON.parse(presenceGraphJSONString);return[presenceGraph]}})}}class PresenceManager{constructor(ditto){this.ditto=ditto;this.isRegistered=false;this.currentRemotePeers=[];this.callbacksByPresenceToken={}}addObserver(callback){this.registerIfNeeded();const token=generateEphemeralToken();this.callbacksByPresenceToken[token]=callback;this.ditto.keepAlive.retain(`PresenceObservation.${token}`);callback(this.currentRemotePeers);return token}removeObserver(token){this.ditto.keepAlive.release(`PresenceObservation.${token}`);delete this.callbacksByPresenceToken[token];this.unregisterIfNeeded()}hasObservers(){return Object.keys(this.callbacksByPresenceToken).length>0}registerIfNeeded(){const needsToRegister=!this.isRegistered;if(needsToRegister){this.isRegistered=true;const dittoPointer=dittoBridge.pointerFor(this.ditto);const remotePeersJSONString=dittoPresenceV1(dittoPointer);this.currentRemotePeers=this.decode(remotePeersJSONString).sort(this.compareRemotePeers);dittoRegisterPresenceV1Callback(dittoPointer,this.handlePresenceV1Callback.bind(this))}}unregisterIfNeeded(){const needsToUnregister=!this.hasObservers()&&this.isRegistered;if(needsToUnregister){this.isRegistered=false;const dittoPointer=dittoBridge.pointerFor(this.ditto);dittoRegisterPresenceV1Callback(dittoPointer,null);this.currentRemotePeers=[]}}handlePresenceV1Callback(remotePeersJSONString){const remotePeers=this.decode(remotePeersJSONString).sort(this.compareRemotePeers);this.currentRemotePeers=remotePeers;this.notify()}notify(){for(const token in this.callbacksByPresenceToken){const callback=this.callbacksByPresenceToken[token];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"]}}))}finalize(token){this.removeObserver(token)}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 dittoPointer=dittoBridge.pointerFor(this.ditto);return dittoRegisterTransportConditionChangedCallback(dittoPointer,callback)}unregister(){const dittoPointer=dittoBridge.pointerFor(this.ditto);return dittoRegisterTransportConditionChangedCallback(dittoPointer,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 Sync{constructor(ditto){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,isWebValid:false,isX509Valid:false,isSyncActive:false};this.ditto=ditto;this.parameters=parameters;this.state=stateFrom(parameters);this.staticTCPClientsByAddress={};this.websocketClientsByURL={}}update(parameters){this["parameters"]={...parameters};const stateOld=this.state;const stateNew=stateFrom(this.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.state=stateNew}updatePeerToPeerBluetoothLE(stateOld,stateNew){dittoBridge.pointerFor(this.ditto);const bluetoothLEOld=stateOld.effectiveTransportConfig.peerToPeer.bluetoothLE;const bluetoothLENew=stateNew.effectiveTransportConfig.peerToPeer.bluetoothLE;const shouldStart=!bluetoothLEOld.isEnabled&&bluetoothLENew.isEnabled;const shouldStop=bluetoothLEOld.isEnabled&&!bluetoothLENew.isEnabled;if(shouldStart&&this.bluetoothLETransportPointer)throw new Error(`Internal inconsistency, when starting BLE transport, no BLE transport pointer should exist.`);if(shouldStop&&!this.bluetoothLETransportPointer)throw new Error(`Internal inconsistency, when stopping BLE transport, a BLE transport pointer should exist.`);if(shouldStart){if(!bleIsAvailable())throw new Error("Can't start P2P BluetoothLE transport because not available.");this.bluetoothLETransportPointer=bleCreate()}if(shouldStop){bleDestroy(this.bluetoothLETransportPointer);delete this.bluetoothLETransportPointer}}updatePeerToPeerAWDL(stateOld,stateNew){dittoBridge.pointerFor(this.ditto);const awdlOld=stateOld.effectiveTransportConfig.peerToPeer.awdl;const awdlNew=stateNew.effectiveTransportConfig.peerToPeer.awdl;const shouldStart=!awdlOld.isEnabled&&awdlNew.isEnabled;const shouldStop=awdlOld.isEnabled&&!awdlNew.isEnabled;if(shouldStart&&this.awdlTransportPointer)throw new Error(`Internal inconsistency, when starting AWDL transport, no AWDL transport pointer should exist.`);if(shouldStop&&!this.awdlTransportPointer)throw new Error(`Internal inconsistency, when stopping AWDL transport, an AWDL transport pointer should exist.`);if(shouldStart){if(!awdlIsAvailable())throw new Error("Can't start P2P AWDL transport because not available.");this.awdlTransportPointer=awdlCreate()}if(shouldStop){awdlDestroy(this.awdlTransportPointer);this.awdlTransportPointer=null}}updatePeerToPeerLAN(stateOld,stateNew){const dittoPointer=dittoBridge.pointerFor(this.ditto);const lanOld=stateOld.effectiveTransportConfig.peerToPeer.lan;const lanNew=stateNew.effectiveTransportConfig.peerToPeer.lan;if(lanOld.isEnabled){if(lanOld.isMdnsEnabled){lanDestroy(this.lanTransportPointer);delete this.lanTransportPointer}if(lanOld.isMulticastEnabled){dittoRemoveMulticastTransport(dittoPointer)}}if(lanNew.isEnabled){if(lanNew.isMdnsEnabled){if(!lanIsAvailable())throw new Error("Can't start P2P LAN transport because not available.");this.lanTransportPointer=lanCreate()}if(lanNew.isMulticastEnabled){dittoAddMulticastTransport(dittoPointer)}}}updateListenTCP(stateOld,stateNew){const tcpOld=stateOld.effectiveTransportConfig.listen.tcp;const tcpNew=stateNew.effectiveTransportConfig.listen.tcp;if(TransportConfig.areListenTCPsEqual(tcpNew,tcpOld))return;const dittoPointer=dittoBridge.pointerFor(this.ditto);if(tcpOld.isEnabled)dittoStopTCPServer(dittoPointer);if(tcpNew.isEnabled)dittoStartTCPServer(dittoPointer,`${tcpNew.interfaceIP}:${tcpNew.port}`)}updateListenHTTP(stateOld,stateNew){const httpOld=stateOld.effectiveTransportConfig.listen.http;const httpNew=stateNew.effectiveTransportConfig.listen.http;if(TransportConfig.areListenHTTPsEqual(httpOld,httpNew))return;const dittoPointer=dittoBridge.pointerFor(this.ditto);if(httpOld.isEnabled)dittoStopHTTPServer(dittoPointer);if(httpNew.isEnabled){dittoStartHTTPServer(dittoPointer,`${httpNew.interfaceIP}:${httpNew.port}`,httpNew.staticContentPath||null,httpNew.websocketSync?"Enabled":"Disabled",httpNew.tlsCertificatePath||null,httpNew.tlsKeyPath||null)}}updateConnectTCPServers(stateOld,stateNew){const currentTCPServers=Object.getOwnPropertyNames(this.staticTCPClientsByAddress);const desiredTCPServers=stateNew.effectiveTransportConfig.connect.tcpServers;const tcpServersToConnectToSet=new Set(desiredTCPServers);for(const tcpServer of currentTCPServers)tcpServersToConnectToSet.delete(tcpServer);const tcpServersToDisconnectFromSet=new Set(currentTCPServers);for(const tcpServer of desiredTCPServers)tcpServersToDisconnectFromSet.delete(tcpServer);const tcpServersToConnectTo=tcpServersToConnectToSet.values();const tcpServersToDisconnectFrom=tcpServersToDisconnectFromSet.values();for(const tcpServer of tcpServersToConnectTo){const staticTCPClientPointer=addStaticTCPClient(dittoBridge.pointerFor(this.ditto),tcpServer);const staticTCPClient=staticTCPClientBridge.bridge(staticTCPClientPointer);this.staticTCPClientsByAddress[tcpServer]=staticTCPClient}for(const tcpServer of tcpServersToDisconnectFrom){const staticTCPClient=this.staticTCPClientsByAddress[tcpServer];if(!staticTCPClient)throw new Error(`Internal inconsistency, can't disconnect from TCP address '${tcpServer}', no staticTCPClient found.`);const staticTCPClientPointer=staticTCPClientBridge.pointerFor(staticTCPClient);staticTCPClientBridge.unregister(staticTCPClient);staticTCPClientFreeHandle(staticTCPClientPointer);delete this.staticTCPClientsByAddress[tcpServer]}}updateConnectWebsocketURLs(stateOld,stateNew){const currentWebsocketURLs=Object.getOwnPropertyNames(this.websocketClientsByURL);const desiredWebsocketURLs=stateNew.effectiveTransportConfig.connect.websocketURLs.slice();const websocketURLsToConnectToSet=new Set(desiredWebsocketURLs);for(const websocketURL of currentWebsocketURLs)websocketURLsToConnectToSet.delete(websocketURL);const websocketURLsToDisconnectFromSet=new Set(currentWebsocketURLs);for(const websocketURL of desiredWebsocketURLs)websocketURLsToDisconnectFromSet.delete(websocketURL);const websocketURLsToConnectTo=websocketURLsToConnectToSet.values();const websocketURLsToDisconnectFrom=websocketURLsToDisconnectFromSet.values();const routingHint=stateNew.effectiveTransportConfig.global.routingHint;for(const websocketURL of websocketURLsToConnectTo){const websocketClientPointer=addWebsocketClient(dittoBridge.pointerFor(this.ditto),websocketURL,routingHint);const websocketClient=websocketClientBridge.bridge(websocketClientPointer);this.websocketClientsByURL[websocketURL]=websocketClient}for(const websocketURL of websocketURLsToDisconnectFrom){const websocketClient=this.websocketClientsByURL[websocketURL];if(!websocketClient)throw new Error(`Internal inconsistency, can't disconnect from websocket URL '${websocketURL}', no websocketClient found.`);const websocketClientPointer=websocketClientBridge.pointerFor(websocketClient);websocketClientBridge.unregister(websocketClient);websocketClientFreeHandle(websocketClientPointer);delete this.websocketClientsByURL[websocketURL]}}updateGlobal(stateOld,stateNew){if(stateOld.effectiveTransportConfig.global.syncGroup!==stateNew.effectiveTransportConfig.global.syncGroup){dittoSetSyncGroup(dittoBridge.pointerFor(this.ditto),stateNew.effectiveTransportConfig.global.syncGroup)}}}function stateFrom(parameters){var _a;const transportConfig=parameters.transportConfig.copy();const identity=parameters.identity;const isSyncActive=parameters.isSyncActive;const isX509Valid=parameters.isX509Valid;const isWebValid=parameters.isWebValid;transportConfig.connect.tcpServers;transportConfig.connect.websocketURLs;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=identity.hasOwnProperty("enableDittoCloudSync")?identity.enableDittoCloudSync:true}{const enabledP2PTransports=[];if(transportConfig.peerToPeer.bluetoothLE.isEnabled){enabledP2PTransports.push("BluetoothLE")}if(transportConfig.peerToPeer.awdl.isEnabled){enabledP2PTransports.push("AWDL")}if(transportConfig.peerToPeer.lan.isEnabled){enabledP2PTransports.push("LAN")}if(enabledP2PTransports.length>0){throw new Error(`Ditto does not support P2P transports when running in the browser, but the following were enabled: ${enabledP2PTransports.join(", ")}`)}}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)}if(transportConfig.peerToPeer.lan.isEnabled&&!transportConfig.listen.tcp.isEnabled){transportConfig.listen.tcp.isEnabled=true;transportConfig.listen.tcp.interfaceIP="0.0.0.0";transportConfig.listen.tcp.port=0}return{underlyingSyncParameters:parameters,effectiveTransportConfig:transportConfig.freeze()}}class Ditto{get sdkVersion(){dittoBridge.pointerFor(this);return dittoGetSDKVersion()}constructor(identity,path){this.isWebValid=false;this.isX509Valid=false;const isPathGiven=path&&path.trim().length>0;const identityOrDefault=identity!==null&&identity!==void 0?identity:{type:"offlinePlayground",appID:""};const pathOrDefault=isPathGiven?path:"ditto";const validIdentity=Object.freeze(this.validateIdentity(identityOrDefault));this.identity=Object.freeze(validIdentity);this.path=pathOrDefault;{this.deviceName=navigator.userAgent}this.keepAlive=new KeepAlive;const uninitializedDittoX=uninitializedDittoMake(pathOrDefault);let secondsRemainingUntilAuthenticationExpires=null;const weakThis=new WeakRef(this);const authClientX=(()=>{var _a,_b,_c;if(validIdentity.type==="offlinePlayground"){return dittoAuthClientMakeForDevelopment(pathOrDefault,validIdentity.appID,(_a=validIdentity.siteID)!==null&&_a!==void 0?_a:0)}if(validIdentity.type==="manual"){return dittoAuthClientMakeWithStaticX509(validIdentity.certificate)}if(validIdentity.type==="sharedKey"){return dittoAuthClientMakeWithSharedKey(pathOrDefault,validIdentity.appID,validIdentity.sharedKey,validIdentity.siteID)}if(validIdentity.type==="onlinePlayground"){const authURL=(_b=validIdentity.customAuthURL)!==null&&_b!==void 0?_b:defaultAuthURL(validIdentity.appID);return dittoAuthClientMakeAnonymousClient(pathOrDefault,validIdentity.appID,validIdentity.token,authURL)}if(validIdentity.type==="onlineWithAuthentication"){const authURL=(_c=validIdentity.customAuthURL)!==null&&_c!==void 0?_c:defaultAuthURL(validIdentity.appID);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}}));return dittoAuthClientMakeWithWeb(pathOrDefault,validIdentity.appID,authURL,loginProviderX)}throw new Error(`Can't create Ditto, unsupported identity type: ${validIdentity}`)})();dittoAuthClientSetValidityListener(authClientX,(function(...args){var _a;(_a=weakThis.deref())===null||_a===void 0?void 0:_a.authClientValidityChanged(...args)}));const isWebValid=dittoAuthClientIsWebValid(authClientX);const isX509Valid=dittoAuthClientIsX509Valid(authClientX);const siteID=dittoAuthClientGetSiteID(authClientX);const dittoX=dittoMake(uninitializedDittoX,authClientX);dittoBridge.bridge(dittoX,this);if(validIdentity.type==="onlineWithAuthentication"){this.auth=new OnlineAuthenticator(this.keepAlive,authClientX,this,validIdentity.authHandler)}else if(validIdentity.type==="onlinePlayground"){this.auth=new OnlineAuthenticator(this.keepAlive,authClientX,this,{authenticationRequired:function(authenticator){},authenticationExpiringSoon:function(authenticator,secondsRemaining){}})}else{dittoAuthClientFree(authClientX);this.auth=new NotAvailableAuthenticator(this.keepAlive)}const transportConfig=this.makeDefaultTransportConfig();this.siteID=siteID;this.transportConfig=transportConfig.copy().freeze();this.isX509Valid=isX509Valid;this.isWebValid=isWebValid;this.sync=new Sync(this);this.sync.update({isSyncActive:false,isX509Valid:isX509Valid,isWebValid:isWebValid,identity:validIdentity,transportConfig:transportConfig});this.isActivated=isWebBuild||!IdentityTypesRequiringOfflineLicenseToken.includes(validIdentity.type);this.store=new Store(this);this.presence=new Presence(this);this.presenceManager=new PresenceManager(this);this.transportConditionsManager=new TransportConditionsManager(this);if(secondsRemainingUntilAuthenticationExpires!==null){this.auth["@ditto.authenticationExpiring"](secondsRemainingUntilAuthenticationExpires)}}setOfflineOnlyLicenseToken(licenseToken){if(isWebBuild){Logger.info("Offline license token are ignored on web builds. Token validation will be skipped.")}else{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")}}}setTransportConfig(transportConfig){this.transportConfig;this["transportConfig"]=transportConfig.copy().freeze();const transportConfigNew=this.transportConfig;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})}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 dittoPointer=dittoBridge.pointerFor(this);dittoRunGarbageCollection(dittoPointer)}disableSyncWithV2(){const dittoPointer=dittoBridge.pointerFor(this);dittoDisableSyncWithV2(dittoPointer)}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})}validateIdentity(identity){const validIdentity={...identity};identity["appName"];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){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")}const dittoPointer=dittoBridge.pointerFor(this);this["isSyncActive"]=flag;const isWebValid=this.isWebValid;const isX509Valid=this.isX509Valid;const identity=this.identity;const transportConfig=this.transportConfig;dittoSetDeviceName(dittoPointer,this.deviceName);this.sync.update({identity:identity,transportConfig:transportConfig,isWebValid:isWebValid,isX509Valid:isX509Valid,isSyncActive:!!flag})}makeDefaultTransportConfig(){dittoBridge.pointerFor(this);const transportConfig=new TransportConfig;if(bleIsAvailable()){transportConfig.peerToPeer.bluetoothLE.isEnabled=true}if(awdlIsAvailable()){transportConfig.peerToPeer.awdl.isEnabled=true}if(lanIsAvailable()){transportConfig.peerToPeer.lan.isEnabled=true}return transportConfig.freeze()}}const dittoBridge=new Bridge(Ditto,(dittoPointer=>{dittoClearPresenceCallback(dittoPointer);dittoFree(dittoPointer)}));class Value{constructor(value,options={}){this.value=value;this.isDefault=!!options["isDefault"]}}export{Attachment,AttachmentFetcher,AttachmentToken,Authenticator,CBOR,Collection,CollectionsEvent,Counter,Ditto,Document,DocumentID,DocumentPath,IdentityTypesRequiringOfflineLicenseToken,KeepAlive,LiveQuery,LiveQueryEventInitial,LiveQueryEventUpdate,Logger,MutableCounter,MutableDocument,MutableDocumentPath,MutableRegister,NotAvailableAuthenticator,Observer,OnlineAuthenticator,PendingCollectionsOperation,PendingCursorOperation,PendingIDSpecificOperation,Presence,RGA,Register,SingleDocumentLiveQueryEvent,Store,Subscription,TransportConfig,UpdateResult,UpdateResultsMap,Value,addressToString,attachmentBridge,dittoBridge,documentBridge,init,mutableDocumentBridge,validateDocumentIDCBOR,validateDocumentIDValue};
|
|
1
|
+
const debugTypeNames=[],debugAllTypes=!1;class Meta{constructor(t,e,n){this.type=t,this.object=e,this.pointer=n}toString(){return`{ Meta | type: ${this.type.name}, object: ${this.object.deref()}, FFI address: ${this.pointer.addr}, FFI type: ${this.pointer.type} }`}}class Bridge{constructor(t,e,n={}){this.type=t,this.release=e,this.metaByAddrMap={},this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(this)),Bridge.all.push(new WeakRef(this))}pointerFor(t){return t["@ditto.ptr"]}objectFor(t){const e=this.metaByAddrMap[t.addr];if(!e)return;if(e.type!==this.type)throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${e.type} but this bridge is configured for ${this.type}`);const n=e.object.deref();if(!n)throw new Error(`Internal inconsistency, found a meta entry for an object whose object is undefined (garbage collected): ${t}`);return n}bridge(t,e,n={}){const r=n.throwIfAlreadyBridged,i=this.objectFor(t);if(i&&r)throw new Error(`Can't bridge, pointer has already been bridged: ${JSON.stringify(t)}`);if(i)return i;let o;if(e||(e=()=>Reflect.construct(this.type,[])),"function"==typeof e){if(o=e(),!o)throw new Error(`Can't bridge, expected passed in create function to return an object but got: ${o}`)}else o=e;return this.register(o,t),o}register(t,e){const n=t.constructor,r=this.type;if(n!==r)throw new Error(`Can't register, bridge is configured for type ${r.name} but passed in object is of type ${n.name}`);const i=this.pointerFor(t),o=this.metaByAddrMap[e.addr];if(i&&o)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${o.pointer}`);if(i&&!o)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no meta entry: ${t}`);if(!i&&o)throw new Error(`Internal inconsistency, trying to register an object which has a meta entry but no associated pointer: ${t}`);const a=new Meta(n,new WeakRef(t),e);t["@ditto.ptr"]=e,this.metaByAddrMap[a.pointer.addr]=a,this.finalizationRegistry.register(t,e,t),debugTypeNames.includes(this.type.name)&&console.log(`[VERBOSE] Bridge REGISTERED a new instance of ${this.type.name}, current count: ${Object.keys(this.metaByAddrMap).length}`)}unregister(t){const e=t.constructor,n=this.type;if(e!==n)throw new Error(`Can't unregister, bridge is configured for type ${n.name} but passed in object is of type ${e.name}`);const r=this.pointerFor(t);if(!r)throw new Error(`Can't unregister, object that has not been registered before: ${t}`);const i=this.metaByAddrMap[r.addr];if(!i)throw new Error(`Internal inconsistency, trying to unregister an object which has an associated pointer but no meta entry: ${t}`);if(i.type!==n)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry with a different type than that of the bridge: ${i}`);if(!i.object.deref())throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry whose object is undfined (garbage collected): ${i}`);if(i.object.deref()!==t)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry holding a different object: ${i}`);this.finalizationRegistry.unregister(t),delete this.metaByAddrMap[r.addr],delete t["@ditto.ptr"],debugTypeNames.includes(this.type.name)&&console.log(`[VERBOSE] Bridge UNREGISTERED an instance of ${this.type.name}, current count: ${Object.keys(this.metaByAddrMap).length}`)}unregisterAll(){debugTypeNames.includes(this.type.name)&&console.log(`[VERBOSE] Unregistering ALL bridged instances of type ${this.type.name}.`);for(const t of Object.values(this.metaByAddrMap)){const e=t.object.deref();e&&this.unregister(e)}}get count(){return Object.keys(this.metaByAddrMap).length}finalize(t){if(!this.metaByAddrMap[t.addr])throw new Error(`Internal inconsistency, tried to finalize an instance for a pointer, that has no meta entry: ${t}`);delete this.metaByAddrMap[t.addr],this.release(t),debugTypeNames.includes(this.type.name)&&console.log(`[VERBOSE] Bridge FINALIZED an instance of ${this.type.name}, current count: ${Object.keys(this.metaByAddrMap).length}`)}}Bridge.all=[];const isWebBuild=!0,defaultDittoCloudDomain="cloud.ditto.live";function defaultAuthURL(t){return`https://${t}.cloud.ditto.live`}function defaultDittoCloudURL(t){return`wss://${t}.cloud.ditto.live`}function validateNumber(t,e={}){var n;const r=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Number validation failed:",i=!!e.integer,o=e.min,a=e.max,s=e.minX,c=e.maxX;if("number"!=typeof t)throw new Error(`${r} '${t}' is not a number.`);if(i&&Math.floor(t)!==t)throw new Error(`${r} '${t}' is not an integer.`);if(void 0!==o&&t<o)throw new Error(`${r} '${t}' must be >= ${o}.`);if(void 0!==a&&t>a)throw new Error(`${r} '${t}' must be <= ${a}.`);if(void 0!==s&&t<=s)throw new Error(`${r} '${t}' must be > ${s}.`);if(void 0!==c&&t>=c)throw new Error(`${r} '${t}' must be < ${c}.`);return t}function validateQuery(t,e={}){var n;const r=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Query validation failed,";if("string"!=typeof t)throw new Error(`${r} query is not a string: ${t}`);if(""===t)throw new Error(`${r} query is an empty string.`);const i=t.trim();if(""===i)throw new Error(`${r} query contains only whitespace characters.`);return i}class StaticTCPClient{}class WebsocketClient{}const staticTCPClientBridge=new Bridge(StaticTCPClient,staticTCPClientFreeHandle),websocketClientBridge=new Bridge(WebsocketClient,websocketClientFreeHandle);function generateEphemeralToken(){let t;t=crypto;const e=new Uint16Array(16);t.getRandomValues(e);return Array.from(e).map((t=>t.toString(16))).join("")}function sleep(t){return new Promise(((e,n)=>{setTimeout(e,t)}))}async function step(t){return await sleep(0),t()}const performAsyncToWorkaroundNonAsyncFFIAPI=step;function to_string(t){return t.toString()}function is_number(t){return"number"==typeof t}function try_downsize(t){switch(typeof t){case"bigint":if(-Number.MAX_SAFE_INTEGER<=t&&t<=Number.MAX_SAFE_INTEGER)return Number(t);case"number":return t;default:throw new Error(`number or bigint expected, got \`${t}\``)}}function from_string(t){return BigInt(t)}function get_element(t,e){return t[e]}function typeof_(t){return typeof t}function mk_send_ret(){return function send_ret(t){return t}}let wasm;const heap=new Array(32).fill(void 0);function getObject(t){return heap[t]}heap.push(void 0,null,!0,!1);let heap_next=heap.length;function dropObject(t){t<36||(heap[t]=heap_next,heap_next=t)}function takeObject(t){const e=getObject(t);return dropObject(t),e}const cachedTextDecoder=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});cachedTextDecoder.decode();let cachedUint8Memory0=new Uint8Array;function getUint8Memory0(){return 0===cachedUint8Memory0.byteLength&&(cachedUint8Memory0=new Uint8Array(wasm.memory.buffer)),cachedUint8Memory0}function getStringFromWasm0(t,e){return cachedTextDecoder.decode(getUint8Memory0().subarray(t,t+e))}function addHeapObject(t){heap_next===heap.length&&heap.push(heap.length+1);const e=heap_next;return heap_next=heap[e],heap[e]=t,e}let WASM_VECTOR_LEN=0;const cachedTextEncoder=new TextEncoder("utf-8"),encodeString="function"==typeof cachedTextEncoder.encodeInto?function(t,e){return cachedTextEncoder.encodeInto(t,e)}:function(t,e){const n=cachedTextEncoder.encode(t);return e.set(n),{read:t.length,written:n.length}};function passStringToWasm0(t,e,n){if(void 0===n){const n=cachedTextEncoder.encode(t),r=e(n.length);return getUint8Memory0().subarray(r,r+n.length).set(n),WASM_VECTOR_LEN=n.length,r}let r=t.length,i=e(r);const o=getUint8Memory0();let a=0;for(;a<r;a++){const e=t.charCodeAt(a);if(e>127)break;o[i+a]=e}if(a!==r){0!==a&&(t=t.slice(a)),i=n(i,r,r=a+3*t.length);const e=getUint8Memory0().subarray(i+a,i+r);a+=encodeString(t,e).written}return WASM_VECTOR_LEN=a,i}function isLikeNone(t){return null==t}let cachedInt32Memory0=new Int32Array;function getInt32Memory0(){return 0===cachedInt32Memory0.byteLength&&(cachedInt32Memory0=new Int32Array(wasm.memory.buffer)),cachedInt32Memory0}function debugString(t){const e=typeof t;if("number"==e||"boolean"==e||null==t)return`${t}`;if("string"==e)return`"${t}"`;if("symbol"==e){const e=t.description;return null==e?"Symbol":`Symbol(${e})`}if("function"==e){const e=t.name;return"string"==typeof e&&e.length>0?`Function(${e})`:"Function"}if(Array.isArray(t)){const e=t.length;let n="[";e>0&&(n+=debugString(t[0]));for(let r=1;r<e;r++)n+=", "+debugString(t[r]);return n+="]",n}const n=/\[object ([^\]]+)\]/.exec(toString.call(t));let r;if(!(n.length>1))return toString.call(t);if(r=n[1],"Object"==r)try{return"Object("+JSON.stringify(t)+")"}catch(t){return"Object"}return t instanceof Error?`${t.name}: ${t.message}\n${t.stack}`:r}const CLOSURE_DTORS=new FinalizationRegistry((t=>{wasm.__wbindgen_export_2.get(t.dtor)(t.a,t.b)}));function makeMutClosure(t,e,n,r){const i={a:t,b:e,cnt:1,dtor:n},real=(...t)=>{i.cnt++;const e=i.a;i.a=0;try{return r(e,i.b,...t)}finally{0==--i.cnt?(wasm.__wbindgen_export_2.get(i.dtor)(e,i.b),CLOSURE_DTORS.unregister(i)):i.a=e}};return real.original=i,CLOSURE_DTORS.register(real,i,i),real}function __wbg_adapter_30(t,e){wasm._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h0129b967ac039f18(t,e)}function __wbg_adapter_33(t,e,n){wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hb5ade02e6eaa007a(t,e,addHeapObject(n))}function __wbg_adapter_36(t,e,n){wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hf3d57baca1da1c0a(t,e,addHeapObject(n))}function __wbg_adapter_39(t,e){wasm._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hdc33ecbb0cdb7076(t,e)}function __wbg_adapter_42(t,e,n){wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__haddad2acf3ad06dc(t,e,addHeapObject(n))}function ditto_register_presence_v1_callback(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_presence_v1_callback(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_presence_v3_callback(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_presence_v3_callback(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_log(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_log(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_minimum_log_level_get(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_minimum_log_level_get(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_minimum_log_level(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_minimum_log_level(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_emoji_headings_enabled_get(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_emoji_headings_enabled_get(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_emoji_headings_enabled(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_emoji_headings_enabled(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_enabled_get(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_enabled_get(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_enabled(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_enabled(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_init(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_init(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_set_log_file(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_set_log_file(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_logger_set_custom_log_cb(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_logger_set_custom_log_cb(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_add_subscription(t,e,n,r,i,o,a){try{const d=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_add_subscription(d,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a));var s=getInt32Memory0()[d/4+0],c=getInt32Memory0()[d/4+1];if(getInt32Memory0()[d/4+2])throw takeObject(c);return takeObject(s)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_remove_subscription(t,e,n,r,i,o,a){try{const d=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_remove_subscription(d,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a));var s=getInt32Memory0()[d/4+0],c=getInt32Memory0()[d/4+1];if(getInt32Memory0()[d/4+2])throw takeObject(c);return takeObject(s)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_get(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_get(a,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_remove(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_remove(a,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_evict(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_evict(a,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_update_multiple(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_update_multiple(a,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_update(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_update(a,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_insert_value(t,e,n,r,i,o,a){try{const d=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_insert_value(d,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a));var s=getInt32Memory0()[d/4+0],c=getInt32Memory0()[d/4+1];if(getInt32Memory0()[d/4+2])throw takeObject(c);return takeObject(s)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_get_collection_names(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_collection_names(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_documents_hash(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_documents_hash(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_documents_hash_mnemonic(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_documents_hash_mnemonic(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_evict_query_str(t,e,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_evict_query_str(l,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_remove_query_str(t,e,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_remove_query_str(l,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_collection_exec_query_str(t,e,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_collection_exec_query_str(l,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function jsDocsToCDocs(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.jsDocsToCDocs(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_logout(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_logout(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_login_with_credentials(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_login_with_credentials(a,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_login_with_token(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_login_with_token(o,addHeapObject(t),addHeapObject(e),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_is_x509_valid(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_is_x509_valid(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_user_id(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_user_id(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_is_web_valid(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_is_web_valid(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_get_site_id(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_get_site_id(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_free(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_free(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_make_with_static_x509(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_with_static_x509(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_make_with_shared_key(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_with_shared_key(a,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_make_anonymous_client(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_anonymous_client(a,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_make_for_development(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_for_development(o,addHeapObject(t),addHeapObject(e),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_make_with_web(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_with_web(a,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_make_login_provider(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_make_login_provider(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_auth_client_set_validity_listener(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_auth_client_set_validity_listener(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function verify_license(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.verify_license(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_signal_available_next(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_signal_available_next(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_stop(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_stop(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_start(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_start(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_register_str_detached(t,e,n,r,i,o,a,s){try{const l=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_register_str_detached(l,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a),addHeapObject(s));var c=getInt32Memory0()[l/4+0],d=getInt32Memory0()[l/4+1];if(getInt32Memory0()[l/4+2])throw takeObject(d);return takeObject(c)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_live_query_webhook_register_str(t,e,n,r,i,o,a){try{const d=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_live_query_webhook_register_str(d,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i),addHeapObject(o),addHeapObject(a));var s=getInt32Memory0()[d/4+0],c=getInt32Memory0()[d/4+1];if(getInt32Memory0()[d/4+2])throw takeObject(c);return takeObject(s)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_error_message(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_error_message(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_free(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_free(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_get_cbor_with_path_type(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_get_cbor_with_path_type(o,addHeapObject(t),addHeapObject(e),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_remove(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_remove(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_set_cbor_with_timestamp(t,e,n,r,i){try{const s=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_set_cbor_with_timestamp(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_set_cbor(t,e,n,r){try{const a=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_set_cbor(a,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r));var i=getInt32Memory0()[a/4+0],o=getInt32Memory0()[a/4+1];if(getInt32Memory0()[a/4+2])throw takeObject(o);return takeObject(i)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_increment_counter(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_increment_counter(o,addHeapObject(t),addHeapObject(e),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_id(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_id(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_init_sdk_version(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_init_sdk_version(o,addHeapObject(t),addHeapObject(e),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_get_sdk_version(){try{const n=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_sdk_version(n);var t=getInt32Memory0()[n/4+0],e=getInt32Memory0()[n/4+1];if(getInt32Memory0()[n/4+2])throw takeObject(e);return takeObject(t)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_disable_sync_with_v2(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_disable_sync_with_v2(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_run_garbage_collection(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_run_garbage_collection(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_sync_group(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_sync_group(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_set_device_name(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_set_device_name(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_presence_v3(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_presence_v3(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_presence_v1(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_presence_v1(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_add_websocket_client(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_add_websocket_client(o,addHeapObject(t),addHeapObject(e),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_clear_presence_v3_callback(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_clear_presence_v3_callback(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_clear_presence_callback(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_clear_presence_callback(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_free(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_free(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_make(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_make(o,addHeapObject(t),addHeapObject(e),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function uninitialized_ditto_make(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.uninitialized_ditto_make(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_register_transport_condition_changed_callback(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_register_transport_condition_changed_callback(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_validate_document_id(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_validate_document_id(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_document_id_query_compatible(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_document_id_query_compatible(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function websocket_client_free_handle(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.websocket_client_free_handle(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_cancel_resolve_attachment(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_cancel_resolve_attachment(o,addHeapObject(t),addHeapObject(e),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_free_attachment_handle(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_free_attachment_handle(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_get_complete_attachment_data(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_get_complete_attachment_data(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_new_attachment_from_bytes(t,e,n){try{const o=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_new_attachment_from_bytes(o,addHeapObject(t),addHeapObject(e),addHeapObject(n));var r=getInt32Memory0()[o/4+0],i=getInt32Memory0()[o/4+1];if(getInt32Memory0()[o/4+2])throw takeObject(i);return takeObject(r)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_resolve_attachment(t,e,n,r,i){try{const s=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_resolve_attachment(s,addHeapObject(t),addHeapObject(e),addHeapObject(n),addHeapObject(r),addHeapObject(i));var o=getInt32Memory0()[s/4+0],a=getInt32Memory0()[s/4+1];if(getInt32Memory0()[s/4+2])throw takeObject(a);return takeObject(o)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_write_transaction_commit(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction_commit(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_write_transaction(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_write_transaction(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_read_transaction_free(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_read_transaction_free(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function ditto_read_transaction(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.ditto_read_transaction(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function handleError(t,e){try{return t.apply(this,e)}catch(t){wasm.__wbindgen_exn_store(addHeapObject(t))}}function notDefined(t){return()=>{throw new Error(`${t} is not defined`)}}function getArrayU8FromWasm0(t,e){return getUint8Memory0().subarray(t/1,t/1+e)}function __wbg_adapter_326(t,e,n,r){wasm.wasm_bindgen__convert__closures__invoke2_mut__hea28da18ec0de61e(t,e,addHeapObject(n),addHeapObject(r))}function boxCStringIntoString(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.boxCStringIntoString(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function refCStringToString(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.refCStringToString(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function boxCBytesIntoBuffer(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.boxCBytesIntoBuffer(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function withOutPtr$1(t,e){try{const i=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.withOutPtr(i,addHeapObject(t),addHeapObject(e));var n=getInt32Memory0()[i/4+0],r=getInt32Memory0()[i/4+1];if(getInt32Memory0()[i/4+2])throw takeObject(r);return takeObject(n)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function withOutBoxCBytes(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.withOutBoxCBytes(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}function cStringVecToStringArray(t){try{const r=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.cStringVecToStringArray(r,addHeapObject(t));var e=getInt32Memory0()[r/4+0],n=getInt32Memory0()[r/4+1];if(getInt32Memory0()[r/4+2])throw takeObject(n);return takeObject(e)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}async function load(t,e){if("function"==typeof Response&&t instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(t,e)}catch(e){if("application/wasm"==t.headers.get("Content-Type"))throw e;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",e)}const n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}{const n=await WebAssembly.instantiate(t,e);return n instanceof WebAssembly.Instance?{instance:n,module:t}:n}}function getImports(){const t={wbg:{}};return t.wbg.__wbindgen_object_drop_ref=function(t){takeObject(t)},t.wbg.__wbindgen_string_new=function(t,e){return addHeapObject(getStringFromWasm0(t,e))},t.wbg.__wbg_log_c6f7064ce12c2dfa=function(t,e){try{console.log(getStringFromWasm0(t,e))}finally{wasm.__wbindgen_free(t,e)}},t.wbg.__wbindgen_cb_drop=function(t){const e=takeObject(t).original;if(1==e.cnt--)return e.a=0,!0;return!1},t.wbg.__wbg_new_abda76e883ba8a5f=function(){return addHeapObject(new Error)},t.wbg.__wbg_stack_658279fe44541cf6=function(t,e){const n=passStringToWasm0(getObject(e).stack,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_error_f851667af71bcfc6=function(t,e){try{console.error(getStringFromWasm0(t,e))}finally{wasm.__wbindgen_free(t,e)}},t.wbg.__wbindgen_is_string=function(t){return"string"==typeof getObject(t)},t.wbg.__wbindgen_string_get=function(t,e){const n=getObject(e),r="string"==typeof n?n:void 0;var i=isLikeNone(r)?0:passStringToWasm0(r,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),o=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=o,getInt32Memory0()[t/4+0]=i},t.wbg.__wbindgen_object_clone_ref=function(t){return addHeapObject(getObject(t))},t.wbg.__wbg_fetch_3894579f6e2af3be=function(t){return addHeapObject(fetch(getObject(t)))},t.wbg.__wbg_clearTimeout_23ee6db72c0ad922="function"==typeof clearTimeout?clearTimeout:notDefined("clearTimeout"),t.wbg.__wbg_setTimeout_09074a1669d0f224=function(){return handleError((function(t,e){return setTimeout(getObject(t),e)}),arguments)},t.wbg.__wbg_clearInterval_d5655e407a861314="function"==typeof clearInterval?clearInterval:notDefined("clearInterval"),t.wbg.__wbg_setInterval_fa82463ae3f43f48=function(){return handleError((function(t,e){return setInterval(getObject(t),e)}),arguments)},t.wbg.__wbg_randomFillSync_6894564c2c334c42=function(){return handleError((function(t,e,n){getObject(t).randomFillSync(getArrayU8FromWasm0(e,n))}),arguments)},t.wbg.__wbg_getRandomValues_805f1c3d65988a5a=function(){return handleError((function(t,e){getObject(t).getRandomValues(getObject(e))}),arguments)},t.wbg.__wbg_crypto_e1d53a1d73fb10b8=function(t){return addHeapObject(getObject(t).crypto)},t.wbg.__wbindgen_is_object=function(t){const e=getObject(t);return"object"==typeof e&&null!==e},t.wbg.__wbg_process_038c26bf42b093f8=function(t){return addHeapObject(getObject(t).process)},t.wbg.__wbg_versions_ab37218d2f0b24a8=function(t){return addHeapObject(getObject(t).versions)},t.wbg.__wbg_node_080f4b19d15bc1fe=function(t){return addHeapObject(getObject(t).node)},t.wbg.__wbg_msCrypto_6e7d3e1f92610cbb=function(t){return addHeapObject(getObject(t).msCrypto)},t.wbg.__wbg_require_78a3dcfbdba9cbce=function(){return handleError((function(){return addHeapObject(module.require)}),arguments)},t.wbg.__wbindgen_is_function=function(t){return"function"==typeof getObject(t)},t.wbg.__wbindgen_number_new=function(t){return addHeapObject(t)},t.wbg.__wbg_mksendret_0b638c0dafde2c36=function(){return addHeapObject(mk_send_ret())},t.wbg.__wbg_trydownsize_28e49b8073c2a2fc=function(t){return addHeapObject(try_downsize(takeObject(t)))},t.wbg.__wbg_isnumber_c97122a46d4ace09=function(t){return is_number(getObject(t))},t.wbg.__wbg_tostring_7847f1b7af649ba5=function(t,e){const n=passStringToWasm0(to_string(getObject(e)),wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_fromstring_721719aff319c1fe=function(t,e){return addHeapObject(from_string(getStringFromWasm0(t,e)))},t.wbg.__wbg_getelement_cd48f1e89008c242=function(t,e){return addHeapObject(get_element(getObject(t),e>>>0))},t.wbg.__wbg_typeof_cb5c1bc26a697ea8=function(t,e){const n=passStringToWasm0(typeof_(getObject(e)),wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},t.wbg.__wbindgen_is_null=function(t){return null===getObject(t)},t.wbg.__wbindgen_is_undefined=function(t){return void 0===getObject(t)},t.wbg.__wbg_new_2d0053ee81e4dd2a=function(){return handleError((function(){return addHeapObject(new Headers)}),arguments)},t.wbg.__wbg_append_de37df908812970d=function(){return handleError((function(t,e,n,r,i){getObject(t).append(getStringFromWasm0(e,n),getStringFromWasm0(r,i))}),arguments)},t.wbg.__wbg_code_b09504754e0520f1=function(t){return getObject(t).code},t.wbg.__wbg_now_8172cd917e5eda6b=function(t){return getObject(t).now()},t.wbg.__wbg_wasClean_2af04e6cf2076497=function(t){return getObject(t).wasClean},t.wbg.__wbg_code_24e161f043adce8a=function(t){return getObject(t).code},t.wbg.__wbg_reason_40159cc3d2fc655d=function(t,e){const n=passStringToWasm0(getObject(e).reason,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_newwithstrandinit_05d7180788420c40=function(){return handleError((function(t,e,n){return addHeapObject(new Request(getStringFromWasm0(t,e),getObject(n)))}),arguments)},t.wbg.__wbg_data_7b1f01f4e6a64fbe=function(t){return addHeapObject(getObject(t).data)},t.wbg.__wbg_fetch_749a56934f95c96c=function(t,e){return addHeapObject(getObject(t).fetch(getObject(e)))},t.wbg.__wbg_instanceof_Blob_d18d26355bccfd22=function(t){let e;try{e=getObject(t)instanceof Blob}catch{e=!1}return e},t.wbg.__wbg_readyState_9c0f66433e329c9e=function(t){return getObject(t).readyState},t.wbg.__wbg_setonopen_9ce48dce57e549b5=function(t,e){getObject(t).onopen=getObject(e)},t.wbg.__wbg_setonerror_02393260b3e29972=function(t,e){getObject(t).onerror=getObject(e)},t.wbg.__wbg_setonclose_4ce49fd8fd7783fb=function(t,e){getObject(t).onclose=getObject(e)},t.wbg.__wbg_setonmessage_c5a806b62a0c5607=function(t,e){getObject(t).onmessage=getObject(e)},t.wbg.__wbg_setbinaryType_ee55743ddf4beb37=function(t,e){getObject(t).binaryType=takeObject(e)},t.wbg.__wbg_new_d29e507f6606de91=function(){return handleError((function(t,e){return addHeapObject(new WebSocket(getStringFromWasm0(t,e)))}),arguments)},t.wbg.__wbg_newwithstrsequence_7b0c4aadc1ae1635=function(){return handleError((function(t,e,n){return addHeapObject(new WebSocket(getStringFromWasm0(t,e),getObject(n)))}),arguments)},t.wbg.__wbg_close_45d053bea59e7746=function(){return handleError((function(t){getObject(t).close()}),arguments)},t.wbg.__wbg_send_80b256d87a6779e5=function(){return handleError((function(t,e,n){getObject(t).send(getStringFromWasm0(e,n))}),arguments)},t.wbg.__wbg_send_640853f8eb0f0385=function(){return handleError((function(t,e,n){getObject(t).send(getArrayU8FromWasm0(e,n))}),arguments)},t.wbg.__wbg_instanceof_Response_eaa426220848a39e=function(t){let e;try{e=getObject(t)instanceof Response}catch{e=!1}return e},t.wbg.__wbg_url_74285ddf2747cb3d=function(t,e){const n=passStringToWasm0(getObject(e).url,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},t.wbg.__wbg_status_c4ef3dd591e63435=function(t){return getObject(t).status},t.wbg.__wbg_headers_fd64ad685cf22e5d=function(t){return addHeapObject(getObject(t).headers)},t.wbg.__wbg_arrayBuffer_4c27b6f00c530232=function(){return handleError((function(t){return addHeapObject(getObject(t).arrayBuffer())}),arguments)},t.wbg.__wbg_new_1d9a920c6bfc44a8=function(){return addHeapObject(new Array)},t.wbg.__wbg_valueOf_8404142eb850b917=function(t){return getObject(t).valueOf()},t.wbg.__wbg_newnoargs_b5b063fc6c2f0376=function(t,e){return addHeapObject(new Function(getStringFromWasm0(t,e)))},t.wbg.__wbg_next_579e583d33566a86=function(t){return addHeapObject(getObject(t).next)},t.wbg.__wbg_next_aaef7c8aa5e212ac=function(){return handleError((function(t){return addHeapObject(getObject(t).next())}),arguments)},t.wbg.__wbg_done_1b73b0672e15f234=function(t){return getObject(t).done},t.wbg.__wbg_value_1ccc36bc03462d71=function(t){return addHeapObject(getObject(t).value)},t.wbg.__wbg_iterator_6f9d4f28845f426c=function(){return addHeapObject(Symbol.iterator)},t.wbg.__wbg_get_765201544a2b6869=function(){return handleError((function(t,e){return addHeapObject(Reflect.get(getObject(t),getObject(e)))}),arguments)},t.wbg.__wbg_call_97ae9d8645dc388b=function(){return handleError((function(t,e){return addHeapObject(getObject(t).call(getObject(e)))}),arguments)},t.wbg.__wbg_new_0b9bfdd97583284e=function(){return addHeapObject(new Object)},t.wbg.__wbg_self_6d479506f72c6a71=function(){return handleError((function(){return addHeapObject(self.self)}),arguments)},t.wbg.__wbg_window_f2557cc78490aceb=function(){return handleError((function(){return addHeapObject(window.window)}),arguments)},t.wbg.__wbg_globalThis_7f206bda628d5286=function(){return handleError((function(){return addHeapObject(globalThis.globalThis)}),arguments)},t.wbg.__wbg_global_ba75c50d1cf384f4=function(){return handleError((function(){return addHeapObject(global.global)}),arguments)},t.wbg.__wbg_push_740e4b286702d964=function(t,e){return getObject(t).push(getObject(e))},t.wbg.__wbg_instanceof_ArrayBuffer_e5e48f4762c5610b=function(t){let e;try{e=getObject(t)instanceof ArrayBuffer}catch{e=!1}return e},t.wbg.__wbg_apply_22a3220d244124da=function(){return handleError((function(t,e,n){return addHeapObject(getObject(t).apply(getObject(e),getObject(n)))}),arguments)},t.wbg.__wbg_call_168da88779e35f61=function(){return handleError((function(t,e,n){return addHeapObject(getObject(t).call(getObject(e),getObject(n)))}),arguments)},t.wbg.__wbg_valueOf_6b6effad03e5c546=function(t){return getObject(t).valueOf()},t.wbg.__wbg_getTime_cb82adb2556ed13e=function(t){return getObject(t).getTime()},t.wbg.__wbg_new0_a57059d72c5b7aee=function(){return addHeapObject(new Date)},t.wbg.__wbg_now_58886682b7e790d7=function(){return Date.now()},t.wbg.__wbg_instanceof_Object_595a1007518cbea3=function(t){let e;try{e=getObject(t)instanceof Object}catch{e=!1}return e},t.wbg.__wbg_new_9962f939219f1820=function(t,e){try{var n={a:t,b:e};const r=new Promise(((t,e)=>{const r=n.a;n.a=0;try{return __wbg_adapter_326(r,n.b,t,e)}finally{n.a=r}}));return addHeapObject(r)}finally{n.a=n.b=0}},t.wbg.__wbg_resolve_99fe17964f31ffc0=function(t){return addHeapObject(Promise.resolve(getObject(t)))},t.wbg.__wbg_then_11f7a54d67b4bfad=function(t,e){return addHeapObject(getObject(t).then(getObject(e)))},t.wbg.__wbg_then_cedad20fbbd9418a=function(t,e,n){return addHeapObject(getObject(t).then(getObject(e),getObject(n)))},t.wbg.__wbg_buffer_3f3d764d4747d564=function(t){return addHeapObject(getObject(t).buffer)},t.wbg.__wbg_newwithbyteoffsetandlength_d9aa266703cb98be=function(t,e,n){return addHeapObject(new Uint8Array(getObject(t),e>>>0,n>>>0))},t.wbg.__wbg_new_8c3f0052272a457a=function(t){return addHeapObject(new Uint8Array(getObject(t)))},t.wbg.__wbg_set_83db9690f9353e79=function(t,e,n){getObject(t).set(getObject(e),n>>>0)},t.wbg.__wbg_length_9e1ae1900cb0fbd5=function(t){return getObject(t).length},t.wbg.__wbg_instanceof_Uint8Array_971eeda69eb75003=function(t){let e;try{e=getObject(t)instanceof Uint8Array}catch{e=!1}return e},t.wbg.__wbg_newwithlength_f5933855e4f48a19=function(t){return addHeapObject(new Uint8Array(t>>>0))},t.wbg.__wbg_subarray_58ad4efbb5bcb886=function(t,e,n){return addHeapObject(getObject(t).subarray(e>>>0,n>>>0))},t.wbg.__wbg_has_8359f114ce042f5a=function(){return handleError((function(t,e){return Reflect.has(getObject(t),getObject(e))}),arguments)},t.wbg.__wbg_set_bf3f89b92d5a34bf=function(){return handleError((function(t,e,n){return Reflect.set(getObject(t),getObject(e),getObject(n))}),arguments)},t.wbg.__wbg_parse_e23be3fecd886e2a=function(){return handleError((function(t,e){return addHeapObject(JSON.parse(getStringFromWasm0(t,e)))}),arguments)},t.wbg.__wbg_stringify_d6471d300ded9b68=function(){return handleError((function(t){return addHeapObject(JSON.stringify(getObject(t)))}),arguments)},t.wbg.__wbindgen_debug_string=function(t,e){const n=passStringToWasm0(debugString(getObject(e)),wasm.__wbindgen_malloc,wasm.__wbindgen_realloc),r=WASM_VECTOR_LEN;getInt32Memory0()[t/4+1]=r,getInt32Memory0()[t/4+0]=n},t.wbg.__wbindgen_throw=function(t,e){throw new Error(getStringFromWasm0(t,e))},t.wbg.__wbindgen_memory=function(){return addHeapObject(wasm.memory)},t.wbg.__wbindgen_closure_wrapper3115=function(t,e,n){return addHeapObject(makeMutClosure(t,e,806,__wbg_adapter_30))},t.wbg.__wbindgen_closure_wrapper3117=function(t,e,n){return addHeapObject(makeMutClosure(t,e,806,__wbg_adapter_33))},t.wbg.__wbindgen_closure_wrapper11909=function(t,e,n){return addHeapObject(makeMutClosure(t,e,3294,__wbg_adapter_36))},t.wbg.__wbindgen_closure_wrapper18048=function(t,e,n){return addHeapObject(makeMutClosure(t,e,4800,__wbg_adapter_39))},t.wbg.__wbindgen_closure_wrapper19387=function(t,e,n){return addHeapObject(makeMutClosure(t,e,5209,__wbg_adapter_42))},t}function finalizeInit(t,e){return wasm=t.exports,init$3.__wbindgen_wasm_module=e,cachedInt32Memory0=new Int32Array,cachedUint8Memory0=new Uint8Array,wasm}async function init$3(t){if(void 0===t)throw new Error("Can't load ditto.wasm, expected module to be provided at initialization time but got nothing.");const e=getImports();("string"==typeof t||"function"==typeof Request&&t instanceof Request||"function"==typeof URL&&t instanceof URL)&&(t=fetch(t));const{instance:n,module:r}=await load(await t,e);return finalizeInit(n,r)}const DittoCRDTTypeKey="_ditto_internal_type_jkb12973t4b",DittoCRDTValueKey="_value";var DittoCRDTType;function documentSetCBORWithTimestamp(t,e,n,r,i){ensureInitialized();const o=ditto_document_set_cbor_with_timestamp(t,bytesFromString(e),n,r,i);if(0!==o)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${o}`)}function documentSetCBOR(t,e,n,r){ensureInitialized();const i=ditto_document_set_cbor(t,bytesFromString(e),n,r);if(0!==i)throw new Error(errorMessage()||`ditto_document_set_cbor() failed with error code: ${i}`)}function documentID(t){ensureInitialized();return boxCBytesIntoBuffer(ditto_document_id(t))}function documentGetCBORWithPathType(t,e,n){ensureInitialized();const r=ditto_document_get_cbor_with_path_type(t,bytesFromString(e),n);return{statusCode:r.status_code,cbor:boxCBytesIntoBuffer(r.cbor)}}function documentRemove(t,e){ensureInitialized();const n=ditto_document_remove(t,bytesFromString(e));if(0!==n)throw new Error(errorMessage()||`ditto_document_remove() failed with error code: ${n}`)}function documentIncrementCounter(t,e,n){ensureInitialized();const r=ditto_document_increment_counter(t,bytesFromString(e),n);if(0!==r)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${r}`)}function documentFree(t){ensureInitialized(),ditto_document_free(t)}function documentIDQueryCompatible(t,e){ensureInitialized();return boxCStringIntoString(ditto_document_id_query_compatible(t,e))}function validateDocumentID(t){ensureInitialized();return boxCBytesIntoBuffer(withOutBoxCBytes((e=>{const n=ditto_validate_document_id(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_validate_document_id() failed with error code: ${n}`);return e})))}async function collectionGet(t,e,n,r){ensureInitialized();const i=bytesFromString(e),{status_code:o,document:a}=await ditto_collection_get(t,i,n,r);if(o===NOT_FOUND_ERROR_CODE)return null;if(0!==o)throw new Error(errorMessage()||`ditto_collection_get() failed with error code: ${o}`);return a}async function collectionInsertValue(t,e,n,r,i){ensureInitialized();const o=bytesFromString(e);let a;switch(i){case"merge":a="Merge";break;case"insertIfAbsent":a="InsertIfAbsent";break;case"insertDefaultIfAbsent":a="InsertDefaultIfAbsent";break;default:throw new Error("Invalid write strategy provided")}const{status_code:s,id:c}=await ditto_collection_insert_value(t,o,n,r,a,null,null);if(0!==s)throw new Error(errorMessage()||`ditto_collection_insert_value() failed with error code: ${s}`);return boxCBytesIntoBuffer(c)}async function collectionRemove(t,e,n,r){ensureInitialized();const i=bytesFromString(e),{status_code:o,bool_value:a}=await ditto_collection_remove(t,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${o}`);return a}async function collectionEvict(t,e,n,r){ensureInitialized();const i=bytesFromString(e),{status_code:o,bool_value:a}=await ditto_collection_evict(t,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${o}`);return a}async function collectionUpdate(t,e,n,r){ensureInitialized();const i=bytesFromString(e),o=await ditto_collection_update(t,i,n,r);if(0!==o)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${o}`)}async function collectionUpdateMultiple(t,e,n,r){ensureInitialized();const i=bytesFromString(e),o=jsDocsToCDocs(r),a=await ditto_collection_update_multiple(t,i,n,o);if(0!==a)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${a}`)}async function collectionExecQueryStr(t,e,n,r,i,o,a,s){ensureInitialized();const c=bytesFromString(e),d=bytesFromString(r);return await ditto_collection_exec_query_str(t,c,n,d,i,o,a,s)}async function collectionRemoveQueryStr(t,e,n,r,i,o,a,s){ensureInitialized();const c=bytesFromString(e),d=bytesFromString(r);return await ditto_collection_remove_query_str(t,c,n,d,i,o,a,s)}async function collectionEvictQueryStr(t,e,n,r,i,o,a,s){ensureInitialized();const c=bytesFromString(e),d=bytesFromString(r);return await ditto_collection_evict_query_str(t,c,n,d,i,o,a,s)}function addSubscription(t,e,n,r,i,o,a){ensureInitialized();return ditto_add_subscription(t,bytesFromString(e),bytesFromString(n),r,i,o,a)}function removeSubscription(t,e,n,r,i,o,a){ensureInitialized();return ditto_remove_subscription(t,bytesFromString(e),bytesFromString(n),r,i,o,a)}function liveQueryRegister(t,e,n,r,i,o,a,s,c){ensureInitialized();const d=bytesFromString(e),l=bytesFromString(n),{status_code:_,i64:u}=ditto_live_query_register_str_detached(t,d,l,r,i,o,a,wrapBackgroundCbForFFI(c,s));if(0!==_)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${_}`);return u}async function liveQueryStart(t,e){ensureInitialized();const n=await ditto_live_query_start(t,e);if(0!==n)throw new Error(errorMessage()||`\`ditto_live_query_start()\` failed with error code: ${n}`)}function liveQueryStop(t,e){ensureInitialized(),ditto_live_query_stop(t,e)}async function liveQuerySignalAvailableNext(t,e){ensureInitialized(),await ditto_live_query_signal_available_next(t,e)}async function liveQueryWebhookRegister(t,e,n,r,i,o,a){ensureInitialized();const s=bytesFromString(e),c=bytesFromString(n),d=bytesFromString(a),{status_code:l,id:_}=await ditto_live_query_webhook_register_str(t,s,c,r,i,o,d);if(0!==l)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${l}`);return boxCBytesIntoBuffer(_)}async function readTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await ditto_read_transaction(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_read_transaction()\` failed with error code: ${e}`);return n}function readTransactionFree(t){return ensureInitialized(),ditto_read_transaction_free(t)}async function writeTransaction(t){ensureInitialized();const{status_code:e,txn:n}=await ditto_write_transaction(t,null);if(0!==e)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${e}`);return n}async function writeTransactionCommit(t,e){ensureInitialized();const n=await ditto_write_transaction_commit(t,e);if(0!==n)throw new Error(errorMessage()||`ditto_write_transaction_commit() failed with error code: ${n}`)}function addStaticTCPClient(t,e){ensureInitialized();return(void 0)(t,bytesFromString(e))}function staticTCPClientFreeHandle(t){(void 0)(t)}function addWebsocketClient(t,e,n){ensureInitialized();return ditto_add_websocket_client(t,bytesFromString(e),n)}function websocketClientFreeHandle(t){ensureInitialized(),websocket_client_free_handle(t)}function loggerInit(){ensureInitialized(),ditto_logger_init()}async function loggerSetCustomLogCb(t){if(ensureInitialized(),null===t)await ditto_logger_set_custom_log_cb(null);else{const e=wrapBackgroundCbForFFI(null,((e,n)=>{try{const r=boxCStringIntoString(n);t(e,r)}catch(t){console.error(`The registered cb in \`ditto_logger_set_custom_log_cb()\` failed with: ${t}`)}}));await ditto_logger_set_custom_log_cb(e)}}function loggerEnabled(t){ensureInitialized(),ditto_logger_enabled(!!t)}function loggerEnabledGet(){return ensureInitialized(),!!ditto_logger_enabled_get()}function loggerEmojiHeadingsEnabled(t){ensureInitialized(),ditto_logger_emoji_headings_enabled(t)}function loggerEmojiHeadingsEnabledGet(){return ensureInitialized(),ditto_logger_emoji_headings_enabled_get()}function loggerMinimumLogLevel(t){ensureInitialized(),ditto_logger_minimum_log_level(t)}function loggerMinimumLogLevelGet(){return ensureInitialized(),ditto_logger_minimum_log_level_get()}function loggerSetLogFile(t){ensureInitialized();if(0!==ditto_logger_set_log_file(t?bytesFromString(t):null))throw errorMessage(),new Error(`Can't set log file, due to error: ${errorMessage}`)}function log(t,e){ensureInitialized(),bytesFromString(t);ditto_log(t,bytesFromString(e))}function dittoAuthClientMakeAnonymousClient(t,e,n,r){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(e),a=bytesFromString(n),s=bytesFromString(r),{status_code:c,auth_client:d}=ditto_auth_client_make_anonymous_client(i,o,a,s);if(0!==c)throw new Error(errorMessage()||`ditto_auth_client_make_anonymous_client() failed with error code: ${c}`);return d}function dittoAuthClientMakeWithWeb(t,e,n,r){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(e),a=bytesFromString(n),{status_code:s,auth_client:c}=ditto_auth_client_make_with_web(i,o,a,r);if(0!==s)throw new Error(errorMessage()||`ditto_auth_client_make_with_web() failed with error code: ${s}`);return c}function dittoAuthClientMakeForDevelopment(t,e,n){ensureInitialized();const r=bytesFromString(t),i=bytesFromString(e),o=Number(n),{status_code:a,auth_client:s}=ditto_auth_client_make_for_development(r,i,o);if(0!==a)throw new Error(errorMessage()||`ditto_auth_client_make_for_development() failed with error code: ${a}`);return s}function dittoAuthClientMakeWithSharedKey(t,e,n,r){ensureInitialized();const i=bytesFromString(t),o=bytesFromString(e),a=bytesFromString(n),s=Number(r),{status_code:c,auth_client:d}=ditto_auth_client_make_with_shared_key(i,o,a,s);if(0!==c)throw new Error(errorMessage()||`ditto_auth_client_make_with_shared_key() failed with error code: ${c}`);return d}function dittoAuthClientMakeWithStaticX509(t){ensureInitialized();const e=bytesFromString(t),{status_code:n,auth_client:r}=ditto_auth_client_make_with_static_x509(e);if(0!==n)throw new Error(errorMessage()||`ditto_auth_client_make_with_static_x509() failed with error code: ${n}`);return r}function dittoAuthClientGetSiteID(t){return ensureInitialized(),ditto_auth_client_get_site_id(t)}function dittoAuthClientFree(t){return ensureInitialized(),ditto_auth_client_free(t)}function dittoAuthClientIsWebValid(t){return ensureInitialized(),0!==ditto_auth_client_is_web_valid(t)}function dittoAuthClientUserID(t){ensureInitialized();return boxCStringIntoString(ditto_auth_client_user_id(t))}function dittoAuthClientIsX509Valid(t){return ensureInitialized(),0!==ditto_auth_client_is_x509_valid(t)}async function dittoAuthClientLoginWithToken(t,e,n){ensureInitialized();const r=bytesFromString(e),i=bytesFromString(n),o=await ditto_auth_client_login_with_token(t,r,i);if(0!==o)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${o}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(t,e,n,r){ensureInitialized();const i=bytesFromString(e),o=bytesFromString(n),a=bytesFromString(r),s=await ditto_auth_client_login_with_credentials(t,i,o,a);if(0!==s)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${s}).`)}async function dittoAuthClientLogout(t){ensureInitialized();const e=await ditto_auth_client_logout(t);if(0!==e)throw new Error(errorMessage()||`Ditto failed to logout (error code: ${e}).`)}function uninitializedDittoMake(t){ensureInitialized();return uninitialized_ditto_make(bytesFromString(t))}function dittoMake(t,e){return ensureInitialized(),ditto_make(t,e,"Disabled")}async function dittoGetCollectionNames(t){ensureInitialized();const e=await ditto_get_collection_names(t),n=e.status_code,r=e.names;if(0!==n)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${n}`);return cStringVecToStringArray(r)}function dittoFree(t){return ensureInitialized(),ditto_free(t)}async function dittoRegisterPresenceV1Callback(t,e){ensureInitialized(),e?ditto_register_presence_v1_callback(t,wrapBackgroundCbForFFI((t=>console.error(`The registered presence callback errored with ${t}`)),(t=>{const n=refCStringToString(t);e(n)}))):await ditto_clear_presence_callback(t)}async function dittoRegisterPresenceV3Callback(t,e){ensureInitialized(),ditto_register_presence_v3_callback(t,wrapBackgroundCbForFFI((t=>console.error(`The registered presence callback v3 errored with ${t}`)),(t=>{const n=refCStringToString(t);e(n)})))}async function dittoClearPresenceV3Callback(t){ensureInitialized(),ditto_clear_presence_v3_callback(t)}async function dittoClearPresenceCallback(t){ensureInitialized(),await ditto_clear_presence_callback(t)}function dittoRegisterTransportConditionChangedCallback(t,e){ensureInitialized(),ditto_register_transport_condition_changed_callback(t,e?wrapBackgroundCbForFFI((t=>console.error(`The registered "transport condition changed" callback errored with ${t}`)),e):null)}function dittoSetDeviceName(t,e){ensureInitialized();let n=bytesFromString(e);if(n.length>64){n=bytesFromString(e.replace(/[^ -~]+/g,"").substr(0,63))}return ditto_set_device_name(t,n)}function dittoSetSyncGroup(t,e){return ensureInitialized(),ditto_set_sync_group(t,e)}async function dittoNewAttachmentFromBytes(t,e){ensureInitialized();const n={},r=await ditto_new_attachment_from_bytes(t,e,n);if(0!==r)throw new Error(errorMessage()||`ditto_new_attachment_from_bytes() failed with error code: ${r}`);return n}async function dittoResolveAttachment(t,e,n,r){ensureInitialized();const{onComplete:i,onProgress:o,onDelete:a}=n,{status_code:s,cancel_token:c}=await ditto_resolve_attachment(t,e,wrapBackgroundCbForFFI(r,i),wrapBackgroundCbForFFI(r,o),wrapBackgroundCbForFFI(r,a));if(0!==s)throw new Error(errorMessage()||`ditto_resolve_attachment() failed with error code: ${s}`);return c}function dittoCancelResolveAttachment(t,e,n){ensureInitialized();const r=ditto_cancel_resolve_attachment(t,e,n);if(0!==r)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${r}`)}function freeAttachmentHandle(t){ensureInitialized(),ditto_free_attachment_handle(t)}async function dittoGetCompleteAttachmentData(t,e){ensureInitialized();const{status:n,data:r}=await ditto_get_complete_attachment_data(t,e);if(0!==n)throw new Error(errorMessage()||`\`ditto_get_complete_attachment_data()\` failed with error code: ${n}`);return boxCBytesIntoBuffer(r)}function dittoGetSDKVersion(t){ensureInitialized();return boxCStringIntoString(ditto_get_sdk_version())}function dittoPresenceV1(t){ensureInitialized();return boxCStringIntoString(ditto_presence_v1(t))}function dittoPresenceV3(t){ensureInitialized();return boxCStringIntoString(ditto_presence_v3(t))}function dittoStartTCPServer(t,e){ensureInitialized();return(void 0)(t,bytesFromString(e))}function dittoStopTCPServer(t){return ensureInitialized(),(void 0)(t)}function dittoAddMulticastTransport(t){return ensureInitialized(),(void 0)(t)}function dittoRemoveMulticastTransport(t){return ensureInitialized(),(void 0)(t)}function dittoStartHTTPServer(t,e,n,r,i,o){ensureInitialized();return(void 0)(t,bytesFromString(e),bytesFromString(n),r,bytesFromString(i),bytesFromString(o))}function dittoStopHTTPServer(t){return ensureInitialized(),(void 0)(t)}function dittoRunGarbageCollection(t){return ensureInitialized(),ditto_run_garbage_collection(t)}async function dittoDisableSyncWithV2(t){ensureInitialized();const e=await ditto_disable_sync_with_v2(t);if(0!==e)throw new Error(errorMessage()||`ditto_disable_sync_with_v2() failed with error code: ${e}`)}function documentsHash(t){ensureInitialized();const{status_code:e,u64:n}=ditto_documents_hash(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash()\` failed with error code: ${e}`);return BigInt(n)}function documentsHashMnemonic(t){ensureInitialized();const{status_code:e,c_string:n}=ditto_documents_hash_mnemonic(t);if(0!==e)throw new Error(errorMessage()||`\`ditto_documents_hash_mnemonic()\` failed with error code: ${e}`);return boxCStringIntoString(n)}function dittoAuthClientMakeLoginProvider(t,e){return ensureInitialized(),ditto_auth_client_make_login_provider(wrapBackgroundCbForFFI(e,t))}function dittoAuthClientSetValidityListener(t,e,n){ensureInitialized();return ditto_auth_client_set_validity_listener(t,wrapBackgroundCbForFFI(n,(function(t,n){return e(1===t,1===n)})))}!function(t){t[t.counter=0]="counter",t[t.register=1]="register",t[t.attachment=2]="attachment",t[t.rga=3]="rga",t[t.rwMap=4]="rwMap"}(DittoCRDTType||(DittoCRDTType={}));let withOutPtr,isInitialized$1=!1;async function init$2(t){t?await init$3(t):await init$3(),isInitialized$1=!0,withOutPtr=wrapFFIOutFunction(withOutPtr$1)}function initSDKVersion(t,e,n){ensureInitialized(),bytesFromString(t),bytesFromString(e);const r=ditto_init_sdk_version(t,e,bytesFromString(n));if(void 0!==r&&0!==r)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${r}`)}function verifyLicense(t){ensureInitialized();const e=bytesFromString(t);let n;const r=boxCStringIntoString(withOutPtr("char *",(t=>(n=verify_license(e,t),t))));return{result:n,errorMessage:r}}const NOT_FOUND_ERROR_CODE=-30798;function wrapBackgroundCbForFFI(t,e){return void 0===t&&(t=console.error),(n,...r)=>{let i;try{i=e(...r)}catch(e){try{t(e)}catch(t){console.error(`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${t}`)}}return n(i)}}function wrapFFIOutFunction(t){return function(...e){let n,r,i=!1;const o=e[e.length-1],a=e.splice(0,e.length-1),s=t(...a,(t=>{try{r=o(t),i=r===t}catch(t){n=t}}));if(n)throw n;return i?s:r}}function bytesFromString(t){if(void 0===t)return;if(null===t)return null;if("string"!=typeof t)throw new Error(`Can't convert string to Uint8Array, not a string: ${t}`);return(new TextEncoder).encode(`${t}\0`)}function errorMessage(){ensureInitialized();return boxCStringIntoString(ditto_error_message())}function ensureInitialized(){if(!isInitialized$1)throw new Error("Ditto needs to be initialized before using any of its API, please make sure to call `await init()` first.")}async function init$1(){}function bleIsAvailable(t){return!1}function bleCreate(t){throw new Error("Can't create BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}function bleDestroy(t){throw new Error("Can't destroy BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}function lanIsAvailable(t){return!1}function lanCreate(t){throw new Error("Can't create LAN handle, P2P LAN transport is not supported on this platform.")}function lanDestroy(t){throw new Error("Can't destroy LAN handle, P2P LAN transport is not supported on this platform.")}function awdlIsAvailable(t){return!1}function awdlCreate(t){throw new Error("Can't create AWDL handle, P2P AWDL transport is not supported on this platform.")}function awdlDestroy(t){throw new Error("Can't destroy AWDL handle, P2P AWDL transport is not supported on this platform.")}const fullBuildVersionString="3.0.6-experimental.node-loading-issues.3.linux-x64",defaultDittoWasmFileURL="https://software.ditto.live/js/Ditto/3.0.6-experimental.node-loading-issues.3.linux-x64/ditto.wasm";let isInitialized=!1;async function init(t={}){if(!isInitialized){{const e=t.webAssemblyModule||defaultDittoWasmFileURL;await init$2(e),await init$1(),initSDKVersion("Web","JavaScript",fullBuildVersionString),loggerInit()}isInitialized=!0}}class KeepAlive{get isActive(){return null!==this.intervalID}constructor(){this.countsByID={},this.intervalID=null}retain(t){if(void 0===this.countsByID[t]&&(this.countsByID[t]=0),this.countsByID[t]+=1,null===this.intervalID){const t=2147483647;this.intervalID=setInterval((()=>{}),t),KeepAlive.finalizationRegistry.register(this,this.intervalID,this)}}release(t){if(void 0===this.countsByID[t])throw new Error(`Internal inconsistency, trying to release a keep-alive ID that hasn't been retained before or isn't tracked anymore: ${t}`);this.countsByID[t]-=1,0===this.countsByID[t]&&delete this.countsByID[t],0===Object.keys(this.countsByID).length&&(KeepAlive.finalizationRegistry.unregister(this),clearInterval(this.intervalID),this.intervalID=null)}currentIDs(){return Object.keys(this.countsByID)}countForID(t){var e;return null!==(e=this.countsByID[t])&&void 0!==e?e:null}}KeepAlive.finalizationRegistry=new FinalizationRegistry(clearInterval);class Logger{static setLogFile(t){t?(loggerSetLogFile(t),this.logFile=t):(loggerSetLogFile(null),delete this.logFile)}static setLogFileURL(t){this.setLogFile(null==t?void 0:t.pathname)}static get enabled(){return loggerEnabledGet()}static set enabled(t){loggerEnabled(t)}static get emojiLogLevelHeadingsEnabled(){return loggerEmojiHeadingsEnabledGet()}static set emojiLogLevelHeadingsEnabled(t){loggerEmojiHeadingsEnabled(t)}static get minimumLogLevel(){return loggerMinimumLogLevelGet()}static set minimumLogLevel(t){loggerMinimumLogLevel(t)}static async setCustomLogCallback(t){t?(await loggerSetCustomLogCb(t),this.customLogCallback=t):(await loggerSetCustomLogCb(null),delete this.customLogCallback)}static log(t,e){log(t,e)}static error(t){this.log("Error",t)}static warning(t){this.log("Warning",t)}static info(t){this.log("Info",t)}static debug(t){this.log("Debug",t)}static verbose(t){this.log("Verbose",t)}constructor(){throw new Error("Logger can't be instantiated, use it's static properties & methods directly instead.")}}class ObserverManager{constructor(t,e={}){var n,r,i,o;const a=null!==(n=e.keepAlive)&&void 0!==n?n:null,s=null!==(r=e.register)&&void 0!==r?r:null,c=null!==(i=e.unregister)&&void 0!==i?i:null,d=null!==(o=e.process)&&void 0!==o?o:null;this.id=t,this.keepAlive=a,this.isRegistered=!1,this.callbacksByToken={},null!==s&&(this.register=s),null!==c&&(this.unregister=c),null!==d&&(this.process=d)}addObserver(t){var e;this.registerIfNeeded();const n=generateEphemeralToken();return this.callbacksByToken[n]=t,null===(e=this.keepAlive)||void 0===e||e.retain(`${this.id}.${n}`),n}removeObserver(t){var e;delete this.callbacksByToken[t],null===(e=this.keepAlive)||void 0===e||e.release(`${this.id}.${t}`),this.unregisterIfNeeded()}notify(...t){const e=this.process(...t);for(const t in this.callbacksByToken){(0,this.callbacksByToken[t])(...e)}}register(t){}unregister(){}process(...t){return t}hasObservers(){return Object.keys(this.callbacksByToken).length>0}registerIfNeeded(){if(!this.isRegistered){const t=new WeakRef(this);this.isRegistered=!0,this.register((function(...e){const n=t.deref();n&&n.notify(...e)}))}}unregisterIfNeeded(){!this.hasObservers()&&this.isRegistered&&(this.isRegistered=!1,this.unregister())}async finalize(t){await this.removeObserver(t)}}class Observer{constructor(t,e,n={}){this.observerManager=t,this.token=e,this.options=n,n.stopsWhenFinalized&&Observer.finalizationRegistry.register(this,{observerManager:t,token:e},this)}get isStopped(){return void 0===this.token}stop(){const t=this.token;t&&(delete this.token,Observer.finalizationRegistry.unregister(this),this.observerManager.removeObserver(t))}static finalize(t){const{observerManager:e,token:n}=t;e.removeObserver(n)}}Observer.finalizationRegistry=new FinalizationRegistry(Observer.finalize);class Authenticator{loginWithToken(t,e){throw new Error("Authenticator.loginWithToken() is abstract and must be implemented by subclasses.")}loginWithUsernameAndPassword(t,e,n){throw new Error("Authenticator.loginWithUsernameAndPassword() is abstract and must be implemented by subclasses.")}logout(t){throw new Error("Authenticator.logout() is abstract and must be implemented by subclasses.")}observeStatus(t){const e=this.observerManager.addObserver(t);return new Observer(this.observerManager,e,{stopsWhenFinalized:!0})}constructor(t){this.keepAlive=t,this.status={isAuthenticated:!1,userID:null},this.loginSupported=!1,this.observerManager=new ObserverManager("AuthenticationStatusObservation",{keepAlive:t})}"@ditto.authenticationExpiring"(t){throw new Error("Authenticator['@ditto.authenticationExpiring']() is abstract and must be implemented by subclasses.")}"@ditto.authClientValidityChanged"(t,e){throw new Error("Authenticator['@ditto.authClientValidityChanged']() is abstract and must be implemented by subclasses.")}}class OnlineAuthenticator extends Authenticator{async loginWithToken(t,e){await dittoAuthClientLoginWithToken(this.authClientPointer,t,e)}async loginWithUsernameAndPassword(t,e,n){await dittoAuthClientLoginWithUsernameAndPassword(this.authClientPointer,t,e,n)}async logout(t){const e=this.ditto.deref();e?(await dittoAuthClientLogout(this.authClientPointer),e.stopSync(),null==t||t(this.ditto)):Logger.warning("Unable to logout, related Ditto object does not exist anymore.")}constructor(t,e,n,r){super(t),this.loginSupported=!0,this.status={isAuthenticated:!1,userID:null},this.authClientPointer=e,this.ditto=new WeakRef(n),this.authenticationHandler=r,this.updateAndNotify(!1),OnlineAuthenticator.finalizationRegistry.register(this,e)}"@ditto.authenticationExpiring"(t){const e=this.authenticationHandler;t>0?e.authenticationExpiringSoon(this,t):e.authenticationRequired(this)}"@ditto.authClientValidityChanged"(t,e){this.updateAndNotify(!0)}updateAndNotify(t){var e;const n=this.status.isAuthenticated,r=this.status.userID,i=dittoAuthClientIsWebValid(this.authClientPointer),o=dittoAuthClientUserID(this.authClientPointer),a={isAuthenticated:i,userID:o};if(this.status=a,t){!!n==!!i&&r===o||(null===(e=this.authenticationHandler.authenticationStatusDidChange)||void 0===e||e.call(this.authenticationHandler,this),this.observerManager.notify(a))}}static finalize(t){dittoAuthClientFree(t)}}OnlineAuthenticator.finalizationRegistry=new FinalizationRegistry(OnlineAuthenticator.finalize);class NotAvailableAuthenticator extends Authenticator{async loginWithToken(t,e){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}async loginWithUsernameAndPassword(t,e,n){throw new Error("Can't login, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}logout(t){throw new Error("Can't logout, authentication is not supported for the identity in use, please use an onlineWithAuthentication identity.")}"@ditto.authenticationExpiring"(t){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authenticationExpiring() was called on authenticator: ${this}`)}"@ditto.authClientValidityChanged"(t,e){throw new Error(`Internal inconsistency, authentication is not available, yet the @ditto.authClientValidityChanged() was called on authenticator: ${this}`)}}const IdentityTypesRequiringOfflineLicenseToken=["manual","sharedKey","offlinePlayground"],NO_PREFERRED_ROUTE_HINT=0;class TransportConfig{constructor(){this.peerToPeer={bluetoothLE:{isEnabled:!1},awdl:{isEnabled:!1},lan:{isEnabled:!1,isMdnsEnabled:!0,isMulticastEnabled:!0}},this.connect={tcpServers:[],websocketURLs:[]},this.listen={tcp:{isEnabled:!1,interfaceIP:"0.0.0.0",port:4040},http:{isEnabled:!1,interfaceIP:"0.0.0.0",port:80,websocketSync:!0}},this.global={syncGroup:0,routingHint:0}}setAllPeerToPeerEnabled(t){this.peerToPeer.bluetoothLE.isEnabled=t,this.peerToPeer.lan.isEnabled=t,this.peerToPeer.awdl.isEnabled=t}freeze(){return this.isFrozen||(this.isFrozen=!0,Object.freeze(this.peerToPeer.bluetoothLE),Object.freeze(this.peerToPeer.awdl),Object.freeze(this.peerToPeer.lan),Object.freeze(this.peerToPeer),Object.freeze(this.connect.tcpServers),Object.freeze(this.connect.websocketURLs),Object.freeze(this.connect),Object.freeze(this.listen.tcp),Object.freeze(this.listen.http),Object.freeze(this.listen),Object.freeze(this.global)),this}copy(){const t=new TransportConfig;return t.peerToPeer.bluetoothLE.isEnabled=this.peerToPeer.bluetoothLE.isEnabled,t.peerToPeer.awdl.isEnabled=this.peerToPeer.awdl.isEnabled,t.peerToPeer.lan.isEnabled=this.peerToPeer.lan.isEnabled,t.peerToPeer.lan.isMdnsEnabled=this.peerToPeer.lan.isMdnsEnabled,t.peerToPeer.lan.isMulticastEnabled=this.peerToPeer.lan.isMulticastEnabled,t.connect.tcpServers=this.connect.tcpServers.slice(),t.connect.websocketURLs=this.connect.websocketURLs.slice(),t.listen.tcp={...this.listen.tcp},t.listen.http={...this.listen.http},t.global.syncGroup=this.global.syncGroup,t.global.routingHint=this.global.routingHint,t}static areListenTCPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port}static areListenHTTPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port&&t.staticContentPath===e.staticContentPath&&t.websocketSync===e.websocketSync&&t.tlsKeyPath===e.tlsKeyPath&&t.tlsCertificatePath===e.tlsCertificatePath}}const POW_2_24=5.960464477539063e-8,POW_2_32=4294967296,POW_2_53=9007199254740992,DECODE_CHUNK_SIZE=8192;function objectIs(t,e){return"function"==typeof Object.is?Object.is(t,e):t===e?0!==t||1/t==1/e:t!=t&&e!=e}class TaggedValue{constructor(t,e){this.value=t,this.tag=e}}function decode(t,e,n){let r=new DataView(t),i=new Uint8Array(t),o=0,tagValueFunction=function(t,e){return new TaggedValue(t,e)},simpleValFunction=function(t){};function commitRead(t,e){return o+=t,e}function readArrayBuffer(e){return commitRead(e,new Uint8Array(t,o,e))}function readUint8(){return commitRead(1,i[o])}function readUint16(){return commitRead(2,r.getUint16(o))}function readUint32(){return commitRead(4,r.getUint32(o))}function readBreak(){return 255===i[o]&&(o+=1,!0)}function readLength(t){if(t<24)return t;if(24===t)return readUint8();if(25===t)return readUint16();if(26===t)return readUint32();if(27===t)return function readUint64(){return readUint32()*POW_2_32+readUint32()}();if(31===t)return-1;throw new Error("Invalid length encoding")}function readIndefiniteStringLength(t){let e=readUint8();if(255===e)return-1;let n=readLength(31&e);if(n<0||e>>5!==t)throw new Error("Invalid indefinite length element");return n}function appendUtf16Data(t,e){for(let n=0;n<e;++n){let n=readUint8();128&n&&(n<224?(n=(31&n)<<6|63&readUint8(),e-=1):n<240?(n=(15&n)<<12|(63&readUint8())<<6|63&readUint8(),e-=2):(n=(15&n)<<18|(63&readUint8())<<12|(63&readUint8())<<6|63&readUint8(),e-=3)),n<65536?t.push(n):(n-=65536,t.push(55296|n>>10),t.push(56320|1023&n))}}"function"==typeof e&&(tagValueFunction=e),"function"==typeof n&&(simpleValFunction=n);let a=function decodeItem(){let t,e,n=readUint8(),i=n>>5,a=31&n;if(7===i)switch(a){case 25:return function readFloat16(){let t=new ArrayBuffer(4),e=new DataView(t),n=readUint16(),r=32768&n,i=31744&n,o=1023&n;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==o)return(r?-1:1)*o*POW_2_24;return e.setUint32(0,r<<16|i<<13|o<<13),e.getFloat32(0)}();case 26:return function readFloat32(){return commitRead(4,r.getFloat32(o))}();case 27:return function readFloat64(){return commitRead(8,r.getFloat64(o))}()}if(e=readLength(a),e<0&&(i<2||6<i))throw new Error("Invalid length");switch(i){case 0:return e;case 1:return-1-e;case 2:if(e<0){let n=[],r=0;for(;(e=readIndefiniteStringLength(i))>=0;)r+=e,n.push(readArrayBuffer(e));let o=new Uint8Array(r),a=0;for(t=0;t<n.length;++t)o.set(n[t],a),a+=n[t].length;return o}return readArrayBuffer(e);case 3:let n=[];if(e<0)for(;(e=readIndefiniteStringLength(i))>=0;)appendUtf16Data(n,e);else appendUtf16Data(n,e);let r="";for(t=0;t<n.length;t+=8192)r+=String.fromCharCode.apply(null,n.slice(t,t+8192));return r;case 4:let o;if(e<0)for(o=[];!readBreak();)o.push(decodeItem());else for(o=new Array(e),t=0;t<e;++t)o[t]=decodeItem();return o;case 5:let a={};for(t=0;t<e||e<0&&!readBreak();++t){a[decodeItem()]=decodeItem()}return a;case 6:return tagValueFunction(decodeItem(),e);case 7:switch(e){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:return simpleValFunction(e)}}}();if(o!==t.byteLength)throw new Error("Remaining bytes");return a}function encode(t){let e,n=new ArrayBuffer(256),r=new DataView(n),i=new Uint8Array(n),o=0;function prepareWrite(t){let a=n.byteLength,s=o+t;for(;a<s;)a<<=1;if(a!==n.byteLength){let t=r;n=new ArrayBuffer(a),r=new DataView(n),i=new Uint8Array(n);let e=o+3>>2;for(let n=0;n<e;++n)r.setUint32(n<<2,t.getUint32(n<<2))}return e=t,r}function commitWrite(...t){o+=e}function writeUint8(t){commitWrite(prepareWrite(1).setUint8(o,t))}function writeUint8Array(t){prepareWrite(t.length),i.set(t,o),commitWrite()}function writeUint16(t){commitWrite(prepareWrite(2).setUint16(o,t))}function writeUint32(t){commitWrite(prepareWrite(4).setUint32(o,t))}function writeUint64(t){let e=t%POW_2_32,n=(t-e)/POW_2_32,r=prepareWrite(8);r.setUint32(o,n),r.setUint32(o+4,e),commitWrite()}function writeTypeAndLength(t,e){e<24?writeUint8(t<<5|e):e<256?(writeUint8(t<<5|24),writeUint8(e)):e<65536?(writeUint8(t<<5|25),writeUint16(e)):e<4294967296?(writeUint8(t<<5|26),writeUint32(e)):(writeUint8(t<<5|27),writeUint64(e))}if(function encodeItem(t){let e;if(!1===t)return writeUint8(244);if(!0===t)return writeUint8(245);if(null===t)return writeUint8(246);if(void 0===t)return writeUint8(247);if(objectIs(t,-0))return writeUint8Array([249,128,0]);switch(typeof t){case"number":if(Math.floor(t)===t){if(0<=t&&t<=POW_2_53)return writeTypeAndLength(0,t);if(-POW_2_53<=t&&t<0)return writeTypeAndLength(1,-(t+1))}return writeUint8(251),function writeFloat64(t){commitWrite(prepareWrite(8).setFloat64(o,t))}(t);case"string":let n=[];for(e=0;e<t.length;++e){let r=t.charCodeAt(e);r<128?n.push(r):r<2048?(n.push(192|r>>6),n.push(128|63&r)):r<55296||r>=57344?(n.push(224|r>>12),n.push(128|r>>6&63),n.push(128|63&r)):(r=(1023&r)<<10,r|=1023&t.charCodeAt(++e),r+=65536,n.push(240|r>>18),n.push(128|r>>12&63),n.push(128|r>>6&63),n.push(128|63&r))}return writeTypeAndLength(3,n.length),writeUint8Array(n);default:let r,i;if(Array.isArray(t))for(r=t.length,writeTypeAndLength(4,r),e=0;e<r;e+=1)encodeItem(t[e]);else if(t instanceof Uint8Array)writeTypeAndLength(2,t.length),writeUint8Array(t);else if(ArrayBuffer.isView(t))i=new Uint8Array(t.buffer),writeTypeAndLength(2,i.length),writeUint8Array(i);else if(t instanceof ArrayBuffer||"function"==typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer)i=new Uint8Array(t),writeTypeAndLength(2,i.length),writeUint8Array(i);else if(t instanceof TaggedValue)!function writeVarUint(t,e){t<=255?t<24?writeUint8(t|e):(writeUint8(24|e),writeUint8(t)):t<=65535?(writeUint8(25|e),writeUint16(t)):t<=4294967295?(writeUint8(26|e),writeUint32(t)):(writeUint8(27|e),writeUint64(t))}(t.tag,192),encodeItem(t.value);else{let n=Object.keys(t);for(r=n.length,writeTypeAndLength(5,r),e=0;e<r;e+=1){let r=n[e];encodeItem(r),encodeItem(t[r])}}}}(t),"slice"in n)return n.slice(0,o);let a=new ArrayBuffer(o),s=new DataView(a);for(let t=0;t<o;++t)s.setUint8(t,r.getUint8(t));return a}const CBOR$1={decode:decode,encode:encode};class CBOR{static encode(t){const e=CBOR$1.encode(t);return new Uint8Array(e)}static decode(t){const e=t.buffer;return CBOR$1.decode(e)}}class DocumentID{get value(){let t=this["@ditto.value"];return void 0===t&&(t=CBOR.decode(this["@ditto.cbor"]),this["@ditto.value"]=t),t}constructor(t,e=!1,n=!1){const r=e?t:CBOR.encode(t),i=n?r:validateDocumentIDCBOR(r);if(!i)throw new Error(`Can't create DocumentID, passed in value is not valid: ${t}`);this.isValidated=!n,this["@ditto.cbor"]=i}equals(t){const e=this["@ditto.cbor"],n=t["@ditto.cbor"];if(e===n)return!0;if(!(e instanceof Uint8Array))return!1;if(!(n instanceof Uint8Array))return!1;if(e.length!==n.length)return!1;for(let t=0;t<e.length;t+=1)if(e[t]!==n[t])return!1;return!0}toString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithoutQuotes")}toBase64String(){const t=this["@ditto.cbor"];return btoa(String.fromCharCode.apply(null,t))}toQueryCompatibleString(){return documentIDQueryCompatible(this["@ditto.cbor"],"WithQuotes")}toCBOR(){return this["@ditto.cbor"]}}function validateDocumentIDValue(t){if(void 0===t)throw new Error(`Invalid document ID: ${t}`);return t}function validateDocumentIDCBOR(t){const e=validateDocumentID(t);return null!=e?e:t}class Attachment{get metadata(){return this.token.metadata}getData(){return dittoGetCompleteAttachmentData(dittoBridge.pointerFor(this.ditto),attachmentBridge.pointerFor(this))}copyToPath(t){throw new Error("Can't copy attachment to path, not available when running in the browser.")}constructor(t,e){this.ditto=t,this.token=e}}const attachmentBridge=new Bridge(Attachment,freeAttachmentHandle);class AttachmentToken{constructor(t){if(t[DittoCRDTTypeKey]!==DittoCRDTType.attachment)throw new Error("Invalid attachment token");const e=t._id;if(!(e instanceof Uint8Array))throw new Error("Invalid attachment token id");const n=t._len;if("number"!=typeof n||n<0)throw new Error("Invalid attachment token length");const r=t._meta;if("object"!=typeof r)throw new Error("Invalid attachment token meta");this.id=e,this.len=n,this.metadata=r}}class AttachmentFetcher{stop(){AttachmentFetcher.stopWithContextInfo({ditto:this.ditto,attachmentTokenID:this.token.id,cancelTokenPromise:this.cancelTokenPromise})}then(t,e){return this.attachment.then(t,e)}constructor(t,e,n){this.ditto=t,this.token=e,this.eventHandler=n||null,this.cancelTokenPromise=null;const r=n||function(){};this.attachment=new Promise(((n,i)=>{const o=dittoBridge.pointerFor(t);this.cancelTokenPromise=dittoResolveAttachment(o,e.id,{onComplete:t=>{this.eventHandler=null,this.cancelTokenPromise=null;const e=new Attachment(this.ditto,this.token);attachmentBridge.bridge(t,(()=>e),{throwIfAlreadyBridged:!0}),r({type:"Completed",attachment:e}),n(e)},onProgress:(t,e)=>{r({type:"Progress",totalBytes:e,downloadedBytes:t})},onDelete:()=>{this.eventHandler=null,this.cancelTokenPromise=null,r({type:"Deleted"}),n(null)}},(t=>{this.eventHandler=null,this.cancelTokenPromise=null,i(t)}))}));const i={ditto:t,attachmentTokenID:e.id,cancelTokenPromise:this.cancelTokenPromise};AttachmentFetcher.finalizationRegistry.register(this,i,i)}static stopWithContextInfo(t){step((async()=>{const e=await t.cancelTokenPromise;if(e){dittoCancelResolveAttachment(dittoBridge.pointerFor(t.ditto),t.attachmentTokenID,e)}}))}}AttachmentFetcher.finalizationRegistry=new FinalizationRegistry(AttachmentFetcher.stopWithContextInfo);class Subscription{get collectionName(){return this.collection.name}cancel(){this.isCancelled||(this.isCancelled=!0,Subscription.remove(this,this.contextInfo))}constructor(t,e,n,r,i,o){this.isCancelled=!1,this.query=e,this.queryArgsCBOR=n,this.collection=t,this.contextInfo={ditto:t.store.ditto,collectionName:t.name,query:e,queryArgsCBOR:n,orderBys:r,limit:i,offset:o},Subscription.add(this,this.contextInfo)}static add(t,e){addSubscription(dittoBridge.pointerFor(e.ditto),e.collectionName,e.query,e.queryArgsCBOR,e.orderBys,e.limit,e.offset),this.finalizationRegistry.register(t,e,e)}static remove(t,e){removeSubscription(dittoBridge.pointerFor(e.ditto),e.collectionName,e.query,e.queryArgsCBOR,e.orderBys,e.limit,e.offset),t&&this.finalizationRegistry.unregister(e)}}Subscription.finalizationRegistry=new FinalizationRegistry((t=>{Subscription.remove(null,t)}));const privateToken$1="@ditto.64d129224a5377b63e9727479ec987d9";class Counter{constructor(){this.value=0}static"@ditto.create"(t,e,n){const r=t?new MutableCounter(privateToken$1):new Counter;return r.mutDoc=t,r.path=e,r.value=n,r}}class MutableCounter extends Counter{increment(t){const e=this.mutDoc,n=this.path;if(!e)throw new Error("Can't increment counter, only possible within the closure of a collection's update() method.");e.at(n)["@ditto.increment"](t),this.value+=t}constructor(){if(arguments[0]!==privateToken$1)throw new Error("MutableCounter constructor is for internal use only.");super()}}const privateToken="@ditto.ff82dae89821c5ab822a8b539056bce4";class Register{get value(){return this["@ditto.value"]}constructor(t){this["@ditto.value"]=t}static"@ditto.create"(t,e,n){const r=t?new MutableRegister(n,privateToken):new Register(n);return r["@ditto.mutableDocument"]=t,r["@ditto.path"]=e,r["@ditto.value"]=n,r}}class MutableRegister extends Register{get value(){return super.value}set value(t){this.set(t)}set(t){const e=this["@ditto.mutableDocument"],n=this["@ditto.path"];e.at(n)["@ditto.set"](t),this["@ditto.value"]=t}constructor(t){if(arguments[1]!==privateToken)throw new Error("MutableRegister constructor is for internal use only.");super(t)}}class RGA{get value(){return this["@ditto.value"]}constructor(t=[]){this["@ditto.value"]=t}static"@ditto.create"(t,e){const n=new RGA(e);return n["@ditto.path"]=t,n["@ditto.value"]=e,n}}class UpdateResult{static set(t,e,n){return new UpdateResult("set",t,e,n,void 0)}static incremented(t,e,n){return new UpdateResult("incremented",t,e,void 0,n)}static removed(t,e){return new UpdateResult("removed",t,e,void 0,void 0)}constructor(t,e,n,r,i){this.type=t,this.docID=e,this.path=n,void 0!==r&&(this.value=r),void 0!==i&&(this.amount=i)}}function augmentJSONValue(t,e,n){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,r)=>augmentJSONValue(t,e,`${n}[${r}]`)));if(t[DittoCRDTTypeKey]===DittoCRDTType.counter)return Counter["@ditto.create"](e,n,t._value);if(t[DittoCRDTTypeKey]===DittoCRDTType.register)return Register["@ditto.create"](e,n,t._value);if(t[DittoCRDTTypeKey]===DittoCRDTType.rga){const r=augmentJSONValue(t._value,e,n);return RGA["@ditto.create"](n,r)}if(t[DittoCRDTTypeKey]===DittoCRDTType.attachment)return new AttachmentToken(t);for(const[r,i]of Object.entries(t))t[r]=augmentJSONValue(i,e,`${n}['${r}']`);return t}return t}function desugarJSObject(t,e=!1){if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,e)=>desugarJSObject(t,!1)));if(t instanceof DocumentID)return t.value;if(t instanceof Counter){const e={};return e[DittoCRDTTypeKey]=DittoCRDTType.counter,e._value=t.value,e}if(t instanceof Register){const e={};return e[DittoCRDTTypeKey]=DittoCRDTType.register,e._value=t.value,e}if(t instanceof RGA){const e={};return e[DittoCRDTTypeKey]=DittoCRDTType.rga,e._value=desugarJSObject(t.value),e}if(t instanceof Attachment){const e={_id:t.token.id,_len:t.token.len,_meta:t.token.metadata};return e[DittoCRDTTypeKey]=DittoCRDTType.attachment,e}for(const[e,n]of Object.entries(t))t[e]=desugarJSObject(n,!1);return t}return t}const regularKeyPattern=/\.([A-Za-z_]\w*)/.source,subscriptIndexPattern=/\[(\d+)\]/.source,subscriptSingleQuoteKeyPattern=/\[\'(.+?)\'\]/.source,subscriptDoubleQuoteKeyPattern=/\[\"(.+?)\"\]/.source,validKeyPathPattern=`((${regularKeyPattern})|(${subscriptIndexPattern})|(${subscriptSingleQuoteKeyPattern})|(${subscriptDoubleQuoteKeyPattern}))*`,regularKeyRegExp=new RegExp(`^${regularKeyPattern}`),subscriptIndexRegExp=new RegExp(`^${subscriptIndexPattern}`),subscriptSingleQuoteKeyRegExp=new RegExp(`^${subscriptSingleQuoteKeyPattern}`),subscriptDoubleQuoteKeyRegExp=new RegExp(`^${subscriptDoubleQuoteKeyPattern}`),validKeyPathRegExp=new RegExp(`^${validKeyPathPattern}$`);class KeyPath{static withLeadingDot(t){if("number"==typeof t)return t;if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);return"string"==typeof t&&!!t.match(/^[A-Za-z_]/)?`.${t}`:t}static withoutLeadingDot(t){if("number"==typeof t)return t;if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);return"string"==typeof t&&!!t.match(/^\./)?t.slice(1):t}static validate(t,e={}){var n;const r=null!==(n=e.isInitial)&&void 0!==n&&n;if("number"==typeof t)return Math.floor(Math.abs(t));if("string"!=typeof t)throw new Error(`Key-path must be a string or a number but is ${typeof t}: ${t}`);const i=this.withLeadingDot(t);if(!validKeyPathRegExp.test(i))throw new Error(`Key-path is not valid: ${t}`);return r?t:i}static evaluate(t,e,n={}){var r;const i=null!==(r=n.stopAtLastContainer)&&void 0!==r&&r,o={keyPath:t,object:e,options:{...n},coveredPath:null,nextPathComponent:null,remainingPath:t,value:e};return function recurse(t,e){if(""===e)return o.value=t,o;const{nextPathComponentRaw:n,nextPathComponent:r,remainingPath:a}=function advance(t){if("number"==typeof t)return{nextPathComponentRaw:t,nextPathComponent:t,remainingPath:""};if("string"!=typeof t)throw new Error(`Can't return value at given keyPath, expected keyPath to be a string or a number but got ${typeof t}: ${t}`);const e=t.match(regularKeyRegExp);if(null!==e){const n=e[0],r=e[1];return{nextPathComponentRaw:n,nextPathComponent:r,remainingPath:t.slice(r.length+1)}}const n=t.match(subscriptIndexRegExp);if(null!==n){const e=n[0],r=n[1];return{nextPathComponentRaw:e,nextPathComponent:parseInt(r),remainingPath:t.slice(r.length+2)}}const r=t.match(subscriptSingleQuoteKeyRegExp);if(null!==r){const e=r[0],n=r[1];return{nextPathComponentRaw:e,nextPathComponent:n,remainingPath:t.slice(n.length+4)}}const i=t.match(subscriptDoubleQuoteKeyRegExp);if(null!==i){const e=i[0],n=i[1];return{nextPathComponentRaw:e,nextPathComponent:n,remainingPath:t.slice(n.length+4)}}throw new Error(`Can't return value at keyPath because the following part of the keyPath is invalid: ${t}`)}(e);return o.nextPathComponent=r,o.remainingPath=a,null===o.coveredPath||"number"==typeof n?o.coveredPath=n:o.coveredPath+=n,""===a&&i?(o.value=t,o):recurse(t[r],a)}(e,this.withLeadingDot(t))}constructor(){}}class DocumentPath{at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e),r=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new DocumentPath(this.document,r,!1)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"DocumentPath.at() validation failed index:"});return new DocumentPath(this.document,`${this.path}[${e.toString()}]`,!1)}throw new Error(`Can't return document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const t=this.underlyingValueForPathType("Counter");return void 0!==t?Counter["@ditto.create"](null,this.path,t):null}get register(){const t=this.underlyingValueForPathType("Register");return void 0!==t?Register["@ditto.create"](null,this.path,t):null}get rga(){const t=this.underlyingValueForPathType("Rga");return void 0!==t?RGA["@ditto.create"](this.path,t):null}get attachmentToken(){const t=this.underlyingValueForPathType("Attachment");return void 0!==t?new AttachmentToken(t):null}constructor(t,e,n){this.document=t,this.path=n?KeyPath.validate(e,{isInitial:!0}):e}underlyingValueForPathType(t){const e=this.path,n=this.document,r=documentGetCBORWithPathType(documentBridge.pointerFor(n),e,t);return null!==r.cbor?CBOR.decode(r.cbor):void 0}}class MutableDocumentPath{at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e),r=KeyPath.withoutLeadingDot(`${this.path}${n}`);return new MutableDocumentPath(this.mutableDocument,r,!1)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"MutableDocumentPath.at() validation failed index:"});return new MutableDocumentPath(this.mutableDocument,`${this.path}[${e.toString()}]`,!1)}throw new Error(`Can't return mutable document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}get value(){return this.underlyingValueForPathType("Any")}get counter(){const t=this.underlyingValueForPathType("Counter");return void 0!==t?Counter["@ditto.create"](this.mutableDocument,this.path,t):null}get register(){const t=this.underlyingValueForPathType("Register");return void 0!==t?Register["@ditto.create"](this.mutableDocument,this.path,t):null}get rga(){const t=this.underlyingValueForPathType("Rga");return void 0!==t?RGA["@ditto.create"](this.path,t):null}get attachmentToken(){const t=this.underlyingValueForPathType("Attachment");return void 0!==t?new AttachmentToken(t):null}set(t,e){return this["@ditto.set"](t,e)}remove(){return this["@ditto.remove"]()}constructor(t,e,n){this.mutableDocument=t,this.path=n?KeyPath.validate(e,{isInitial:!0}):e}underlyingValueForPathType(t){const e=this.path,n=this.mutableDocument,r=documentGetCBORWithPathType(mutableDocumentBridge.pointerFor(n),e,t);return null!==r.cbor?CBOR.decode(r.cbor):void 0}"@ditto.increment"(t){documentIncrementCounter(mutableDocumentBridge.pointerFor(this.mutableDocument),this.path,t);const e=UpdateResult.incremented(this.mutableDocument.id,this.path,t);this.recordUpdateResult(e)}"@ditto.set"(t,e){const n=mutableDocumentBridge.pointerFor(this.mutableDocument),r=desugarJSObject(t,!1),i=CBOR.encode(r);e?documentSetCBORWithTimestamp(n,this.path,i,!0,0):documentSetCBOR(n,this.path,i,!0);const o=augmentJSONValue(CBOR.decode(i),this.mutableDocument,this.path),a=UpdateResult.set(this.mutableDocument.id,this.path,o);this.recordUpdateResult(a)}"@ditto.remove"(){documentRemove(mutableDocumentBridge.pointerFor(this.mutableDocument),this.path),this.updateInMemory(((t,e)=>{Array.isArray(t)&&"number"==typeof e?t.splice(e,1):delete t[e]}));const t=UpdateResult.removed(this.mutableDocument.id,this.path);this.recordUpdateResult(t)}updateInMemory(t){const e=this.mutableDocument.value,n=KeyPath.evaluate(this.path,e,{stopAtLastContainer:!0});t(n.value,n.nextPathComponent)}recordUpdateResult(t){const e=this.mutableDocument["@ditto.updateResults"].slice();e.push(t),Object.freeze(e),this.mutableDocument["@ditto.updateResults"]=e}}class Document{static hash(t){return documentsHash(documentsFrom(t).map((t=>documentBridge.pointerFor(t))))}static hashMnemonic(t){return documentsHashMnemonic(documentsFrom(t).map((t=>documentBridge.pointerFor(t))))}get id(){let t=this["@ditto.id"];if(void 0===t){const e=documentID(documentBridge.pointerFor(this));t=new DocumentID(e,!0),this["@ditto.id"]=t}return t}get path(){return new DocumentPath(this,"",!1)}get value(){let t=this["@ditto.value"];return void 0===t&&(t=this.path.value,this["@ditto.value"]=t),t}at(t){return this.path.at(t)}constructor(){}static idCBOR(t){return documentID(documentBridge.pointerFor(t))}static canonicalizedIDCBOR(t){return validateDocumentIDCBOR(t)}static isIDCBORCanonical(t){return t===this.canonicalizedIDCBOR(t)}}class MutableDocument{get id(){let t=this["@ditto.id"];if(void 0===t){const e=documentID(mutableDocumentBridge.pointerFor(this));t=new DocumentID(e,!0),this["@ditto.id"]=t}return t}get path(){return new MutableDocumentPath(this,"",!1)}get value(){return this.path.value}at(t){return this.path.at(t)}constructor(){this["@ditto.updateResults"]=[]}static idCBOR(t){return documentID(mutableDocumentBridge.pointerFor(t))}}MutableDocument.canonicalizedIDCBOR=Document.canonicalizedIDCBOR,MutableDocument.isIDCBORCanonical=Document.isIDCBORCanonical;const documentBridge=new Bridge(Document,documentFree),mutableDocumentBridge=new Bridge(MutableDocument,documentFree);function documentsFrom(t){if(!t)return[];if(t instanceof Document)return[t];if(t instanceof Array)return t;throw new Error(`Expected null, a single document, or an array of documents but got value of type ${typeof t}: ${t}`)}class UpdateResultsMap{get(t){const e=(t instanceof DocumentID?t:new DocumentID(t)).toString();return this.updateResultsByDocumentIDString[e]}keys(){return this.documentIDs.slice()}constructor(t,e){const n=t.map((t=>t.toString())).sort().join(", ");if(n!==Object.keys(e).sort().join(", "))throw new Error("Internal inconsistency, can't construct update results map, documentIDs must all be keys in update results (by document ID string)");this.documentIDs=t.slice(),this.updateResultsByDocumentIDString={...e}}}class LiveQueryEventInitial{constructor(){this.isInitial=!0}hash(t){return documentsHash(t.map((t=>documentBridge.pointerFor(t))))}hashMnemonic(t){return documentsHashMnemonic(t.map((t=>documentBridge.pointerFor(t))))}}class LiveQueryEventUpdate{hash(t){return documentsHash(t.map((t=>documentBridge.pointerFor(t))))}hashMnemonic(t){return documentsHashMnemonic(t.map((t=>documentBridge.pointerFor(t))))}constructor(t){this.isInitial=!1,this.oldDocuments=t.oldDocuments,this.insertions=t.insertions,this.deletions=t.deletions,this.updates=t.updates,this.moves=t.moves}}class SingleDocumentLiveQueryEvent{hash(t){return documentsHash(null===t?[]:[documentBridge.pointerFor(t)])}hashMnemonic(t){return documentsHashMnemonic(null===t?[]:[documentBridge.pointerFor(t)])}constructor(t,e){this.isInitial=t,this.oldDocument=e}}class LiveQuery{get collectionName(){return this.collection.name}get isStopped(){return null===this.liveQueryID}stop(){var t;const e=this.liveQueryID;if(null!==e){this.collection.store.ditto.keepAlive.release(`LiveQuery.${e}`),this.liveQueryID=null;const n=dittoBridge.pointerFor(this.collection.store.ditto);null===(t=this.subscription)||void 0===t||t.cancel(),liveQueryStop(n,e)}}constructor(t,e,n,r,i,o,a,s,c){this.query=t,this.queryArgs=e?Object.freeze({...e}):null,this.queryArgsCBOR=n,this.orderBys=r,this.limit=i,this.offset=o,this.collection=a,this.handler=c,s&&(this.subscription=s);const d=a.name,l=new WeakRef(a.store.ditto);let _;const signalNext=async()=>{const t=l.deref();if(t){const e=dittoBridge.pointerFor(t);await liveQuerySignalAvailableNext(e,_)}},u=dittoBridge.pointerFor(a.store.ditto);if(_=liveQueryRegister(u,d,t,n,this.orderBys,i,o,(t=>{const e=t.documents.map((t=>documentBridge.bridge(t)));let n;n=t.is_initial?new LiveQueryEventInitial:new LiveQueryEventUpdate({oldDocuments:t.old_documents.map((t=>documentBridge.bridge(t))),insertions:t.insertions,deletions:t.deletions,updates:t.updates,moves:t.moves.map((t=>({from:t[0],to:t[1]})))}),c(e,n,signalNext)})),!_)throw new Error("Internal inconsistency, couldn't create a valid live query ID.");this.liveQueryID=_,step((async()=>await liveQueryStart(u,_))),a.store.ditto.keepAlive.retain(`LiveQuery.${_}`)}async signalNext(){const t=dittoBridge.pointerFor(this.collection.store.ditto);await liveQuerySignalAvailableNext(t,this.liveQueryID)}}class PendingCursorOperation{sort(t,e="ascending"){return this.orderBys.push({query:t,direction:"ascending"===e?"Ascending":"Descending"}),this}offset(t){if(t<0)throw new Error(`Can't offset by '${t}', offset must be >= 0`);if(!Number.isFinite(t))throw new Error(`Can't offset by '${t}', offset must be a finite number`);if(Number.isNaN(t))throw new Error(`Can't offset by '${t}', offset must be a valid number`);if(t!==Math.round(t))throw new Error(`Can't offset by '${t}', offset must be an integer number`);return this.currentOffset=t,this}limit(t){if(t<-1)throw new Error(`Can't limit to '${t}', limit must be >= -1 (where -1 means unlimited)`);if(!Number.isFinite(t))throw new Error(`Can't limit to '${t}', limit must be a finite number`);if(Number.isNaN(t))throw new Error(`Can't limit to '${t}', limit must be a valid number`);if(t!==Math.round(t))throw new Error(`Can't limit to '${t}', limit must be an integer number`);return this.currentLimit=t,this}subscribe(){return new Subscription(this.collection,this.query,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)}observeLocal(t){return this._observe(t,!1,!1)}observeLocalWithNextSignal(t){return this._observe(t,!1,!0)}async remove(){const t=this.query,e=dittoBridge.pointerFor(this.collection.store.ditto);return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const n=await writeTransaction(e),r=await collectionRemoveQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,n),r}))).map((t=>new DocumentID(t,!0)))}async evict(){const t=this.query,e=dittoBridge.pointerFor(this.collection.store.ditto);return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const n=await writeTransaction(e),r=await collectionEvictQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return await writeTransactionCommit(e,n),r}))).map((t=>new DocumentID(t,!0)))}async exec(){const t=this.query,e=dittoBridge.pointerFor(this.collection.store.ditto);return(await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionExecQueryStr(e,this.collection.name,null,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset)))).map((t=>documentBridge.bridge(t)))}async update(t){return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=this.query,n=dittoBridge.pointerFor(this.collection.store.ditto),r=await writeTransaction(n),i=await collectionExecQueryStr(n,this.collection.name,r,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset),o=i.map((t=>mutableDocumentBridge.bridge(t,(()=>new MutableDocument))));t(o);const a=[],s={};for(const t of o){const e=t.id,n=e.toString(),r=t["@ditto.updateResults"];if(s[n])throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${n}`);a.push(e),s[n]=r,mutableDocumentBridge.pointerFor(t),mutableDocumentBridge.unregister(t)}return await collectionUpdateMultiple(n,this.collection.name,r,i),await writeTransactionCommit(n,r),new UpdateResultsMap(a,s)}))}constructor(t,e,n){this.currentLimit=-1,this.currentOffset=0,this.orderBys=[],this.query=validateQuery(t),this.queryArgs=e?Object.freeze({...e}):null,this.collection=n,this.queryArgsCBOR=e?CBOR.encode(e):null}_observe(t,e,n){const r=e?this.subscribe():null;const i=n?t:function wrappedHandler(e,n,r){try{return t.call(this,e,n)}finally{r()}};return new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,r,i)}then(t,e){return this.exec().then(t,e)}}class PendingIDSpecificOperation{subscribe(){return new Subscription(this.collection,this.query,null,[],-1,0)}observeLocal(t){return this._observe(t,!1,!1)}observeLocalWithNextSignal(t){return this._observe(t,!1,!0)}async remove(){const t=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await writeTransaction(t),n=await collectionRemove(t,this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t,e),n}))}async evict(){const t=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await writeTransaction(t),n=await collectionEvict(t,this.collection.name,e,this.documentIDCBOR);return await writeTransactionCommit(t,e),n}))}async exec(){const t=dittoBridge.pointerFor(this.collection.store.ditto);return await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>{const e=await readTransaction(t),n=await collectionGet(t,this.collection.name,this.documentIDCBOR,e);let r;return n&&(r=documentBridge.bridge(n)),readTransactionFree(e),r}))}async update(t){const e=dittoBridge.pointerFor(this.collection.store.ditto),n=await readTransaction(e),r=await collectionGet(e,this.collection.name,this.documentIDCBOR,n);if(readTransactionFree(n),!r)throw new Error(`Can't update, document with ID '${this.documentID.toString()}' not found in collection named '${this.collection.name}'`);const i=mutableDocumentBridge.bridge(r,(()=>new MutableDocument));t(i),mutableDocumentBridge.unregister(i);const o=await writeTransaction(e);return await collectionUpdate(e,this.collection.name,o,r),await writeTransactionCommit(e,o),i["@ditto.updateResults"].slice()}constructor(t,e){this.documentID=t,this.collection=e,this.documentIDCBOR=t.toCBOR()}_observe(t,e,n){const r=e?this.subscribe():null;return new LiveQuery(this.query,null,null,[],-1,0,this.collection,r,((e,r,i)=>{if(e.length>1){const t=e.map((t=>t.id.toBase64String()));throw new Error(`Internal inconsistency, single document live query returned more than one document. Query: ${this.query}, documentIDs: ${t.join(", ")}.`)}if(!1===r.isInitial&&r.oldDocuments.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one old documents. Query ${this.query}.`);if(!1===r.isInitial&&r.insertions.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one insertion, which doesn't make sense for single document observations. Query ${this.query}.`);if(!1===r.isInitial&&r.deletions.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one deletion, which doesn't make sense for single document observations. Query ${this.query}.`);if(!1===r.isInitial&&r.updates.length>1)throw new Error(`Internal inconsistency, single document live query returned an update event with more than one update, which doesn't make sense for single document observations. Query ${this.query}.`);if(!1===r.isInitial&&r.moves.length>0)throw new Error(`Internal inconsistency, single document live query returned an update event with moves, which doesn't make sense for single document observations. Query ${this.query}.`);if((!0===r.isInitial?0:r.insertions.length+r.deletions.length+r.updates.length)>1)throw new Error(`Internal inconsistency, single document live query returned a combination of inserts, updates, and/or deletes, which doesn't make sense for single document observation. Query ${this.query}.`);const o=e[0]||null,a=!0===r.isInitial?void 0:r.oldDocuments[0],s=new SingleDocumentLiveQueryEvent(r.isInitial,a);if(n)t(o,s,i);else try{t(o,s)}finally{i()}}))}then(t,e){return this.exec().then(t,e)}get query(){return`_id == ${this.documentID.toQueryCompatibleString()}`}}class Collection{find(t,e){return new PendingCursorOperation(t,null!=e?e:null,this)}findAll(){return this.find("true")}findByID(t){const e=t instanceof DocumentID?t:new DocumentID(t);return new PendingIDSpecificOperation(e,this)}async upsert(t,e={}){var n;const r=null!==(n=e.writeStrategy)&&void 0!==n?n:"merge",i=this.store.ditto,o=dittoBridge.pointerFor(i),a=t._id;let s;s=void 0===a?void 0:a instanceof DocumentID?a:new DocumentID(a);const c=void 0===s?null:s.toCBOR(),d=desugarJSObject(t,!0),l=CBOR.encode(d),_=await performAsyncToWorkaroundNonAsyncFFIAPI((async()=>await collectionInsertValue(o,this.name,l,c,r)));return new DocumentID(_,!0)}async newAttachment(t,e={}){const n=this.store.ditto,r=dittoBridge.pointerFor(n),{id:i,len:o,handle:a}=await(async()=>{if("string"==typeof t)throw new Error("Can't create attachment from file when running in the browser. Please pass the raw data (as a Uint8Array) instead.");if(t instanceof Uint8Array)return await dittoNewAttachmentFromBytes(r,t);throw new Error(`Can't create new attachment, only file path as string or raw data as Uint8Array are supported, but got: ${typeof t}, ${t}`)})(),s={_id:i,_len:o,_meta:{...e}};s[DittoCRDTTypeKey]=DittoCRDTType.attachment;const c=new AttachmentToken(s),d=new Attachment(n,c);return attachmentBridge.bridge(a,(()=>d),{throwIfAlreadyBridged:!0})}fetchAttachment(t,e){const n=this.store.ditto;return new AttachmentFetcher(n,t,e)}constructor(t,e){this.name=t,this.store=e}findByIDCBOR(t){const e=new DocumentID(t,!0,!0);return new PendingIDSpecificOperation(e,this)}}class CollectionsEvent{static initial(t){return new CollectionsEvent({isInitial:!0,collections:t,oldCollections:[],insertions:[],deletions:[],updates:[],moves:[]})}constructor(t){this.isInitial=t.isInitial,this.collections=t.collections,this.oldCollections=t.oldCollections,this.insertions=t.insertions,this.deletions=t.deletions,this.updates=t.updates,this.moves=t.moves}}class PendingCollectionsOperation{sort(t,e="ascending"){return this.pendingCursorOperation.sort(t,e),this}offset(t){return this.pendingCursorOperation.offset(t),this}limit(t){return this.pendingCursorOperation.limit(t),this}subscribe(){return this.pendingCursorOperation.subscribe()}observeLocal(t){return this._observe(t,!1,!1)}observeLocalWithNextSignal(t){return this._observe(t,!1,!0)}async exec(){return collectionsFromDocuments(await this.pendingCursorOperation.exec(),this.store)}constructor(t){this.store=t,this.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",t))}then(t,e){return this.exec().then(t,e)}_observe(t,e,n){const r=new WeakRef(this);return this.pendingCursorOperation._observe((function(e,i,o){const a=r.deref();if(null===a)return;const s=collectionsFromDocuments(e,a.store);let c;if(!0===i.isInitial)c=CollectionsEvent.initial(s);else{const t=collectionsFromDocuments(i.oldDocuments,a.store);c=new CollectionsEvent({isInitial:!1,collections:s,oldCollections:t,insertions:i.insertions,deletions:i.deletions,updates:i.updates,moves:i.moves})}n?t(c,o):t(c)}),e,n)}}function collectionsFromDocuments(t,e){const n=[];for(const r of t){const t=r.at("name").value;void 0!==t&&"string"==typeof t&&n.push(new Collection(t,e))}return n}class Store{collection(t){return new Collection(t,this)}collections(){return new PendingCollectionsOperation(this.ditto.store)}collectionNames(){return dittoGetCollectionNames(dittoBridge.pointerFor(this.ditto))}constructor(t){this.ditto=t}async registerLiveQueryWebhook(t,e,n){const r=validateQuery(e),i=await liveQueryWebhookRegister(dittoBridge.pointerFor(this.ditto),t,r,[],0,0,n);return new DocumentID(i,!0)}}function addressToString(t){return`${t.siteId}-${t.pubkey}`}class Presence{get graph(){const t=dittoPresenceV3(dittoBridge.pointerFor(this.ditto));return JSON.parse(t)}observe(t){const e=this.observerManager.addObserver(t),n=new Observer(this.observerManager,e,{stopsWhenFinalized:!0});return t(this.graph),n}constructor(t){this.ditto=t,this.observerManager=new ObserverManager("PresenceObservation",{keepAlive:t.keepAlive,register:t=>{dittoRegisterPresenceV3Callback(dittoBridge.pointerFor(this.ditto),t)},unregister:()=>{dittoClearPresenceV3Callback(dittoBridge.pointerFor(this.ditto))},process:t=>[JSON.parse(t)]})}}class PresenceManager{constructor(t){this.ditto=t,this.isRegistered=!1,this.currentRemotePeers=[],this.callbacksByPresenceToken={}}addObserver(t){this.registerIfNeeded();const e=generateEphemeralToken();return this.callbacksByPresenceToken[e]=t,this.ditto.keepAlive.retain(`PresenceObservation.${e}`),t(this.currentRemotePeers),e}removeObserver(t){this.ditto.keepAlive.release(`PresenceObservation.${t}`),delete this.callbacksByPresenceToken[t],this.unregisterIfNeeded()}hasObservers(){return Object.keys(this.callbacksByPresenceToken).length>0}registerIfNeeded(){if(!this.isRegistered){this.isRegistered=!0;const t=dittoBridge.pointerFor(this.ditto),e=dittoPresenceV1(t);this.currentRemotePeers=this.decode(e).sort(this.compareRemotePeers),dittoRegisterPresenceV1Callback(t,this.handlePresenceV1Callback.bind(this))}}unregisterIfNeeded(){if(!this.hasObservers()&&this.isRegistered){this.isRegistered=!1;dittoRegisterPresenceV1Callback(dittoBridge.pointerFor(this.ditto),null),this.currentRemotePeers=[]}}handlePresenceV1Callback(t){const e=this.decode(t).sort(this.compareRemotePeers);this.currentRemotePeers=e,this.notify()}notify(){for(const t in this.callbacksByPresenceToken){(0,this.callbacksByPresenceToken[t])(this.currentRemotePeers)}}decode(t){return JSON.parse(t).map((t=>{var e,n;return{networkID:t.network_id,deviceName:t.device_name,rssi:null!==(e=t.rssi)&&void 0!==e?e:void 0,approximateDistanceInMeters:null!==(n=t.approximate_distance_in_meters)&&void 0!==n?n:void 0,connections:t.connections}}))}finalize(t){this.removeObserver(t)}compareRemotePeers(t,e){return 0===t.connections.length&&e.connections.length>0?1:t.connections.length>0&&0===e.connections.length||t.deviceName<e.deviceName?-1:t.deviceName>e.deviceName?1:0}}class TransportConditionsManager extends ObserverManager{constructor(t){super("TransportConditionsObservation",{keepAlive:t.keepAlive}),this.ditto=t}register(t){return dittoRegisterTransportConditionChangedCallback(dittoBridge.pointerFor(this.ditto),t)}unregister(){return dittoRegisterTransportConditionChangedCallback(dittoBridge.pointerFor(this.ditto),null)}process(t,e){let n,r;switch(t){case"Bluetooth":n="BLE";break;case"Tcp":n="TCP";break;case"Awdl":n="AWDL";break;case"Mdns":n="MDNS"}switch(e){case"Unknown":r="Unknown";break;case"Ok":r="OK";break;case"GenericFailure":r="GenericFailure";break;case"AppInBackground":r="AppInBackground";break;case"MdnsFailure":r="MDNSFailure";break;case"TcpListenFailure":r="TCPListenFailure";break;case"NoBleCentralPermission":r="NoBLECentralPermission";break;case"NoBlePeripheralPermission":r="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":r="CannotEstablishConnection";break;case"BleDisabled":r="BLEDisabled";break;case"NoBleHardware":r="NoBLEHardware";break;case"WifiDisabled":r="WiFiDisabled";break;case"TemporarilyUnavailable":r="TemporarilyUnavailable"}return[r,n]}}class Sync{constructor(t){this.bluetoothLETransportPointer=null,this.awdlTransportPointer=null,this.lanTransportPointer=null,this.mdnsClientTransportPointer=null,this.mdnsServerAdvertiserPointer=null;const e={identity:t.identity,transportConfig:new TransportConfig,isWebValid:!1,isX509Valid:!1,isSyncActive:!1};this.ditto=t,this.parameters=e,this.state=stateFrom(e),this.staticTCPClientsByAddress={},this.websocketClientsByURL={}}update(t){this.parameters={...t};const e=this.state,n=stateFrom(this.parameters);this.updatePeerToPeerBluetoothLE(e,n),this.updatePeerToPeerAWDL(e,n),this.updatePeerToPeerLAN(e,n),this.updateListenTCP(e,n),this.updateListenHTTP(e,n),this.updateConnectTCPServers(e,n),this.updateConnectWebsocketURLs(e,n),this.updateGlobal(e,n),this.state=n}updatePeerToPeerBluetoothLE(t,e){dittoBridge.pointerFor(this.ditto);const n=t.effectiveTransportConfig.peerToPeer.bluetoothLE,r=e.effectiveTransportConfig.peerToPeer.bluetoothLE,i=!n.isEnabled&&r.isEnabled,o=n.isEnabled&&!r.isEnabled;if(i&&this.bluetoothLETransportPointer)throw new Error("Internal inconsistency, when starting BLE transport, no BLE transport pointer should exist.");if(o&&!this.bluetoothLETransportPointer)throw new Error("Internal inconsistency, when stopping BLE transport, a BLE transport pointer should exist.");if(i){if(!bleIsAvailable())throw new Error("Can't start P2P BluetoothLE transport because not available.");this.bluetoothLETransportPointer=bleCreate()}o&&(bleDestroy(this.bluetoothLETransportPointer),delete this.bluetoothLETransportPointer)}updatePeerToPeerAWDL(t,e){dittoBridge.pointerFor(this.ditto);const n=t.effectiveTransportConfig.peerToPeer.awdl,r=e.effectiveTransportConfig.peerToPeer.awdl,i=!n.isEnabled&&r.isEnabled,o=n.isEnabled&&!r.isEnabled;if(i&&this.awdlTransportPointer)throw new Error("Internal inconsistency, when starting AWDL transport, no AWDL transport pointer should exist.");if(o&&!this.awdlTransportPointer)throw new Error("Internal inconsistency, when stopping AWDL transport, an AWDL transport pointer should exist.");if(i){if(!awdlIsAvailable())throw new Error("Can't start P2P AWDL transport because not available.");this.awdlTransportPointer=awdlCreate()}o&&(awdlDestroy(this.awdlTransportPointer),this.awdlTransportPointer=null)}updatePeerToPeerLAN(t,e){const n=dittoBridge.pointerFor(this.ditto),r=t.effectiveTransportConfig.peerToPeer.lan,i=e.effectiveTransportConfig.peerToPeer.lan;if(r.isEnabled&&(r.isMdnsEnabled&&(lanDestroy(this.lanTransportPointer),delete this.lanTransportPointer),r.isMulticastEnabled&&dittoRemoveMulticastTransport(n)),i.isEnabled){if(i.isMdnsEnabled){if(!lanIsAvailable())throw new Error("Can't start P2P LAN transport because not available.");this.lanTransportPointer=lanCreate()}i.isMulticastEnabled&&dittoAddMulticastTransport(n)}}updateListenTCP(t,e){const n=t.effectiveTransportConfig.listen.tcp,r=e.effectiveTransportConfig.listen.tcp;if(TransportConfig.areListenTCPsEqual(r,n))return;const i=dittoBridge.pointerFor(this.ditto);n.isEnabled&&dittoStopTCPServer(i),r.isEnabled&&dittoStartTCPServer(i,`${r.interfaceIP}:${r.port}`)}updateListenHTTP(t,e){const n=t.effectiveTransportConfig.listen.http,r=e.effectiveTransportConfig.listen.http;if(TransportConfig.areListenHTTPsEqual(n,r))return;const i=dittoBridge.pointerFor(this.ditto);n.isEnabled&&dittoStopHTTPServer(i),r.isEnabled&&dittoStartHTTPServer(i,`${r.interfaceIP}:${r.port}`,r.staticContentPath||null,r.websocketSync?"Enabled":"Disabled",r.tlsCertificatePath||null,r.tlsKeyPath||null)}updateConnectTCPServers(t,e){const n=Object.getOwnPropertyNames(this.staticTCPClientsByAddress),r=e.effectiveTransportConfig.connect.tcpServers,i=new Set(r);for(const t of n)i.delete(t);const o=new Set(n);for(const t of r)o.delete(t);const a=i.values(),s=o.values();for(const t of a){const e=addStaticTCPClient(dittoBridge.pointerFor(this.ditto),t),n=staticTCPClientBridge.bridge(e);this.staticTCPClientsByAddress[t]=n}for(const t of s){const e=this.staticTCPClientsByAddress[t];if(!e)throw new Error(`Internal inconsistency, can't disconnect from TCP address '${t}', no staticTCPClient found.`);const n=staticTCPClientBridge.pointerFor(e);staticTCPClientBridge.unregister(e),staticTCPClientFreeHandle(n),delete this.staticTCPClientsByAddress[t]}}updateConnectWebsocketURLs(t,e){const n=Object.getOwnPropertyNames(this.websocketClientsByURL),r=e.effectiveTransportConfig.connect.websocketURLs.slice(),i=new Set(r);for(const t of n)i.delete(t);const o=new Set(n);for(const t of r)o.delete(t);const a=i.values(),s=o.values(),c=e.effectiveTransportConfig.global.routingHint;for(const t of a){const e=addWebsocketClient(dittoBridge.pointerFor(this.ditto),t,c),n=websocketClientBridge.bridge(e);this.websocketClientsByURL[t]=n}for(const t of s){const e=this.websocketClientsByURL[t];if(!e)throw new Error(`Internal inconsistency, can't disconnect from websocket URL '${t}', no websocketClient found.`);const n=websocketClientBridge.pointerFor(e);websocketClientBridge.unregister(e),websocketClientFreeHandle(n),delete this.websocketClientsByURL[t]}}updateGlobal(t,e){t.effectiveTransportConfig.global.syncGroup!==e.effectiveTransportConfig.global.syncGroup&&dittoSetSyncGroup(dittoBridge.pointerFor(this.ditto),e.effectiveTransportConfig.global.syncGroup)}}function stateFrom(t){var e;const n=t.transportConfig.copy(),r=t.identity,i=t.isSyncActive,o=t.isX509Valid,a=t.isWebValid;let s,c;n.connect.tcpServers,n.connect.websocketURLs;let d=!1;"onlinePlayground"!==r.type&&"onlineWithAuthentication"!==r.type||(s=r.appID,c=null!==(e=r.customDittoCloudURL)&&void 0!==e?e:null,d=!r.hasOwnProperty("enableDittoCloudSync")||r.enableDittoCloudSync);{const t=[];if(n.peerToPeer.bluetoothLE.isEnabled&&t.push("BluetoothLE"),n.peerToPeer.awdl.isEnabled&&t.push("AWDL"),n.peerToPeer.lan.isEnabled&&t.push("LAN"),t.length>0)throw new Error(`Ditto does not support P2P transports when running in the browser, but the following were enabled: ${t.join(", ")}`)}if(i&&o||(n.peerToPeer.bluetoothLE.isEnabled=!1,n.peerToPeer.awdl.isEnabled=!1,n.peerToPeer.lan.isEnabled=!1,n.listen.tcp.isEnabled=!1,n.connect.tcpServers=[]),i&&a||(n.connect.websocketURLs=[]),i||(n.listen.http.isEnabled=!1),i&&a&&d){const t=null!=c?c:defaultDittoCloudURL(s);n.connect.websocketURLs.push(t)}return n.peerToPeer.lan.isEnabled&&!n.listen.tcp.isEnabled&&(n.listen.tcp.isEnabled=!0,n.listen.tcp.interfaceIP="0.0.0.0",n.listen.tcp.port=0),{underlyingSyncParameters:t,effectiveTransportConfig:n.freeze()}}class Ditto{get sdkVersion(){return dittoBridge.pointerFor(this),dittoGetSDKVersion()}constructor(t,e){this.isWebValid=!1,this.isX509Valid=!1;const n=null!=t?t:{type:"offlinePlayground",appID:""},r=e&&e.trim().length>0?e:"ditto",i=Object.freeze(this.validateIdentity(n));this.identity=Object.freeze(i),this.path=r,this.deviceName=navigator.userAgent,this.keepAlive=new KeepAlive;const o=uninitializedDittoMake(r);let a=null;const s=new WeakRef(this),c=(()=>{var t,e,n;if("offlinePlayground"===i.type)return dittoAuthClientMakeForDevelopment(r,i.appID,null!==(t=i.siteID)&&void 0!==t?t:0);if("manual"===i.type)return dittoAuthClientMakeWithStaticX509(i.certificate);if("sharedKey"===i.type)return dittoAuthClientMakeWithSharedKey(r,i.appID,i.sharedKey,i.siteID);if("onlinePlayground"===i.type){const t=null!==(e=i.customAuthURL)&&void 0!==e?e:defaultAuthURL(i.appID);return dittoAuthClientMakeAnonymousClient(r,i.appID,i.token,t)}if("onlineWithAuthentication"===i.type){const t=null!==(n=i.customAuthURL)&&void 0!==n?n:defaultAuthURL(i.appID),e=dittoAuthClientMakeLoginProvider((function(t){const e=s.deref();e?e.auth?e.auth["@ditto.authenticationExpiring"](t):a=t:Logger.warning("Internal inconsistency, LoginProvider callback fired after the corresponding Ditto instance has been deallocated.")}));return dittoAuthClientMakeWithWeb(r,i.appID,t,e)}throw new Error(`Can't create Ditto, unsupported identity type: ${i}`)})();dittoAuthClientSetValidityListener(c,(function(...t){var e;null===(e=s.deref())||void 0===e||e.authClientValidityChanged(...t)}));const d=dittoAuthClientIsWebValid(c),l=dittoAuthClientIsX509Valid(c),_=dittoAuthClientGetSiteID(c),u=dittoMake(o,c);dittoBridge.bridge(u,this),"onlineWithAuthentication"===i.type?this.auth=new OnlineAuthenticator(this.keepAlive,c,this,i.authHandler):"onlinePlayground"===i.type?this.auth=new OnlineAuthenticator(this.keepAlive,c,this,{authenticationRequired:function(t){},authenticationExpiringSoon:function(t,e){}}):(dittoAuthClientFree(c),this.auth=new NotAvailableAuthenticator(this.keepAlive));const g=this.makeDefaultTransportConfig();this.siteID=_,this.transportConfig=g.copy().freeze(),this.isX509Valid=l,this.isWebValid=d,this.sync=new Sync(this),this.sync.update({isSyncActive:!1,isX509Valid:l,isWebValid:d,identity:i,transportConfig:g}),this.isActivated=true,this.store=new Store(this),this.presence=new Presence(this),this.presenceManager=new PresenceManager(this),this.transportConditionsManager=new TransportConditionsManager(this),null!==a&&this.auth["@ditto.authenticationExpiring"](a)}setOfflineOnlyLicenseToken(t){Logger.info("Offline license token are ignored on web builds. Token validation will be skipped.")}setTransportConfig(t){this.transportConfig,this.transportConfig=t.copy().freeze();const e=this.transportConfig,n=this.identity,r=this.isWebValid,i=this.isX509Valid;this.sync.update({transportConfig:e,identity:n,isWebValid:r,isX509Valid:i,isSyncActive:this.isSyncActive})}updateTransportConfig(t){const e=this.transportConfig.copy();return t(e),this.setTransportConfig(e),this}startSync(){this.setSyncActive(!0)}stopSync(){this.setSyncActive(!1)}observePeers(t){Logger.warning("`ditto.observePeers()` is deprecated, please use `ditto.presence.observe()` instead.");const e=this.presenceManager.addObserver(t);return new Observer(this.presenceManager,e,{stopsWhenFinalized:!0})}observeTransportConditions(t){const e=this.transportConditionsManager.addObserver(t);return new Observer(this.transportConditionsManager,e,{stopsWhenFinalized:!0})}runGarbageCollection(){dittoRunGarbageCollection(dittoBridge.pointerFor(this))}disableSyncWithV2(){dittoDisableSyncWithV2(dittoBridge.pointerFor(this))}authClientValidityChanged(t,e){const n=this.transportConfig,r=this.identity,i=this.isSyncActive;this.isX509Valid,this.isWebValid,this.isX509Valid=e,this.isWebValid=t,this.auth["@ditto.authClientValidityChanged"](t,e),this.sync.update({transportConfig:n,identity:r,isWebValid:t,isX509Valid:e,isSyncActive:i})}validateIdentity(t){const e={...t};t.appName;const n=t.appID;if(!["offlinePlayground","sharedKey","manual","onlinePlayground","onlineWithAuthentication"].includes(t.type))throw new Error(`Can't create Ditto instance, unknown identity type: ${t.type}`);if(("offlinePlayground"===t.type||"sharedKey"===t.type||"onlinePlayground"===t.type||"onlineWithAuthentication"===t.type)&&void 0===n)throw new Error("Property .appID must be given for identity, but isn't.");if(void 0!==n&&"string"!=typeof n)throw new Error(`Property .appID must be be of type string, but is of type '${typeof n}': ${n}`);if(("offlinePlayground"===t.type||"sharedKey"===t.type)&&void 0!==t.siteID){const e=t.siteID;if(!("number"==typeof e||"bigint"==typeof e))throw new Error("Can't create Ditto instance, siteID must be a number or BigInt");if(e<0)throw new Error("Can't create Ditto instance, siteID must be >= 0");if(e>BigInt("0xffffffffffffffff"))throw new Error("Can't create Ditto instance, siteID must be < 2^64")}if(t.type,t.type,"onlinePlayground"===t.type){const e=t.token;if(void 0===e)throw new Error("Property .token must be given for identity but isn't. You can find the corresponding token on the Ditto Portal.");if(void 0!==e&&"string"!=typeof e)throw new Error(`Property .token of identity must be be of type string, but is of type '${typeof e}': ${e}`)}return t.type,e}setSyncActive(t){if(t&&IdentityTypesRequiringOfflineLicenseToken.includes(this.identity.type)&&!this.isActivated)throw new Error("Sync could not be started because Ditto has not yet been activated. This can be achieved with a successful call to `setOfflineOnlyLicenseToken`. If you need to obtain a license token then please visit https://portal.ditto.live.");!this.isSyncActive&&t&&this.keepAlive.retain("sync"),this.isSyncActive&&!t&&this.keepAlive.release("sync");const e=dittoBridge.pointerFor(this);this.isSyncActive=t;const n=this.isWebValid,r=this.isX509Valid,i=this.identity,o=this.transportConfig;dittoSetDeviceName(e,this.deviceName),this.sync.update({identity:i,transportConfig:o,isWebValid:n,isX509Valid:r,isSyncActive:!!t})}makeDefaultTransportConfig(){dittoBridge.pointerFor(this);const t=new TransportConfig;return bleIsAvailable()&&(t.peerToPeer.bluetoothLE.isEnabled=!0),awdlIsAvailable()&&(t.peerToPeer.awdl.isEnabled=!0),lanIsAvailable()&&(t.peerToPeer.lan.isEnabled=!0),t.freeze()}}const dittoBridge=new Bridge(Ditto,(t=>{dittoClearPresenceCallback(t),dittoFree(t)}));class Value{constructor(t,e={}){this.value=t,this.isDefault=!!e.isDefault}}export{Attachment,AttachmentFetcher,AttachmentToken,Authenticator,CBOR,Collection,CollectionsEvent,Counter,Ditto,Document,DocumentID,DocumentPath,IdentityTypesRequiringOfflineLicenseToken,KeepAlive,LiveQuery,LiveQueryEventInitial,LiveQueryEventUpdate,Logger,MutableCounter,MutableDocument,MutableDocumentPath,MutableRegister,NotAvailableAuthenticator,Observer,OnlineAuthenticator,PendingCollectionsOperation,PendingCursorOperation,PendingIDSpecificOperation,Presence,RGA,Register,SingleDocumentLiveQueryEvent,Store,Subscription,TransportConfig,UpdateResult,UpdateResultsMap,Value,addressToString,attachmentBridge,dittoBridge,documentBridge,init,mutableDocumentBridge,validateDocumentIDCBOR,validateDocumentIDValue};
|
|
2
2
|
//# sourceMappingURL=ditto.es6.js.map
|