@dittolive/ditto 1.0.14 → 1.0.17

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 CHANGED
@@ -3,10 +3,10 @@
3
3
  *Ditto is a cross platform SDK that allows mobile, web, and IoT apps to sync
4
4
  with and even without connectivity.*
5
5
 
6
- Version: **1.0.14**
6
+ Version: **1.0.17**
7
7
 
8
8
  Please visit [ditto.live](https://ditto.live) for more info as well as the
9
- [API Reference](https://software.ditto.live/js/Ditto/1.0.14/api-reference/) for this particular version.
9
+ [API Reference](https://software.ditto.live/js/Ditto/1.0.17/api-reference/) for this particular version.
10
10
 
11
11
  --------------------------------------------------------------------------------
12
12
 
package/index.html CHANGED
@@ -24,16 +24,15 @@
24
24
  const cars = ditto.store.collection('cars')
25
25
 
26
26
  // Insert an entry:
27
- const fordBlackID = new Ditto.DocumentID('ford-black-123')
28
- const fordBlack = { _id: fordBlackID, model: "Ford", color: "black" }
27
+ const fordBlack = { _id: 'ford-black-123', model: "Ford", color: "black" }
29
28
  await cars.insert(fordBlack)
30
29
 
31
30
  // Find an entry by ID:
32
- const foundFordBlack = await cars.findByID(fordBlackID)
31
+ const foundFordBlack = await cars.findByID('ford-black-123')
33
32
  console.log(foundFordBlack)
34
33
 
35
34
  // Remove an entry:
36
- await cars.findByID(fordBlackID).remove()
35
+ await cars.findByID('ford-black-123').remove()
37
36
  </pre>
38
37
  <hr>
39
38
  <p>
package/node/ditto.cjs.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});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=sharedMetaByAddrMap,this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(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 i=n.throwIfAlreadyBridged,r=this.objectFor(t);if(r&&i)throw new Error(`Can't bridge, pointer has already been bridged: ${JSON.stringify(t)}`);if(r)return r;e||(e=()=>Reflect.construct(this.type,[]));const o=e();if(!o)throw new Error(`Can't bridge, expected create() to return an object but got: ${o}`);return this.register(o,t),o}register(t,e){const n=t.constructor,i=this.type;if(n!==i)throw new Error(`Can't register, bridge is configured for type ${i.name} but passed in object is of type ${n.name}`);const r=this.pointerFor(t),o=this.metaByAddrMap[e.addr];if(r&&o)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${o.pointer}`);if(r&&!o)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no meta entry: ${t}`);if(!r&&o)throw new Error(`Internal inconsistency, trying to register an object which has a meta entry but no associated pointer: ${t}`);const s=new Meta(n,new WeakRef(t),e);t["@ditto.ptr"]=e,this.metaByAddrMap[s.pointer.addr]=s,this.finalizationRegistry.register(t,e,t)}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 i=this.pointerFor(t);if(!i)throw new Error(`Can't unregister, object that has not been registered before: ${t}`);const r=this.metaByAddrMap[i.addr];if(!r)throw new Error(`Internal inconsistency, trying to unregister an object which has an associated pointer but no meta entry: ${t}`);if(r.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: ${r}`);if(!r.object.deref())throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry whose object is undfined (garbage collected): ${r}`);if(r.object.deref()!==t)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry holding a different object: ${r}`);this.finalizationRegistry.unregister(t),delete this.metaByAddrMap[i.addr],delete t["@ditto.ptr"]}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)}}const sharedMetaByAddrMap={},isWebBuild=!1;function validateNumber(t,e={}){var n;const i=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Number validation failed:",r=!!e.integer,o=e.min,s=e.max,a=e.minX,c=e.maxX;if("number"!=typeof t)throw new Error(`${i} '${t}' is not a number.`);if(r&&Math.floor(t)!==t)throw new Error(`${i} '${t}' is not an integer.`);if(void 0!==o&&t<o)throw new Error(`${i} '${t}' must be >= ${o}.`);if(void 0!==s&&t>s)throw new Error(`${i} '${t}' must be <= ${s}.`);if(void 0!==a&&t<=a)throw new Error(`${i} '${t}' must be > ${a}.`);if(void 0!==c&&t>=c)throw new Error(`${i} '${t}' must be < ${c}.`);return t}function validateQuery(t,e={}){var n;const i=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Query validation failed,";if("string"!=typeof t)throw new Error(`${i} query is not a string: ${t}`);if(""===t)throw new Error(`${i} query is an empty string.`);const r=t.trim();if(""===r)throw new Error(`${i} query contains only whitespace characters.`);return r}class StaticTCPClient{}class WebsocketClient{}const staticTCPClientBridge=new Bridge(StaticTCPClient,staticTCPClientFreeHandle),websocketClientBridge=new Bridge(WebsocketClient,websocketClientFreeHandle),arch=process.arch,platform=process.platform,ditto=require("./ditto."+platform+"-"+arch+".node");function ble_client_free_handle(...t){return ditto.ble_client_free_handle(...t)}function ble_server_free_handle(...t){return ditto.ble_server_free_handle(...t)}function boxCBytesIntoBuffer(...t){return ditto.boxCBytesIntoBuffer(...t)}function boxCStringIntoString(...t){return ditto.boxCStringIntoString(...t)}function cStringVecToStringArray(...t){return ditto.cStringVecToStringArray(...t)}function ditto_add_internal_ble_client_transport(...t){return ditto.ditto_add_internal_ble_client_transport(...t)}function ditto_add_internal_ble_server_transport(...t){return ditto.ditto_add_internal_ble_server_transport(...t)}function ditto_add_multicast_transport(...t){return ditto.ditto_add_multicast_transport(...t)}function ditto_add_static_tcp_client(...t){return ditto.ditto_add_static_tcp_client(...t)}function ditto_add_subscription(...t){return ditto.ditto_add_subscription(...t)}function ditto_add_websocket_client(...t){return ditto.ditto_add_websocket_client(...t)}function ditto_auth_client_free(...t){return ditto.ditto_auth_client_free(...t)}function ditto_auth_client_get_site_id(...t){return ditto.ditto_auth_client_get_site_id(...t)}function ditto_auth_client_is_web_valid(...t){return ditto.ditto_auth_client_is_web_valid(...t)}function ditto_auth_client_is_x509_valid(...t){return ditto.ditto_auth_client_is_x509_valid(...t)}function ditto_auth_client_login_with_credentials(...t){return ditto.ditto_auth_client_login_with_credentials(...t)}function ditto_auth_client_login_with_token(...t){return ditto.ditto_auth_client_login_with_token(...t)}function ditto_auth_client_make_for_development(...t){return ditto.ditto_auth_client_make_for_development(...t)}function ditto_auth_client_make_login_provider(...t){return ditto.ditto_auth_client_make_login_provider(...t)}function ditto_auth_client_make_with_shared_key(...t){return ditto.ditto_auth_client_make_with_shared_key(...t)}function ditto_auth_client_make_with_static_x509(...t){return ditto.ditto_auth_client_make_with_static_x509(...t)}function ditto_auth_client_make_with_web(...t){return ditto.ditto_auth_client_make_with_web(...t)}function ditto_auth_client_set_validity_listener(...t){return ditto.ditto_auth_client_set_validity_listener(...t)}function ditto_auth_client_user_id(...t){return ditto.ditto_auth_client_user_id(...t)}function ditto_cancel_resolve_attachment(...t){return ditto.ditto_cancel_resolve_attachment(...t)}function ditto_clear_presence_callback(...t){return ditto.ditto_clear_presence_callback(...t)}function ditto_collection_evict(...t){return ditto.ditto_collection_evict(...t)}function ditto_collection_evict_query_str(...t){return ditto.ditto_collection_evict_query_str(...t)}function ditto_collection_exec_query_str(...t){return ditto.ditto_collection_exec_query_str(...t)}function ditto_collection_get(...t){return ditto.ditto_collection_get(...t)}function ditto_collection_insert(...t){return ditto.ditto_collection_insert(...t)}function ditto_collection_remove(...t){return ditto.ditto_collection_remove(...t)}function ditto_collection_remove_query_str(...t){return ditto.ditto_collection_remove_query_str(...t)}function ditto_collection_update(...t){return ditto.ditto_collection_update(...t)}function ditto_collection_update_multiple(...t){return ditto.ditto_collection_update_multiple(...t)}function ditto_document_cbor(...t){return ditto.ditto_document_cbor(...t)}function ditto_document_free(...t){return ditto.ditto_document_free(...t)}function ditto_document_get_cbor(...t){return ditto.ditto_document_get_cbor(...t)}function ditto_document_id(...t){return ditto.ditto_document_id(...t)}function ditto_document_id_query_compatible(...t){return ditto.ditto_document_id_query_compatible(...t)}function ditto_document_increment_counter(...t){return ditto.ditto_document_increment_counter(...t)}function ditto_document_insert_cbor(...t){return ditto.ditto_document_insert_cbor(...t)}function ditto_document_new_cbor(...t){return ditto.ditto_document_new_cbor(...t)}function ditto_document_new_cbor_default_data(...t){return ditto.ditto_document_new_cbor_default_data(...t)}function ditto_document_pop_cbor(...t){return ditto.ditto_document_pop_cbor(...t)}function ditto_document_push_cbor(...t){return ditto.ditto_document_push_cbor(...t)}function ditto_document_remove(...t){return ditto.ditto_document_remove(...t)}function ditto_document_replace_with_counter(...t){return ditto.ditto_document_replace_with_counter(...t)}function ditto_document_replace_with_counter_with_timestamp(...t){return ditto.ditto_document_replace_with_counter_with_timestamp(...t)}function ditto_document_set_cbor(...t){return ditto.ditto_document_set_cbor(...t)}function ditto_document_set_cbor_with_timestamp(...t){return ditto.ditto_document_set_cbor_with_timestamp(...t)}function ditto_documents_hash(...t){return ditto.ditto_documents_hash(...t)}function ditto_documents_hash_mnemonic(...t){return ditto.ditto_documents_hash_mnemonic(...t)}function ditto_drop(...t){return ditto.ditto_drop(...t)}function ditto_error_message(...t){return ditto.ditto_error_message(...t)}function ditto_free_attachment_handle(...t){return ditto.ditto_free_attachment_handle(...t)}function ditto_get_collection_names(...t){return ditto.ditto_get_collection_names(...t)}function ditto_get_complete_attachment_path(...t){return ditto.ditto_get_complete_attachment_path(...t)}function ditto_get_sdk_version(...t){return ditto.ditto_get_sdk_version(...t)}function ditto_init_sdk_version(...t){return ditto.ditto_init_sdk_version(...t)}function ditto_live_query_register_str(...t){return ditto.ditto_live_query_register_str(...t)}function ditto_live_query_signal_available_next(...t){return ditto.ditto_live_query_signal_available_next(...t)}function ditto_live_query_start(...t){return ditto.ditto_live_query_start(...t)}function ditto_live_query_stop(...t){return ditto.ditto_live_query_stop(...t)}function ditto_live_query_webhook_register_str(...t){return ditto.ditto_live_query_webhook_register_str(...t)}function ditto_log(...t){return ditto.ditto_log(...t)}function ditto_logger_emoji_headings_enabled(...t){return ditto.ditto_logger_emoji_headings_enabled(...t)}function ditto_logger_emoji_headings_enabled_get(...t){return ditto.ditto_logger_emoji_headings_enabled_get(...t)}function ditto_logger_enabled(...t){return ditto.ditto_logger_enabled(...t)}function ditto_logger_enabled_get(...t){return ditto.ditto_logger_enabled_get(...t)}function ditto_logger_init(...t){return ditto.ditto_logger_init(...t)}function ditto_logger_minimum_log_level(...t){return ditto.ditto_logger_minimum_log_level(...t)}function ditto_logger_minimum_log_level_get(...t){return ditto.ditto_logger_minimum_log_level_get(...t)}function ditto_logger_set_custom_log_cb(...t){return ditto.ditto_logger_set_custom_log_cb(...t)}function ditto_logger_set_log_file(...t){return ditto.ditto_logger_set_log_file(...t)}function ditto_make(...t){return ditto.ditto_make(...t)}function ditto_new_attachment_from_bytes(...t){return ditto.ditto_new_attachment_from_bytes(...t)}function ditto_new_attachment_from_file(...t){return ditto.ditto_new_attachment_from_file(...t)}function ditto_presence_v1(...t){return ditto.ditto_presence_v1(...t)}function ditto_read_transaction(...t){return ditto.ditto_read_transaction(...t)}function ditto_read_transaction_free(...t){return ditto.ditto_read_transaction_free(...t)}function ditto_register_presence_v1_callback(...t){return ditto.ditto_register_presence_v1_callback(...t)}function ditto_register_transport_condition_changed_callback(...t){return ditto.ditto_register_transport_condition_changed_callback(...t)}function ditto_remove_multicast_transport(...t){return ditto.ditto_remove_multicast_transport(...t)}function ditto_remove_subscription(...t){return ditto.ditto_remove_subscription(...t)}function ditto_resolve_attachment(...t){return ditto.ditto_resolve_attachment(...t)}function ditto_run_garbage_collection(...t){return ditto.ditto_run_garbage_collection(...t)}function ditto_set_device_name(...t){return ditto.ditto_set_device_name(...t)}function ditto_set_sync_group(...t){return ditto.ditto_set_sync_group(...t)}function ditto_start_http_server(...t){return ditto.ditto_start_http_server(...t)}function ditto_start_tcp_server(...t){return ditto.ditto_start_tcp_server(...t)}function ditto_stop_http_server(...t){return ditto.ditto_stop_http_server(...t)}function ditto_stop_tcp_server(...t){return ditto.ditto_stop_tcp_server(...t)}function ditto_write_transaction(...t){return ditto.ditto_write_transaction(...t)}function ditto_write_transaction_commit(...t){return ditto.ditto_write_transaction_commit(...t)}function jsDocsToCDocs(...t){return ditto.jsDocsToCDocs(...t)}function refCStringToString(...t){return ditto.refCStringToString(...t)}function static_tcp_client_free_handle(...t){return ditto.static_tcp_client_free_handle(...t)}function uninitialized_ditto_make(...t){return ditto.uninitialized_ditto_make(...t)}function verify_license(...t){return ditto.verify_license(...t)}function websocket_client_free_handle(...t){return ditto.websocket_client_free_handle(...t)}function withOutBoxCBytes(...t){return ditto.withOutBoxCBytes(...t)}function withOutPtr$1(...t){return ditto.withOutPtr(...t)}function documentNewCBORDefaultData(t,e){ensureInitialized();const{status_code:n,document:i}=ditto_document_new_cbor_default_data(t,e);if(n===NOT_FOUND_ERROR_CODE)return null;if(0!==n)throw new Error(errorMessage()||`ditto_document_new_cbor_default_data() failed with error code: ${n}`);return i}function documentNewCBOR(t,e,n){ensureInitialized();const i=Number(n),{status_code:r,document:o}=ditto_document_new_cbor(t,e,i);if(r===NOT_FOUND_ERROR_CODE)return null;if(0!==r)throw new Error(errorMessage()||`ditto_document_new_cbor() failed with error code: ${r}`);return o}function documentSetCBORWithTimestamp(t,e,n,i,r){ensureInitialized();const o=ditto_document_set_cbor_with_timestamp(t,bytesFromString(e),n,i,r);if(0!==o)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${o}`)}function documentSetCBOR(t,e,n,i){ensureInitialized();const r=ditto_document_set_cbor(t,bytesFromString(e),n,i);if(0!==r)throw new Error(errorMessage()||`ditto_document_set_cbor() failed with error code: ${r}`)}function documentID(t){ensureInitialized();return boxCBytesIntoBuffer(ditto_document_id(t))}function documentCBOR(t){ensureInitialized();return boxCBytesIntoBuffer(ditto_document_cbor(t))}function documentGetCBOR(t,e){ensureInitialized();return boxCBytesIntoBuffer(ditto_document_get_cbor(t,bytesFromString(e)),e)}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 documentReplaceWithCounter(t,e){ensureInitialized();const n=ditto_document_replace_with_counter(t,bytesFromString(e)),i=errorMessage();if("InvalidPointer"===i)throw new Error(`Can't replace with counter, property does not exist at path or path is not valid: ${e}`);if(0!==n)throw new Error(i||`ditto_document_replace_with_counter() failed with error code: ${n}`)}function documentReplaceWithCounterWithTimestamp(t,e,n){ensureInitialized();const i=ditto_document_replace_with_counter_with_timestamp(t,bytesFromString(e),n),r=errorMessage();if("InvalidPointer"===r)throw new Error(`Can't replace with counter, property does not exist at path or path is not valid: ${e}`);if(0!==i)throw new Error(r||`ditto_document_replace_with_counter_with_timestamp() failed with error code: ${i}`)}function documentIncrementCounter(t,e,n){ensureInitialized();const i=ditto_document_increment_counter(t,bytesFromString(e),n);if(0!==i)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${i}`)}function documentPushCBOR(t,e,n){ensureInitialized();const i=ditto_document_push_cbor(t,bytesFromString(e),n);if(0!==i)throw new Error(errorMessage()||`ditto_document_push_cbor() failed with error code: ${i}`)}function documentPopCBOR(t,e){ensureInitialized();const n=bytesFromString(e);return boxCBytesIntoBuffer(withOutBoxCBytes((e=>{const i=ditto_document_pop_cbor(t,n,e);if(0!==i)throw new Error(errorMessage()||`ditto_document_pop_cbor() failed with error code: ${i}`);return e})))}function documentInsertCBOR(t,e,n){ensureInitialized();const i=ditto_document_insert_cbor(t,bytesFromString(e),n);if(0!==i)throw new Error(errorMessage()||`ditto_document_insert_cbor() failed with error code: ${i}`)}function documentFree(t){ensureInitialized(),ditto_document_free(t)}function documentIDQueryCompatible(t,e){ensureInitialized();return boxCStringIntoString(ditto_document_id_query_compatible(t,e))}function collectionGet(t,e,n,i){ensureInitialized();const r=bytesFromString(e),{status_code:o,document:s}=ditto_collection_get(t,r,n,i);if(o===NOT_FOUND_ERROR_CODE)return null;if(0!==o)throw new Error(errorMessage()||`ditto_collection_get() failed with error code: ${o}`);return s}function collectionInsert(t,e,n,i,r){ensureInitialized();const o=bytesFromString(e);let s;switch(r){case"merge":s="Merge";break;case"overwrite":s="Overwrite";break;case"insertIfAbsent":s="InsertIfAbsent";break;case"insertDefaultIfAbsent":s="InsertDefaultIfAbsent";break;default:throw new Error("Invalid write strategy provided")}const{status_code:a,id:c}=ditto_collection_insert(t,o,n,i,s);if(0!==a)throw new Error(errorMessage()||`ditto_collection_insert() failed with error code: ${a}`);return boxCBytesIntoBuffer(c)}function collectionRemove(t,e,n,i){ensureInitialized();const r=bytesFromString(e),{status_code:o,bool_value:s}=ditto_collection_remove(t,r,n,i);if(0!==o)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${o}`);return s}function collectionEvict(t,e,n,i){ensureInitialized();const r=bytesFromString(e),{status_code:o,bool_value:s}=ditto_collection_evict(t,r,n,i);if(0!==o)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${o}`);return s}function collectionUpdate(t,e,n,i){ensureInitialized();const r=ditto_collection_update(t,bytesFromString(e),n,i);if(0!==r)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${r}`)}function collectionUpdateMultiple(t,e,n,i){ensureInitialized();const r=ditto_collection_update_multiple(t,bytesFromString(e),n,jsDocsToCDocs(i));if(0!==r)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${r}`)}function collectionExecQueryStr(t,e,n,i,r,o,s,a){ensureInitialized();return ditto_collection_exec_query_str(t,bytesFromString(e),n,bytesFromString(i),r,o,s,a)}function collectionRemoveQueryStr(t,e,n,i,r,o,s,a){ensureInitialized();return ditto_collection_remove_query_str(t,bytesFromString(e),n,bytesFromString(i),r,o,s,a)}function collectionEvictQueryStr(t,e,n,i,r,o,s,a){ensureInitialized();return ditto_collection_evict_query_str(t,bytesFromString(e),n,bytesFromString(i),r,o,s,a)}function addSubscription(t,e,n,i){ensureInitialized();return ditto_add_subscription(t,bytesFromString(e),bytesFromString(n),i)}function removeSubscription(t,e,n,i){ensureInitialized();return ditto_remove_subscription(t,bytesFromString(e),bytesFromString(n),i)}function liveQueryRegister(t,e,n,i,r,o,s,a,c,d){ensureInitialized();const u=bytesFromString(e),l=bytesFromString(n),{status_code:h,i64:p}=ditto_live_query_register_str(t,u,l,i,r,o,s,a,wrapBackgroundCbForFFI(d,c));if(0!==h)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${h}`);return p}function liveQueryStart(t,e){ensureInitialized();const n=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)}function liveQueryWebhookRegister(t,e,n,i,r,o,s){ensureInitialized();const a=bytesFromString(e),c=bytesFromString(n),d=bytesFromString(s),{status_code:u,id:l}=ditto_live_query_webhook_register_str(t,a,c,i,r,o,d);if(0!==u)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${u}`);return boxCBytesIntoBuffer(l)}function readTransaction(t){ensureInitialized();const{status_code:e,txn:n}=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)}function writeTransaction(t){ensureInitialized();const{status_code:e,txn:n}=ditto_write_transaction(t);if(0!==e)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${e}`);return n}function writeTransactionCommit(t,e){ensureInitialized();const n=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 ditto_add_static_tcp_client(t,bytesFromString(e))}function staticTCPClientFreeHandle(t){static_tcp_client_free_handle(t)}function addWebsocketClient(t,e){ensureInitialized();return ditto_add_websocket_client(t,bytesFromString(e))}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 i=refCStringToString(n);t(e,i)}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 dittoAuthClientMakeWithWeb(t,e,n,i){ensureInitialized();const r=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(n),{status_code:a,auth_client:c}=ditto_auth_client_make_with_web(r,o,s,i);if(0!==a)throw new Error(errorMessage()||`ditto_auth_client_make_with_web() failed with error code: ${a}`);return c}function dittoAuthClientMakeForDevelopment(t,e,n){ensureInitialized();const i=bytesFromString(t),r=bytesFromString(e),o=Number(n),{status_code:s,auth_client:a}=ditto_auth_client_make_for_development(i,r,o);if(0!==s)throw new Error(errorMessage()||`ditto_auth_client_make_for_development() failed with error code: ${s}`);return a}function dittoAuthClientMakeWithSharedKey(t,e,n,i){ensureInitialized();const r=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(n),a=Number(i),{status_code:c,auth_client:d}=ditto_auth_client_make_with_shared_key(r,o,s,a);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:i}=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 i}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 i=bytesFromString(e),r=bytesFromString(n),o=await ditto_auth_client_login_with_token(t,i,r);if(0!==o)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${o}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(t,e,n,i){ensureInitialized();const r=bytesFromString(e),o=bytesFromString(n),s=bytesFromString(i),a=await ditto_auth_client_login_with_credentials(t,r,o,s);if(0!==a)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${a}).`)}function uninitializedDittoMake(t){ensureInitialized();return uninitialized_ditto_make(bytesFromString(t))}function dittoMake(t,e){return ensureInitialized(),ditto_make(t,e)}function dittoGetCollectionNames(t){ensureInitialized();const e=ditto_get_collection_names(t),n=e.status_code,i=e.names;if(0!==n)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${n}`);return cStringVecToStringArray(i)}function dittoDrop(t){return ensureInitialized(),ditto_drop(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)}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){return ensureInitialized(),ditto_set_device_name(t,bytesFromString(e))}function dittoSetSyncGroup(t,e){return ensureInitialized(),ditto_set_sync_group(t,e)}function dittoNewAttachmentFromFile(t,e,n){ensureInitialized();const i={},r=ditto_new_attachment_from_file(t,bytesFromString(e),n,i);if(0!==r)throw new Error(errorMessage()||`ditto_new_attachment_from_file() failed with error code: ${r}`);return i}function dittoNewAttachmentFromBytes(t,e){ensureInitialized();const n={},i=ditto_new_attachment_from_bytes(t,e,n);if(0!==i)throw new Error(errorMessage()||`ditto_new_attachment_from_bytes() failed with error code: ${i}`);return n}function dittoResolveAttachment(t,e,n,i){ensureInitialized();const{onComplete:r,onProgress:o,onDelete:s}=n,{status_code:a,cancel_token:c}=ditto_resolve_attachment(t,e,wrapBackgroundCbForFFI(i,r),wrapBackgroundCbForFFI(i,o),wrapBackgroundCbForFFI(i,s));if(0!==a)throw new Error(errorMessage()||`ditto_resolve_attachment() failed with error code: ${a}`);return c}function dittoCancelResolveAttachment(t,e,n){ensureInitialized();const i=ditto_cancel_resolve_attachment(t,e,n);if(0!==i)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${i}`)}function freeAttachmentHandle(t){ensureInitialized(),ditto_free_attachment_handle(t)}function dittoGetCompleteAttachmentPath(t,e){ensureInitialized();return refCStringToString(ditto_get_complete_attachment_path(t,e))}function dittoGetSDKVersion(t){ensureInitialized();return boxCStringIntoString(ditto_get_sdk_version(t))}function dittoPresenceV1(t){ensureInitialized();return boxCStringIntoString(ditto_presence_v1(t))}function dittoStartTCPServer(t,e){ensureInitialized();return ditto_start_tcp_server(t,bytesFromString(e))}function dittoStopTCPServer(t){return ensureInitialized(),ditto_stop_tcp_server(t)}function dittoAddMulticastTransport(t){return ensureInitialized(),ditto_add_multicast_transport(t)}function dittoRemoveMulticastTransport(t){return ensureInitialized(),ditto_remove_multicast_transport(t)}function dittoStartHTTPServer(t,e,n,i,r,o){ensureInitialized();return ditto_start_http_server(t,bytesFromString(e),bytesFromString(n),i,bytesFromString(r),bytesFromString(o))}function dittoStopHTTPServer(t){return ensureInitialized(),ditto_stop_http_server(t)}function dittoRunGarbageCollection(t){return ensureInitialized(),ditto_run_garbage_collection(t)}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,((t,n)=>e(1===t,1===n))))}let withOutPtr,isInitialized=!1;function initSDKVersion(t,e,n){ensureInitialized(),bytesFromString(t),bytesFromString(e);const i=ditto_init_sdk_version(t,e,bytesFromString(n));if(void 0!==i&&0!==i)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${i}`)}function verifyLicense(t){ensureInitialized();const e=bytesFromString(t);let n;const i=boxCStringIntoString(withOutPtr("char *",(t=>(n=verify_license(e,t),t))));return{result:n,errorMessage:i}}isInitialized=!0,withOutPtr=wrapFFIOutFunction(withOutPtr$1);const NOT_FOUND_ERROR_CODE=-30798;function wrapBackgroundCbForFFI(t,e){return void 0===t&&(t=console.error),(n,...i)=>{let r;try{r=e(...i)}catch(e){try{t(e)}catch(t){console.error(`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${t}`)}}return n(r)}}function wrapFFIOutFunction(t){return function(...e){let n,i,r=!1;const o=e[e.length-1],s=e.splice(0,e.length-1),a=t(...s,(t=>{try{i=o(t),r=i===t}catch(t){n=t}}));if(n)throw n;return r?a:i}}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)throw new Error("Ditto needs to be initialized before using any of its API, please make sure to call `await init()` first.")}let transports=null;if("undefined"!=typeof process&&"undefined"!=typeof require){const t=process.arch,e=process.platform;try{transports=require(`./transports.${e}-${t}.node`)}catch(t){}}function bleIsAvailable(t){return null!==transports&&transports.bleIsAvailable(t)}function bleCreate(t){if(null!==transports)return transports.bleCreate(t);throw new Error("Can't create BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}function bleDestroy(t){if(null!==transports)return transports.bleDestroy(t);throw new Error("Can't destroy BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}function lanIsAvailable(t){return null!==transports&&transports.lanIsAvailable(t)}function lanCreate(t){if(null!==transports)return transports.lanCreate(t);throw new Error("Can't create LAN handle, P2P LAN transport is not supported on this platform.")}function lanDestroy(t){if(null!==transports)return transports.lanDestroy(t);throw new Error("Can't destroy LAN handle, P2P LAN transport is not supported on this platform.")}function awdlIsAvailable(t){return null!==transports&&transports.awdlIsAvailable(t)}function awdlCreate(t){if(null!==transports)return transports.awdlCreate(t);throw new Error("Can't create AWDL handle, P2P AWDL transport is not supported on this platform.")}function awdlDestroy(t){if(null!==transports)return transports.awdlDestroy(t);throw new Error("Can't destroy AWDL handle, P2P AWDL transport is not supported on this platform.")}const fullBuildVersionString="1.0.14";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:"[::]",port:4040},http:{isEnabled:!1,interfaceIP:"[::]",port:80,websocketSync:!0}},this.global={syncGroup: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}static areListenTCPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port}static areListenHTTPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port&&t.staticContentPath===e.staticContentPath&&t.websocketSync===e.websocketSync&&t.tlsKeyPath===e.tlsKeyPath&&t.tlsCertificatePath===e.tlsCertificatePath}}class OnlineWithAuthenticationAuthenticator{constructor(t){this.loginSupported=!0,this.authClientPointer=t,OnlineWithAuthenticationAuthenticator.finalizationRegistry.register(this,t)}async loginWithToken(t,e){await dittoAuthClientLoginWithToken(this.authClientPointer,t,e)}async loginWithUsernameAndPassword(t,e,n){await dittoAuthClientLoginWithUsernameAndPassword(this.authClientPointer,t,e,n)}isAuthenticated(){return dittoAuthClientIsWebValid(this.authClientPointer)}static finalize(t){dittoAuthClientFree(t)}get userID(){return dittoAuthClientUserID(this.authClientPointer)}}OnlineWithAuthenticationAuthenticator.finalizationRegistry=new FinalizationRegistry(OnlineWithAuthenticationAuthenticator.finalize);class NotAvailableAuthenticator{constructor(){this.loginSupported=!1}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.")}isAuthenticated(){return!1}get userID(){return null}}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}function decode(t,e,n){let i=new DataView(t),r=new Uint8Array(t),o=0,tagValueFunction=function(t,e){return t},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,r[o])}function readUint16(){return commitRead(2,i.getUint16(o))}function readUint32(){return commitRead(4,i.getUint32(o))}function readBreak(){return 255===r[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 s=function decodeItem(){let t,e,n=readUint8(),r=n>>5,s=31&n;if(7===r)switch(s){case 25:return function readFloat16(){let t=new ArrayBuffer(4),e=new DataView(t),n=readUint16(),i=32768&n,r=31744&n,o=1023&n;if(31744===r)r=261120;else if(0!==r)r+=114688;else if(0!==o)return(i?-1:1)*o*POW_2_24;return e.setUint32(0,i<<16|r<<13|o<<13),e.getFloat32(0)}();case 26:return function readFloat32(){return commitRead(4,i.getFloat32(o))}();case 27:return function readFloat64(){return commitRead(8,i.getFloat64(o))}()}if(e=readLength(s),e<0&&(r<2||6<r))throw new Error("Invalid length");switch(r){case 0:return e;case 1:return-1-e;case 2:if(e<0){let n=[],i=0;for(;(e=readIndefiniteStringLength(r))>=0;)i+=e,n.push(readArrayBuffer(e));let o=new Uint8Array(i),s=0;for(t=0;t<n.length;++t)o.set(n[t],s),s+=n[t].length;return o}return readArrayBuffer(e);case 3:let n=[];if(e<0)for(;(e=readIndefiniteStringLength(r))>=0;)appendUtf16Data(n,e);else appendUtf16Data(n,e);let i="";for(t=0;t<n.length;t+=8192)i+=String.fromCharCode.apply(null,n.slice(t,t+8192));return i;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 s={};for(t=0;t<e||e<0&&!readBreak();++t){s[decodeItem()]=decodeItem()}return s;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 s}function encode(t){let e,n=new ArrayBuffer(256),i=new DataView(n),r=new Uint8Array(n),o=0;function prepareWrite(t){let s=n.byteLength,a=o+t;for(;s<a;)s<<=1;if(s!==n.byteLength){let t=i;n=new ArrayBuffer(s),i=new DataView(n),r=new Uint8Array(n);let e=o+3>>2;for(let n=0;n<e;++n)i.setUint32(n<<2,t.getUint32(n<<2))}return e=t,i}function commitWrite(...t){o+=e}function writeUint8(t){commitWrite(prepareWrite(1).setUint8(o,t))}function writeUint8Array(t){prepareWrite(t.length),r.set(t,o),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),function writeUint16(t){commitWrite(prepareWrite(2).setUint16(o,t))}(e)):e<4294967296?(writeUint8(t<<5|26),function writeUint32(t){commitWrite(prepareWrite(4).setUint32(o,t))}(e)):(writeUint8(t<<5|27),function writeUint64(t){let e=t%POW_2_32,n=(t-e)/POW_2_32,i=prepareWrite(8);i.setUint32(o,n),i.setUint32(o+4,e),commitWrite()}(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 i=t.charCodeAt(e);i<128?n.push(i):i<2048?(n.push(192|i>>6),n.push(128|63&i)):i<55296||i>=57344?(n.push(224|i>>12),n.push(128|i>>6&63),n.push(128|63&i)):(i=(1023&i)<<10,i|=1023&t.charCodeAt(++e),i+=65536,n.push(240|i>>18),n.push(128|i>>12&63),n.push(128|i>>6&63),n.push(128|63&i))}return writeTypeAndLength(3,n.length),writeUint8Array(n);default:let i,r;if(Array.isArray(t))for(i=t.length,writeTypeAndLength(4,i),e=0;e<i;e+=1)encodeItem(t[e]);else if(t instanceof Uint8Array)writeTypeAndLength(2,t.length),writeUint8Array(t);else if(ArrayBuffer.isView(t))r=new Uint8Array(t.buffer),writeTypeAndLength(2,r.length),writeUint8Array(r);else if(t instanceof ArrayBuffer||"function"==typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer)r=new Uint8Array(t),writeTypeAndLength(2,r.length),writeUint8Array(r);else{let n=Object.keys(t);for(i=n.length,writeTypeAndLength(5,i),e=0;e<i;e+=1){let i=n[e];encodeItem(i),encodeItem(t[i])}}}}(t),"slice"in n)return n.slice(0,o);let s=new ArrayBuffer(o),a=new DataView(s);for(let t=0;t<o;++t)a.setUint8(t,i.getUint8(t));return s}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{constructor(t,e=!1){if(e)this["@ditto.cbor"]=t;else{const e=CBOR.encode(t);this["@ditto.cbor"]=e}}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"],"WithQuotes")}get value(){let t=this["@ditto.value"];return void 0===t&&(t=CBOR.decode(this["@ditto.cbor"]),this["@ditto.value"]=t),t}}class Attachment{constructor(t,e){this.ditto=t,this.token=e}get metadata(){return this.token.metadata}getData(){{const t=dittoGetCompleteAttachmentPath(dittoBridge.pointerFor(this.ditto),attachmentBridge.pointerFor(this));return require("fs/promises").readFile(t)}}copyToPath(t){{const e=dittoGetCompleteAttachmentPath(dittoBridge.pointerFor(this.ditto),attachmentBridge.pointerFor(this)),n=require("fs/promises");return n.copyFile(e,t,n.COPYFILE_EXCL)}}}const attachmentBridge=new Bridge(Attachment,freeAttachmentHandle);class AttachmentToken{constructor(t){if("ditto_attachment"!==t._type)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 i=t._meta;if("object"!=typeof i)throw new Error("Invalid attachment token meta");this.id=e,this.len=n,this.metadata=i}}class AttachmentFetcher{constructor(t,e,n){this.ditto=t,this.token=e,this.eventHandler=n||null,this.cancelToken=null;const i=n||function(){};this.attachment=new Promise(((n,r)=>{const o=dittoBridge.pointerFor(t);this.cancelToken=dittoResolveAttachment(o,e.id,{onComplete:t=>{this.eventHandler=null,this.cancelToken=null;const e=new Attachment(this.ditto,this.token);attachmentBridge.bridge(t,(()=>e),{throwIfAlreadyBridged:!0}),i({type:"Completed",attachment:e}),n(e)},onProgress:(t,e)=>{i({type:"Progress",totalBytes:e,downloadedBytes:t})},onDelete:()=>{this.eventHandler=null,this.cancelToken=null,i({type:"Deleted"}),n(null)}},(t=>{this.eventHandler=null,this.cancelToken=null,r(t)}))}))}stop(){const t=this.cancelToken;if(t){this.cancelToken=null;dittoCancelResolveAttachment(dittoBridge.pointerFor(this.ditto),this.token.id,t)}}then(t,e){return this.attachment.then(t,e)}}function __log(t,e){Logger.warning("Function __log() is deprecated, use Logger.log() & friends instead."),Logger.log(t,e)}class Logger{constructor(){throw new Error("Logger can't be instantiated, use it's static properties & methods directly instead.")}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)}setLogFile(t){throw new Error("Deprecated, use Logger's static properties and methods directly instead.")}setLogFileURL(t){throw new Error("Deprecated, use Logger's static properties and methods directly instead.")}async setCustomLogCallback(t){throw new Error("Deprecated, use Logger's static properties and methods directly instead.")}static shared(){return Logger.warning("Logger.shared() is deprecated, use Logger's static properties & methods directly instead."),this}}class UpdateResult{constructor(t,e,n,i,r){this.type=t,this.docID=e,this.path=n,void 0!==i&&(this.value=i),void 0!==r&&(this.amount=r)}static set(t,e,n){return new UpdateResult("set",t,e,n,void 0)}static replacedWithCounter(t,e){return new UpdateResult("replacedWithCounter",t,e,void 0,void 0)}static incremented(t,e,n){return new UpdateResult("incremented",t,e,void 0,n)}static inserted(t,e,n){return new UpdateResult("inserted",t,e,n,void 0)}static removed(t,e){return new UpdateResult("removed",t,e,void 0,void 0)}static pushed(t,e,n){return new UpdateResult("pushed",t,e,n,void 0)}static popped(t,e,n){return new UpdateResult("popped",t,e,n,void 0)}}class Counter{constructor(t,e){this.value=t,this.isDefault=!!e}increment(t){if(!this.mutDoc)throw new Error("Can't increment counter, only possible within the closure of a collection's update() method.");this.mutDoc.at(this.path,!0).increment(t),this.value+=t}static __newInternal(t,e,n){const i=new Counter(n);return i.mutDoc=t,i.path=e,i}}class Value{constructor(t,e={}){this.value=t,this.isDefault=!!e.isDefault}}const validPathIdentifier=/^[A-Za-z0-9_]+$/,validPathFirstCharIdentifier=/^[A-Za-z_]/;function validateKeyPathComponent(t,e=!1){if(Number.isFinite(+t))return`[${t}]`;if("string"==typeof t)return validPathFirstCharIdentifier.test(t)&&validPathIdentifier.test(t)?e?t:`.${t}`:`['${t}']`;throw new Error(`Invalid path component: ${t}.`)}const arrayOps=["push","pop","splice","unshift","shift"];function set(t,e,n){let i=n,r=!1;const o=n instanceof Counter,s=n instanceof Value;(o||s)&&(i=n.value,r=!!n.isDefault);const a=i instanceof Counter,c=i instanceof Value;if(o&&a)throw`Can't set counter at path '${e}', nesting of Counter within Counter is forbidden.`;if(o&&c)throw`Can't set counter at path '${e}', nesting of Value within Counter is forbidden.`;if(s&&a)throw`Can't set value at path '${e}', nesting of Counter within Value is forbidden.`;if(s&&c)throw`Can't set value at path '${e}', nesting of Value within Value is forbidden.`;MutableDocument.pathAt(t,e,!0).set(i,r),o&&MutableDocument.pathAt(t,e,!0).replaceWithCounter(r)}function proxyFactory(t,e,n){return new Proxy(t,{get(t,i,r){if("symbol"==typeof i)return t[i];if("object"==typeof t&&""===n){if("_value"===i)return MutableDocument.value(r);if("_valueAt"===i)return t=>MutableDocument.valueAt(r,t);if("_pathAt"===i)return t=>MutableDocument.pathAt(r,t);if("string"==typeof i&&i.startsWith("@ditto."))return e[i]}if("_replaceWithCounterAt"===i)return t=>{const i=validateKeyPathComponent(t);return MutableDocument.replaceWithCounterAt(e,`${n}${i}`)};if("_incrementCounterAt"===i)return(t,i)=>{const r=validateKeyPathComponent(t);return MutableDocument.incrementCounterAt(e,`${n}${r}`,i)};if(t instanceof Counter)return t[i];const o=t[i],s=typeof o;if("undefined"!==s){if("function"===s&&arrayOps.includes(i)&&(t.__arrayOp=i),"object"!==s)return o;const r=validateKeyPathComponent(i,""===n);return proxyFactory(o,e,`${n}${r}`)}return o},set(t,i,r){const o=validateKeyPathComponent(i,""===n),s=`${n}${o}`;if("object"==typeof t&&""===n&&"string"==typeof i&&i.startsWith("@ditto."))return e[i]=r,!0;if("object"==typeof t&&Array.isArray(t)){if("length"===i){if(r===t.length-1){const i=t.__arrayOp;i&&"pop"===i&&(MutableDocument.pathAt(e,n,!0).pop(),t.pop())}return t[i]=r,delete t.__arrayOp,!0}const o=+i;if(isNaN(o))throw new Error(`Attempting to access a non-index property of an array. Property: ${i}.`);const a=t.__arrayOp;if(o===t.length&&a&&"push"===a)MutableDocument.pathAt(e,n,!0).push(r),t.push(r);else if(a){let n=t.__cachedSetOperations||[];if(o>t.length)n.push({index:o,value:r,path:s}),t.__cachedSetOperations=n;else{set(e,s,r),t[o]=r;let i=n.length;for(;i>0;){const r=n[i-1];r.index===t.length&&(set(e,r.path,r.value),t[r.index]=r.value,n.splice(i-1,1)),i--}}}else{if(!(o<=t.length))throw new Error(`Attempting to set an array index of ${o} but the array only has ${t.length} elements`);set(e,s,r),t[o]=r}}else{if(t instanceof Counter&&"value"===i);else{const n=+i;if(Number.isFinite(n))throw new Error(`Attempting to access an array index property (${n}) of an object: ${JSON.stringify(t)}.`);set(e,s,r)}t[i]=r}return!0},deleteProperty(t,i){if(i in t){const r=t.__arrayOp;if(r&&"pop"===r)return!0;const o=validateKeyPathComponent(i,""===n),s=`${n}${o}`;return MutableDocument.pathAt(e,s,!0).remove(),delete t[i],!0}return!1}})}function augmentJSONValue(t,e,n){let i={};if(""===n){for(const[n,r]of Object.entries(t))i[n]=augmentJSONValue(r,e,n);return i}if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,i)=>augmentJSONValue(t,e,`${n}[${i}]`)));if("ditto_counter"===t._type)return Counter.__newInternal(e,n,t._value);if("ditto_attachment"===t._type)return new AttachmentToken(t);for(const[i,r]of Object.entries(t))t[i]=augmentJSONValue(r,e,`${n}['${i}']`);return t}return t}function desugarJSObject(t,e){let n={};if(e){for(const[e,i]of Object.entries(t))n[e]=desugarJSObject(i,!1);return n}if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,e)=>desugarJSObject(t,!1)));if(t instanceof Counter)return t.value;if(t instanceof Attachment)return{_type:"ditto_attachment",_id:t.token.id,_len:t.token.len,_meta:t.token.metadata};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 i=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 r=this.withLeadingDot(t);if(!validKeyPathRegExp.test(r))throw new Error(`Key-path is not valid: ${t}`);return i?t:r}static evaluate(t,e,n={}){var i;const r=null!==(i=n.stopAtLastContainer)&&void 0!==i&&i,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:i,remainingPath:s}=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],i=e[1];return{nextPathComponentRaw:n,nextPathComponent:i,remainingPath:t.slice(i.length+1)}}const n=t.match(subscriptIndexRegExp);if(null!==n){const e=n[0],i=n[1];return{nextPathComponentRaw:e,nextPathComponent:parseInt(i),remainingPath:t.slice(i.length+2)}}const i=t.match(subscriptSingleQuoteKeyRegExp);if(null!==i){const e=i[0],n=i[1];return{nextPathComponentRaw:e,nextPathComponent:n,remainingPath:t.slice(n.length+4)}}const r=t.match(subscriptDoubleQuoteKeyRegExp);if(null!==r){const e=r[0],n=r[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=i,o.remainingPath=s,null===o.coveredPath||"number"==typeof n?o.coveredPath=n:o.coveredPath+=n,""===s&&r?(o.value=t,o):recurse(t[i],s)}(e,this.withLeadingDot(t))}constructor(){}}class DocumentPath{constructor(t,e){this.document=t,this.path=e}at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e);return new DocumentPath(this.document,`${this.path}${n}`)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"DocumentPath.atIndex() validation failed index:"});return new DocumentPath(this.document,`${this.path}[${e.toString()}]`)}throw new Error(`Can't return document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}value(){return Document.valueAt(this.document,this.path)}atIndex(t){return Logger.warning("Method DocumentPath.atIndex() is deprecated, use DocumentPath.at() instead."),this.at(t)}}class MutableDocumentPath{constructor(t,e){this.mutableDocument=t,this.path=e}at(t){if("string"==typeof t){const e=t;return KeyPath.validate(e),new MutableDocumentPath(this.mutableDocument,`${this.path}.${e}`)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"MutableDocumentPath.atIndex() validation failed index:"});return new MutableDocumentPath(this.mutableDocument,`${this.path}[${e.toString()}]`)}throw new Error(`Can't return mutable document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}value(){return MutableDocument.valueAt(this.mutableDocument,this.path)}set(t,e){const n=mutableDocumentBridge.pointerFor(this.mutableDocument),i=desugarJSObject(t,!1),r=CBOR.encode(i);e?documentSetCBORWithTimestamp(n,this.path,r,!0,0):documentSetCBOR(n,this.path,r,!0),this.updateInMemoryByReloadingLastPathComponent();const o=augmentJSONValue(CBOR.decode(r),this.mutableDocument,this.path),s=UpdateResult.set(MutableDocument.id(this.mutableDocument),this.path,o);this.recordUpdateResult(s)}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(MutableDocument.id(this.mutableDocument),this.path);this.recordUpdateResult(t)}replaceWithCounter(t){const e=mutableDocumentBridge.pointerFor(this.mutableDocument);t?documentReplaceWithCounterWithTimestamp(e,this.path,0):documentReplaceWithCounter(e,this.path),this.updateInMemoryByReloadingLastPathComponent();const n=UpdateResult.replacedWithCounter(MutableDocument.id(this.mutableDocument),this.path);this.recordUpdateResult(n)}increment(t){documentIncrementCounter(mutableDocumentBridge.pointerFor(this.mutableDocument),this.path,t),this.updateInMemoryByReloadingLastPathComponent();const e=UpdateResult.incremented(MutableDocument.id(this.mutableDocument),this.path,t);this.recordUpdateResult(e)}push(t){const e=mutableDocumentBridge.pointerFor(this.mutableDocument),n=desugarJSObject(t,!1),i=CBOR.encode(n);documentPushCBOR(e,this.path,i),this.updateInMemory(((e,n)=>{const i=e[n];if(!Array.isArray(i))throw new Error(`Can't push value, object at key-path ${this.path} is not an array.`);i.push(t)}));const r=augmentJSONValue(CBOR.decode(i),this.mutableDocument,this.path),o=UpdateResult.pushed(MutableDocument.id(this.mutableDocument),this.path,r);this.recordUpdateResult(o)}pop(){const t=documentPopCBOR(mutableDocumentBridge.pointerFor(this.mutableDocument),this.path),e=augmentJSONValue(CBOR.decode(t),this.mutableDocument,this.path);this.updateInMemory(((t,e)=>{const n=t[e];if(!Array.isArray(n))throw new Error(`Can't pop, object at key-path ${this.path} is not an array.`);n.pop()}));const n=UpdateResult.popped(MutableDocument.id(this.mutableDocument),this.path,e);return this.recordUpdateResult(n),e}insert(t){const e=mutableDocumentBridge.pointerFor(this.mutableDocument),n=desugarJSObject(t),i=CBOR.encode(n);documentInsertCBOR(e,this.path,i),this.updateInMemory(((e,n)=>{const i=e[n],r=n;if(!Array.isArray(i))throw new Error(`Can't insert value, object at key-path ${this.path} is not an array.`);if("number"==typeof r)throw new Error(`Can't insert value, last path component in key-path ${this.path} is not a number.`);i.splice(r,0,t)}));const r=augmentJSONValue(CBOR.decode(i),this.mutableDocument,this.path),o=UpdateResult.inserted(MutableDocument.id(this.mutableDocument),this.path,r);this.recordUpdateResult(o)}updateInMemory(t){const e=MutableDocument.value(this.mutableDocument),n=KeyPath.evaluate(this.path,e,{stopAtLastContainer:!0});t(n.value,n.nextPathComponent)}updateInMemoryByReloadingLastPathComponent(){const t=mutableDocumentBridge.pointerFor(this.mutableDocument);this.updateInMemory(((e,n)=>{const i=documentGetCBOR(t,this.path),r=augmentJSONValue(CBOR.decode(i),this.mutableDocument,this.path);e[n]=r}))}recordUpdateResult(t){const e=this.mutableDocument["@ditto.updateResults"].slice();e.push(t),Object.freeze(e),this.mutableDocument["@ditto.updateResults"]=e}atIndex(t){return Logger.warning("Method MutableDocumentPath.atIndex() is deprecated, use MutableDocumentPath.at() instead."),this.at(t)}}class Document{static id(t){let e=t["@ditto.id"];if(void 0===e){const n=documentBridge.pointerFor(t);e=new DocumentID(documentID(n),!0),t["@ditto.id"]=e}return e}static value(t){let e=t["@ditto.value"];if(void 0===e){const n=documentCBOR(documentBridge.pointerFor(t));e=augmentJSONValue(CBOR.decode(n),void 0,""),e._id=Document.id(t),t["@ditto.value"]=e}return e}static valueAt(t,e){const n=this.value(t);return KeyPath.evaluate(e,n).value}static pathAt(t,e,n=!1){const i=n?e:KeyPath.validate(e,{isInitial:!0});return new DocumentPath(t,i)}static hash(t){return documentsHash(documentsFrom(t).map((t=>documentBridge.pointerFor(t))))}static hashMnemonic(t){return documentsHashMnemonic(documentsFrom(t).map((t=>documentBridge.pointerFor(t))))}constructor(){return new Proxy(this,{get:function(t,e,n){if("symbol"==typeof e)return t[e];if("_id"===e)return Document.id(n);if("_value"===e)return Document.value(n);if("_valueAt"===e)return t=>Document.valueAt(n,t);if("_pathAt"===e)return t=>Document.pathAt(n,t);if("constructor"===e)return Reflect.get(t,e,n);if("string"==typeof e&&e.startsWith("@ditto."))return Reflect.get(t,e,n);const i=Document.value(t);return i.hasOwnProperty(e)?Reflect.get(i,e,n):Reflect.get(t,e,n)},ownKeys:function(t){return Reflect.ownKeys(Document.value(t))},set:function(t,e,n){if("string"==typeof e&&e.startsWith("@ditto."))return Reflect.set(t,e,n);throw new Error("Document is immutable and can't be mutated.")}})}}class MutableDocument{constructor(){this["@ditto.updateResults"]=[]}static id(t){let e=t["@ditto.id"];if(void 0===e){const n=mutableDocumentBridge.pointerFor(t);e=new DocumentID(documentID(n),!0),t["@ditto.id"]=e}return e}static value(t){let e=t["@ditto.value"];if(void 0===e){const n=documentCBOR(mutableDocumentBridge.pointerFor(t));e=augmentJSONValue(CBOR.decode(n),this,""),e._id=MutableDocument.id(t),t["@ditto.value"]=e}return e}static valueAt(t,e){const n=this.value(t);return KeyPath.evaluate(e,n).value}static pathAt(t,e,n=!1){const i=n?e:KeyPath.validate(e,{isInitial:!0});return new MutableDocumentPath(t,i)}static replaceWithCounterAt(t,e,n=!1){this.pathAt(t,e,n).replaceWithCounter()}static incrementCounterAt(t,e,n,i=!1){this.pathAt(t,e,i).increment(n)}}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 Subscription{constructor(t,e,n){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},Subscription.add(this,this.contextInfo)}get collectionName(){return this.collection.name}cancel(){this.isCancelled||(this.isCancelled=!0,Subscription.remove(this,this.contextInfo))}static add(t,e){addSubscription(dittoBridge.pointerFor(e.ditto),e.collectionName,e.query,e.queryArgsCBOR),this.finalizationRegistry.register(t,e,e)}static remove(t,e){removeSubscription(dittoBridge.pointerFor(e.ditto),e.collectionName,e.query,e.queryArgsCBOR),t&&this.finalizationRegistry.unregister(e)}}Subscription.finalizationRegistry=new FinalizationRegistry((t=>{Subscription.remove(null,t)}));class UpdateResultsMap{constructor(t,e){if(t.map((t=>t.toString())).sort().join(", ")!==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}}get(t){const e=t.toString();return this.updateResultsByDocumentIDString[e]}keys(){return this.documentIDs.slice()}}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{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}hash(t){return documentsHash(t.map((t=>documentBridge.pointerFor(t))))}hashMnemonic(t){return documentsHashMnemonic(t.map((t=>documentBridge.pointerFor(t))))}}class SingleDocumentLiveQueryEvent{constructor(t,e){this.isInitial=t,this.oldDocument=e}hash(t){return documentsHash(null===t?[]:[documentBridge.pointerFor(t)])}hashMnemonic(t){return documentsHashMnemonic(null===t?[]:[documentBridge.pointerFor(t)])}}class LiveQuery{constructor(t,e,n,i,r,o,s,a,c){this.query=t,this.queryArgs=e?Object.freeze({...e}):null,this.queryArgsCBOR=n,this.limit=i,this.offset=r,this.collection=o,this.waitsForNextSignal=a,this.handler=c,s&&(this.subscription=s);const d=dittoBridge.pointerFor(o.store.ditto),u=o.name;let l;const signalNext=async()=>{await liveQuerySignalAvailableNext(d,l)};if(l=liveQueryRegister(d,u,t,n,[],i,r,a?"WhenSignalled":"Always",(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]})))}),a?c(e,n,signalNext):c(e,n)})),!l)throw new Error("Internal inconsistency, couldn't create a valid live query ID.");this.liveQueryID=l,liveQueryStart(d,l)}get collectionName(){return this.collection.name}stop(){var t;const e=dittoBridge.pointerFor(this.collection.store.ditto);null===(t=this.subscription)||void 0===t||t.cancel(),liveQueryStop(e,this.liveQueryID)}async signalNext(){if(this.waitsForNextSignal){const t=dittoBridge.pointerFor(this.collection.store.ditto);await liveQuerySignalAvailableNext(t,this.liveQueryID)}}}class PendingCursorOperation{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}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)}observe(t){return this._observe(t,!0,!1)}observeWithNextSignal(t){return this._observe(t,!0,!0)}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),n=writeTransaction(e),i=collectionRemoveQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return writeTransactionCommit(e,n),i.map((t=>new DocumentID(t,!0)))}async evict(){const t=this.query,e=dittoBridge.pointerFor(this.collection.store.ditto),n=writeTransaction(e),i=collectionEvictQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return writeTransactionCommit(e,n),i.map((t=>new DocumentID(t,!0)))}async exec(){const t=this.query,e=dittoBridge.pointerFor(this.collection.store.ditto),n=writeTransaction(e),i=collectionExecQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return writeTransactionCommit(e,n),i.map((t=>documentBridge.bridge(t)))}async update(t){const e=this.query,n=dittoBridge.pointerFor(this.collection.store.ditto),i=writeTransaction(n),r=collectionExecQueryStr(n,this.collection.name,i,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset),o=r.map((t=>mutableDocumentBridge.bridge(t,(()=>new MutableDocument))));t(o.map((t=>proxyFactory(MutableDocument.value(t),t,""))));const s=[],a={};for(const t of o){const e=MutableDocument.id(t),n=e.toString(),i=t["@ditto.updateResults"];if(a[n])throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${n}`);s.push(e),a[n]=i,mutableDocumentBridge.pointerFor(t),mutableDocumentBridge.unregister(t)}return collectionUpdateMultiple(n,this.collection.name,i,r),writeTransactionCommit(n,i),new UpdateResultsMap(s,a)}then(t,e){return this.exec().then(t,e)}_observe(t,e,n){const i=e?this.subscribe():null;return new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.currentLimit,this.currentOffset,this.collection,i,n,t)}}class PendingIDSpecificOperation{constructor(t,e){this.documentID=t,this.collection=e}subscribe(){return new Subscription(this.collection,this.query,null)}observe(t){return this._observe(t,!0,!1)}observeWithNextSignal(t){return this._observe(t,!0,!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),e=writeTransaction(t),n=collectionRemove(t,this.collection.name,e,this.documentID["@ditto.cbor"]);return writeTransactionCommit(t,e),n}async evict(){const t=dittoBridge.pointerFor(this.collection.store.ditto),e=writeTransaction(t),n=collectionEvict(t,this.collection.name,e,this.documentID["@ditto.cbor"]);return writeTransactionCommit(t,e),n}async exec(){const t=dittoBridge.pointerFor(this.collection.store.ditto),e=readTransaction(t),n=collectionGet(t,this.collection.name,this.documentID["@ditto.cbor"],e);let i;return n&&(i=documentBridge.bridge(n)),readTransactionFree(e),i}async update(t){const e=dittoBridge.pointerFor(this.collection.store.ditto),n=readTransaction(e),i=await collectionGet(e,this.collection.name,this.documentID["@ditto.cbor"],n);if(readTransactionFree(n),!i)throw new Error(`Can't update, document with ID '${this.documentID}' not found in collection named '${this.collection.name}'`);const r=mutableDocumentBridge.bridge(i,(()=>new MutableDocument));t(proxyFactory(MutableDocument.value(r),r,"")),mutableDocumentBridge.unregister(r);const o=writeTransaction(e);return await collectionUpdate(e,this.collection.name,o,i),await writeTransactionCommit(e,o),r["@ditto.updateResults"].slice()}then(t,e){return this.exec().then(t,e)}get query(){return`_id == ${this.documentID.toString()}`}_observe(t,e,n){const i=e?this.subscribe():null;return new LiveQuery(this.query,null,null,-1,0,this.collection,i,n,((e,i,r)=>{if(e.length>1)throw new Error("Internal inconsistency, single document live query returned more than one document.");if(!1===i.isInitial&&i.oldDocuments.length>1)throw new Error("Internal inconsistency, single document live query returned an update event with more than one old documents.");if(!1===i.isInitial&&i.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.");if(!1===i.isInitial&&i.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.");if(!1===i.isInitial&&i.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.");if(!1===i.isInitial&&i.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.");if((!0===i.isInitial?0:i.insertions.length+i.deletions.length+i.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.");const o=e[0]||null,s=!0===i.isInitial?void 0:i.oldDocuments[0],a=new SingleDocumentLiveQueryEvent(i.isInitial,s);n?t(o,a,r):t(o,a)}))}}class Collection{constructor(t,e){this.name=t,this.store=e}find(t,e){return new PendingCursorOperation(t,null!=e?e:null,this)}findAll(){return this.find("true")}findByID(t){const e=validateDocumentID(t);return new PendingIDSpecificOperation(e,this)}async insert(t,e={}){var n,i,r;const o=null!==(n=e.id)&&void 0!==n?n:t._id,s=null!==(i=e.isDefault)&&void 0!==i&&i,a=null!==(r=e.writeStrategy)&&void 0!==r?r:s?"insertDefaultIfAbsent":"overwrite";if(s&&e.writeStrategy&&"insertDefaultIfAbsent"!==e.writeStrategy)throw new Error("Incompatible isDefault and writeStrategy options.");const c=this.store.ditto,d=dittoBridge.pointerFor(c),u=c.siteID,l=void 0===o?null:validateDocumentID(o),h=l?l["@ditto.cbor"]:null;void 0!==t._id&&t._id instanceof DocumentID&&(t._id=t._id.value);const p=desugarJSObject(t,!0),_=CBOR.encode(p);let m=null;m="insertDefaultIfAbsent"===a?documentNewCBORDefaultData(_,h):documentNewCBOR(_,h,u);const f=writeTransaction(d),g=collectionInsert(d,this.name,f,m,a);return writeTransactionCommit(d,f),new DocumentID(g,!0)}newAttachment(t,e={}){const n=this.store.ditto,i=dittoBridge.pointerFor(n),{id:r,len:o,handle:s}=function(){if("string"==typeof t)return dittoNewAttachmentFromFile(i,t,"Copy");if(t instanceof Uint8Array)return dittoNewAttachmentFromBytes(i,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}`)}(),a=new AttachmentToken({_type:"ditto_attachment",_id:r,_len:o,_meta:{...e}}),c=new Attachment(n,a);return attachmentBridge.bridge(s,(()=>c),{throwIfAlreadyBridged:!0})}fetchAttachment(t,e){const n=this.store.ditto;return new AttachmentFetcher(n,t,e)}}function validateDocumentID(t){if(void 0===t)throw new Error(`Invalid document ID: ${t}`);return t instanceof DocumentID?t:new DocumentID(t)}class CollectionsEvent{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}static initial(t){return new CollectionsEvent({isInitial:!0,collections:t,oldCollections:[],insertions:[],deletions:[],updates:[],moves:[]})}}class PendingCollectionsOperation{constructor(t){this.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",t)),this.store=t}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()}observe(t){return this.pendingCursorOperation.observe(((e,n)=>{const i=collectionsFromDocuments(e,this.store);let r;if(!0===n.isInitial)r=CollectionsEvent.initial(i);else{const t=collectionsFromDocuments(n.oldDocuments,this.store);r=new CollectionsEvent({isInitial:!1,collections:i,oldCollections:t,insertions:n.insertions,deletions:n.deletions,updates:n.updates,moves:n.moves})}t(r)}))}async exec(){return collectionsFromDocuments(await this.pendingCursorOperation.exec(),this.store)}then(t,e){return this.exec().then(t,e)}}function collectionsFromDocuments(t,e){const n=[];return t.forEach((t=>{const i=t.name;void 0!==i&&"string"==typeof i&&n.push(new Collection(i,e))})),n}class Store{constructor(t){this.ditto=t}collection(t){return new Collection(t,this)}collections(){return new PendingCollectionsOperation(this.ditto.store)}collectionNames(){return dittoGetCollectionNames(dittoBridge.pointerFor(this.ditto))}registerLiveQueryWebhook(t,e,n){const i=validateQuery(e),r=liveQueryWebhookRegister(dittoBridge.pointerFor(this.ditto),t,i,[],0,0,n);return new DocumentID(r,!0)}}class Observer{constructor(t,e){this.observerManager=t,this.token=e,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 PresenceManager{constructor(t){this.ditto=t,this.isRegistered=!1,this.currentRemotePeers=[],this.callbacksByPresenceToken={}}addObserver(t){this.registerIfNeeded();const e=this.generatePresenceToken();return this.callbacksByPresenceToken[e]=t,t(this.currentRemotePeers),e}removeObserver(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=[]}}generatePresenceToken(){let t;do{t=Math.ceil(Math.random()*Number.MAX_SAFE_INTEGER)}while(this.callbacksByPresenceToken.hasOwnProperty(t));return t}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 ObserverManager{constructor(t){this.ditto=t,this.isRegistered=!1,this.callbacksByToken={}}addObserver(t){this.registerIfNeeded();const e=this.generateToken();return this.callbacksByToken[e]=t,e}removeObserver(t){delete this.callbacksByToken[t],this.unregisterIfNeeded()}register(t,e){throw new Error("ObserverManager.register() is abstract and must either be assigned or implemented in a subclass.")}unregister(t){throw new Error("ObserverManager.unregister() is abstract and must either be assigned or implemented in a subclass.")}processCallback(...t){throw new Error("ObserverManager.processCallback() is abstract and must either be assigned or implemented in a subclass.")}hasObservers(){return Object.keys(this.callbacksByToken).length>0}registerIfNeeded(){if(!this.isRegistered){this.isRegistered=!0;const t=dittoBridge.pointerFor(this.ditto);this.register(t,this.handleCallback.bind(this))}}unregisterIfNeeded(){if(!this.hasObservers()&&this.isRegistered){this.isRegistered=!1;const t=dittoBridge.pointerFor(this.ditto);this.unregister(t)}}generateToken(){let t;do{t=Math.ceil(Math.random()*Number.MAX_SAFE_INTEGER)}while(this.callbacksByToken.hasOwnProperty(t));return t}handleCallback(...t){const e=this.processCallback(...t);this.notify(...e)}notify(...t){for(const e in this.callbacksByToken){(0,this.callbacksByToken[e])(...t)}}async finalize(t){await this.removeObserver(t)}}class TransportConditionsManager extends ObserverManager{register(t,e){return dittoRegisterTransportConditionChangedCallback(t,e)}unregister(t){return dittoRegisterTransportConditionChangedCallback(t,null)}processCallback(t,e){let n,i;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":i="Unknown";break;case"Ok":i="OK";break;case"GenericFailure":i="GenericFailure";break;case"AppInBackground":i="AppInBackground";break;case"MdnsFailure":i="MDNSFailure";break;case"TcpListenFailure":i="TCPListenFailure";break;case"NoBleCentralPermission":i="NoBLECentralPermission";break;case"NoBlePeripheralPermission":i="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":i="CannotEstablishConnection";break;case"BleDisabled":i="BLEDisabled";break;case"NoBleHardware":i="NoBLEHardware";break;case"WifiDisabled":i="WiFiDisabled";break;case"TemporarilyUnavailable":i="TemporarilyUnavailable"}return[i,n]}}class Sync{constructor(t){this.bluetoothLETransportPointer=null,this.awdlTransportPointer=null,this.lanTransportPointer=null;const e={identity:t.identity,transportConfig:new TransportConfig,isWebValid:!1,isX509Valid:!1,isSyncEnabled:!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.updateGlobal(e,n),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.state=n}updatePeerToPeerBluetoothLE(t,e){const n=dittoBridge.pointerFor(this.ditto),i=t.effectiveTransportConfig.peerToPeer.bluetoothLE,r=e.effectiveTransportConfig.peerToPeer.bluetoothLE,o=!i.isEnabled&&r.isEnabled,s=i.isEnabled&&!r.isEnabled;if(o&&this.bluetoothLETransportPointer)throw new Error("Internal inconsistency, when starting BLE transport, no BLE transport pointer should exist.");if(s&&!this.bluetoothLETransportPointer)throw new Error("Internal inconsistency, when stopping BLE transport, a BLE transport pointer should exist.");if("linux"!==process.platform){if(o){if(!bleIsAvailable(n))throw new Error("Can't start P2P BluetoothLE transport because not available.");this.bluetoothLETransportPointer=bleCreate(n)}s&&(bleDestroy(this.bluetoothLETransportPointer),delete this.bluetoothLETransportPointer)}else{if(o){const t={clientTransport:ditto_add_internal_ble_client_transport(n),serverTransport:ditto_add_internal_ble_server_transport(n)};this.bluetoothLETransportPointer=t}if(s){const t=this.bluetoothLETransportPointer,{clientTransport:e,serverTransport:n}=t;ble_server_free_handle(n),ble_client_free_handle(e),this.bluetoothLETransportPointer=null}}}updatePeerToPeerAWDL(t,e){const n=dittoBridge.pointerFor(this.ditto),i=t.effectiveTransportConfig.peerToPeer.awdl,r=e.effectiveTransportConfig.peerToPeer.awdl,o=!i.isEnabled&&r.isEnabled,s=i.isEnabled&&!r.isEnabled;if(o&&this.awdlTransportPointer)throw new Error("Internal inconsistency, when starting AWDL transport, no AWDL transport pointer should exist.");if(s&&!this.awdlTransportPointer)throw new Error("Internal inconsistency, when stopping AWDL transport, an AWDL transport pointer should exist.");if(o){if(!awdlIsAvailable(n))throw new Error("Can't start P2P AWDL transport because not available.");this.awdlTransportPointer=awdlCreate(n)}s&&(awdlDestroy(this.awdlTransportPointer),this.awdlTransportPointer=null)}updatePeerToPeerLAN(t,e){const n=dittoBridge.pointerFor(this.ditto),i=t.effectiveTransportConfig.peerToPeer.lan,r=e.effectiveTransportConfig.peerToPeer.lan;if(i.isEnabled&&(i.isMdnsEnabled&&(lanDestroy(this.lanTransportPointer),delete this.lanTransportPointer),i.isMulticastEnabled&&dittoRemoveMulticastTransport(n)),r.isEnabled){if(r.isMdnsEnabled){if(!lanIsAvailable(n))throw new Error("Can't start P2P LAN transport because not available.");this.lanTransportPointer=lanCreate(n)}r.isMulticastEnabled&&dittoAddMulticastTransport(n)}}updateListenTCP(t,e){const n=t.effectiveTransportConfig.listen.tcp,i=e.effectiveTransportConfig.listen.tcp;if(TransportConfig.areListenTCPsEqual(i,n))return;const r=dittoBridge.pointerFor(this.ditto);n.isEnabled&&dittoStopTCPServer(r),i.isEnabled&&dittoStartTCPServer(r,`${i.interfaceIP}:${i.port}`)}updateListenHTTP(t,e){const n=t.effectiveTransportConfig.listen.http,i=e.effectiveTransportConfig.listen.http;if(TransportConfig.areListenHTTPsEqual(n,i))return;const r=dittoBridge.pointerFor(this.ditto);n.isEnabled&&dittoStopHTTPServer(r),i.isEnabled&&dittoStartHTTPServer(r,`${i.interfaceIP}:${i.port}`,i.staticContentPath||null,i.websocketSync?"Enabled":"Disabled",i.tlsCertificatePath||null,i.tlsKeyPath||null)}updateConnectTCPServers(t,e){const n=Object.getOwnPropertyNames(this.staticTCPClientsByAddress),i=e.effectiveTransportConfig.connect.tcpServers,r=new Set(i);for(const t of n)r.delete(t);const o=new Set(n);for(const t of i)o.delete(t);const s=r.values(),a=o.values();for(const t of s){const e=addStaticTCPClient(dittoBridge.pointerFor(this.ditto),t),n=staticTCPClientBridge.bridge(e);this.staticTCPClientsByAddress[t]=n}for(const t of a){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),i=e.effectiveTransportConfig.connect.websocketURLs.slice(),r=new Set(i);for(const t of n)r.delete(t);const o=new Set(n);for(const t of i)o.delete(t);const s=r.values(),a=o.values();for(const t of s){const e=addWebsocketClient(dittoBridge.pointerFor(this.ditto),t),n=websocketClientBridge.bridge(e);this.websocketClientsByURL[t]=n}for(const t of a){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){const e=t.transportConfig.copy(),n=t.identity,i=t.isSyncEnabled,r=t.isX509Valid,o=t.isWebValid;return e.connect.tcpServers,e.connect.websocketURLs,i&&r||(e.peerToPeer.bluetoothLE.isEnabled=!1,e.peerToPeer.awdl.isEnabled=!1,e.peerToPeer.lan.isEnabled=!1,e.listen.tcp.isEnabled=!1,e.connect.tcpServers=[]),i&&o||(e.listen.http.isEnabled=!1,e.connect.websocketURLs=[]),i&&o&&("online"===n.type||"onlinePlayground"===n.type)&&n.enableDittoCloudSync&&e.connect.websocketURLs.push(`wss://${n.appID}.cloud.ditto.live`),e.peerToPeer.lan.isEnabled&&!e.listen.tcp.isEnabled&&(e.listen.tcp.isEnabled=!0,e.listen.tcp.interfaceIP="[::]",e.listen.tcp.port=0),{underlyingSyncParameters:t,effectiveTransportConfig:e.freeze()}}class Ditto{constructor(t,e){this.isWebValid=!1,this.isX509Valid=!1;const n=e&&e.trim().length>0?e:"ditto",i=Object.freeze(this.validateIdentity(t));this.identity=Object.freeze(i),this.path=n;require("fs").mkdirSync(n,{recursive:!0});{const t=require("os");this.deviceName=t.hostname()}const r=uninitializedDittoMake(n);let o=null;const s=(()=>{var t,e;if("development"===i.type||"offlinePlayground"===i.type)return dittoAuthClientMakeForDevelopment(n,i.appID,null!==(t=i.siteID)&&void 0!==t?t:0);if("manual"===i.type||"production"===i.type)return dittoAuthClientMakeWithStaticX509(i.certificate);if("sharedKey"===i.type)return dittoAuthClientMakeWithSharedKey(n,i.appID,i.sharedKey,i.siteID);if("onlinePlayground"===i.type)return dittoAuthClientMakeForDevelopment(n,i.appID,0);if("onlineWithAuthentication"===i.type||"online"===i.type){const t=null!==(e=i.customAuthURL)&&void 0!==e?e:`https://${i.appID}.cloud.ditto.live`,r=dittoAuthClientMakeLoginProvider((t=>{this.auth?this.authenticationExpiring(t):o=t}));return dittoAuthClientMakeWithWeb(n,i.appID,t,r)}throw new Error(`Can't create Ditto, unsupported identity type: ${i}`)})();dittoAuthClientSetValidityListener(s,this.authClientValidityChanged.bind(this));const a=dittoAuthClientIsWebValid(s),c=dittoAuthClientIsX509Valid(s),d=dittoAuthClientGetSiteID(s),u=dittoMake(r,s);["onlineWithAuthentication","online"].includes(i.type)?this.auth=new OnlineWithAuthenticationAuthenticator(s):(dittoAuthClientFree(s),this.auth=new NotAvailableAuthenticator);const l=new TransportConfig;this.siteID=d,this.transportConfig=l.copy().freeze(),this.isX509Valid=c,this.isWebValid=a,this.sync=new Sync(this),this.sync.update({isSyncEnabled:!1,isX509Valid:c,isWebValid:a,identity:i,transportConfig:l}),this.isActivated=false,this.store=new Store(this),this.presenceManager=new PresenceManager(this),this.transportConditionsManager=new TransportConditionsManager(this);const h=dittoBridge.bridge(u,(()=>this));return null!==o&&this.authenticationExpiring(o),h}get sdkVersion(){return dittoGetSDKVersion(dittoBridge.pointerFor(this))}setLicenseToken(t){const{result:e,errorMessage:n}=verifyLicense(t);if("LicenseOk"!==e)throw this.isActivated=false,new Error(n);this.isActivated=!0}setAccessLicense(t){Logger.warning("Ditto.setAccessLicense() is deprecated, use setLicenseToken() instead."),this.setLicenseToken(t)}setTransportConfig(t){this.transportConfig,this.transportConfig=t.copy().freeze();const e=this.transportConfig,n=this.identity,i=this.isWebValid,r=this.isX509Valid;this.sync.update({transportConfig:e,identity:n,isWebValid:i,isX509Valid:r,isSyncEnabled:this.isSyncEnabled})}updateTransportConfig(t){const e=this.transportConfig.copy();return t(e),this.setTransportConfig(e),this}tryStartSync(){this.startSync()}startSync(){this.setSyncEnabled(!0)}stopSync(){this.setSyncEnabled(!1)}observePeers(t){const e=this.presenceManager.addObserver(t);return new Observer(this.presenceManager,e)}observeTransportConditions(t){const e=this.transportConditionsManager.addObserver(t);return new Observer(this.transportConditionsManager,e)}runGarbageCollection(){dittoRunGarbageCollection(dittoBridge.pointerFor(this))}authenticationExpiring(t){if("online"!==this.identity.type&&"onlineWithAuthentication"!==this.identity.type)throw new Error(`Internal inconsistency, authenticationExpiring() should only be called for identities of type 'onlineWithAuthentication' or 'online', but current identity is: ${this.identity.type}`);const e=this.auth,n=this.identity.authHandler;t>0?n.authenticationExpiringSoon(e,t):n.authenticationRequired(e)}authClientValidityChanged(t,e){const n=this.transportConfig,i=this.identity,r=this.isSyncEnabled;this.isX509Valid,this.isWebValid,this.isX509Valid=e,this.isWebValid=t,this.sync.update({transportConfig:n,identity:i,isWebValid:t,isX509Valid:e,isSyncEnabled:r})}validateIdentity(t){const e={...t};if(!["development","offlinePlayground","sharedKey","production","manual","onlinePlayground","online","onlineWithAuthentication"].includes(t.type))throw new Error(`Can't create Ditto instance, unknown identity type: ${t.type}`);if("development"!==t.type&&"offlinePlayground"!==t.type&&"sharedKey"!==t.type||void 0===t.appName||void 0===t.appID||(Logger.warning("Properties .appID and .appName (deprecated) are both given for identity, .appID will be used and .appName will be ignored."),delete e.appName),"development"!==t.type&&"offlinePlayground"!==t.type&&"sharedKey"!==t.type||void 0===t.appName||void 0!==t.appID||(Logger.warning("Property .appName of IdentityDevelopment and IdentitySharedKey is deprecated, use .appID instead."),e.appID=t.appName,delete e.appName),("development"===t.type||"offlinePlayground"===t.type||"sharedKey"===t.type)&&void 0===t.appName&&void 0===t.appID)throw new Error("Property .appID or the deprecated .appName must be given for identity, but aren't.");if(("development"===t.type||"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")}return t.type,"production"===t.type&&Logger.warning("IdentityProduction (type: 'production') is deprecated, please use IdentityManual instead."),t.type,t.type,"online"===t.type||t.type,e}setSyncEnabled(t){if(t&&!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 `setLicenseToken`. If you need to obtain a license token then please visit https://portal.ditto.live.");const e=dittoBridge.pointerFor(this);this.isSyncEnabled=t;const n=this.isWebValid,i=this.isX509Valid,r=this.identity,o=this.transportConfig;dittoSetDeviceName(e,this.deviceName),this.sync.update({identity:r,transportConfig:o,isWebValid:n,isX509Valid:i,isSyncEnabled:!!t})}}Ditto.webAssemblyModule=null;const dittoBridge=new Bridge(Ditto,dittoDrop);async function init(t={}){}switch(process.platform){case"android":initSDKVersion("Android","JavaScript","1.0.14");break;case"darwin":initSDKVersion("Mac","JavaScript","1.0.14");break;case"linux":initSDKVersion("Linux","JavaScript","1.0.14");break;case"win32":initSDKVersion("Windows","JavaScript","1.0.14");break;default:initSDKVersion("Unknown","JavaScript","1.0.14")}loggerInit(),exports.Attachment=Attachment,exports.AttachmentFetcher=AttachmentFetcher,exports.AttachmentToken=AttachmentToken,exports.Collection=Collection,exports.Counter=Counter,exports.Ditto=Ditto,exports.Document=Document,exports.DocumentID=DocumentID,exports.DocumentPath=DocumentPath,exports.LiveQuery=LiveQuery,exports.LiveQueryEventInitial=LiveQueryEventInitial,exports.LiveQueryEventUpdate=LiveQueryEventUpdate,exports.Logger=Logger,exports.MutableDocument=MutableDocument,exports.MutableDocumentPath=MutableDocumentPath,exports.NotAvailableAuthenticator=NotAvailableAuthenticator,exports.Observer=Observer,exports.OnlineWithAuthenticationAuthenticator=OnlineWithAuthenticationAuthenticator,exports.PendingCursorOperation=PendingCursorOperation,exports.PendingIDSpecificOperation=PendingIDSpecificOperation,exports.SingleDocumentLiveQueryEvent=SingleDocumentLiveQueryEvent,exports.Store=Store,exports.Subscription=Subscription,exports.TransportConfig=TransportConfig,exports.UpdateResult=UpdateResult,exports.UpdateResultsMap=UpdateResultsMap,exports.Value=Value,exports.__log=__log,exports.attachmentBridge=attachmentBridge,exports.dittoBridge=dittoBridge,exports.documentBridge=documentBridge,exports.init=init,exports.mutableDocumentBridge=mutableDocumentBridge;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});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=sharedMetaByAddrMap,this.finalizationRegistry=new FinalizationRegistry(this.finalize.bind(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 i=n.throwIfAlreadyBridged,r=this.objectFor(t);if(r&&i)throw new Error(`Can't bridge, pointer has already been bridged: ${JSON.stringify(t)}`);if(r)return r;e||(e=()=>Reflect.construct(this.type,[]));const o=e();if(!o)throw new Error(`Can't bridge, expected create() to return an object but got: ${o}`);return this.register(o,t),o}register(t,e){const n=t.constructor,i=this.type;if(n!==i)throw new Error(`Can't register, bridge is configured for type ${i.name} but passed in object is of type ${n.name}`);const r=this.pointerFor(t),o=this.metaByAddrMap[e.addr];if(r&&o)throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${o.pointer}`);if(r&&!o)throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no meta entry: ${t}`);if(!r&&o)throw new Error(`Internal inconsistency, trying to register an object which has a meta entry but no associated pointer: ${t}`);const s=new Meta(n,new WeakRef(t),e);t["@ditto.ptr"]=e,this.metaByAddrMap[s.pointer.addr]=s,this.finalizationRegistry.register(t,e,t)}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 i=this.pointerFor(t);if(!i)throw new Error(`Can't unregister, object that has not been registered before: ${t}`);const r=this.metaByAddrMap[i.addr];if(!r)throw new Error(`Internal inconsistency, trying to unregister an object which has an associated pointer but no meta entry: ${t}`);if(r.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: ${r}`);if(!r.object.deref())throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry whose object is undfined (garbage collected): ${r}`);if(r.object.deref()!==t)throw new Error(`Internal inconsistency, trying to unregister an object that has a meta entry holding a different object: ${r}`);this.finalizationRegistry.unregister(t),delete this.metaByAddrMap[i.addr],delete t["@ditto.ptr"]}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)}}const sharedMetaByAddrMap={},isWebBuild=!1;function validateNumber(t,e={}){var n;const i=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Number validation failed:",r=!!e.integer,o=e.min,s=e.max,a=e.minX,c=e.maxX;if("number"!=typeof t)throw new Error(`${i} '${t}' is not a number.`);if(r&&Math.floor(t)!==t)throw new Error(`${i} '${t}' is not an integer.`);if(void 0!==o&&t<o)throw new Error(`${i} '${t}' must be >= ${o}.`);if(void 0!==s&&t>s)throw new Error(`${i} '${t}' must be <= ${s}.`);if(void 0!==a&&t<=a)throw new Error(`${i} '${t}' must be > ${a}.`);if(void 0!==c&&t>=c)throw new Error(`${i} '${t}' must be < ${c}.`);return t}function validateQuery(t,e={}){var n;const i=null!==(n=e.errorMessagePrefix)&&void 0!==n?n:"Query validation failed,";if("string"!=typeof t)throw new Error(`${i} query is not a string: ${t}`);if(""===t)throw new Error(`${i} query is an empty string.`);const r=t.trim();if(""===r)throw new Error(`${i} query contains only whitespace characters.`);return r}class StaticTCPClient{}class WebsocketClient{}const staticTCPClientBridge=new Bridge(StaticTCPClient,staticTCPClientFreeHandle),websocketClientBridge=new Bridge(WebsocketClient,websocketClientFreeHandle),arch=process.arch,platform=process.platform,ditto=require("./ditto."+platform+"-"+arch+".node");function ble_client_free_handle(...t){return ditto.ble_client_free_handle(...t)}function ble_server_free_handle(...t){return ditto.ble_server_free_handle(...t)}function boxCBytesIntoBuffer(...t){return ditto.boxCBytesIntoBuffer(...t)}function boxCStringIntoString(...t){return ditto.boxCStringIntoString(...t)}function cStringVecToStringArray(...t){return ditto.cStringVecToStringArray(...t)}function ditto_add_internal_ble_client_transport(...t){return ditto.ditto_add_internal_ble_client_transport(...t)}function ditto_add_internal_ble_server_transport(...t){return ditto.ditto_add_internal_ble_server_transport(...t)}function ditto_add_multicast_transport(...t){return ditto.ditto_add_multicast_transport(...t)}function ditto_add_static_tcp_client(...t){return ditto.ditto_add_static_tcp_client(...t)}function ditto_add_subscription(...t){return ditto.ditto_add_subscription(...t)}function ditto_add_websocket_client(...t){return ditto.ditto_add_websocket_client(...t)}function ditto_auth_client_free(...t){return ditto.ditto_auth_client_free(...t)}function ditto_auth_client_get_site_id(...t){return ditto.ditto_auth_client_get_site_id(...t)}function ditto_auth_client_is_web_valid(...t){return ditto.ditto_auth_client_is_web_valid(...t)}function ditto_auth_client_is_x509_valid(...t){return ditto.ditto_auth_client_is_x509_valid(...t)}function ditto_auth_client_login_with_credentials(...t){return ditto.ditto_auth_client_login_with_credentials(...t)}function ditto_auth_client_login_with_token(...t){return ditto.ditto_auth_client_login_with_token(...t)}function ditto_auth_client_make_for_development(...t){return ditto.ditto_auth_client_make_for_development(...t)}function ditto_auth_client_make_login_provider(...t){return ditto.ditto_auth_client_make_login_provider(...t)}function ditto_auth_client_make_with_shared_key(...t){return ditto.ditto_auth_client_make_with_shared_key(...t)}function ditto_auth_client_make_with_static_x509(...t){return ditto.ditto_auth_client_make_with_static_x509(...t)}function ditto_auth_client_make_with_web(...t){return ditto.ditto_auth_client_make_with_web(...t)}function ditto_auth_client_set_validity_listener(...t){return ditto.ditto_auth_client_set_validity_listener(...t)}function ditto_auth_client_user_id(...t){return ditto.ditto_auth_client_user_id(...t)}function ditto_cancel_resolve_attachment(...t){return ditto.ditto_cancel_resolve_attachment(...t)}function ditto_clear_presence_callback(...t){return ditto.ditto_clear_presence_callback(...t)}function ditto_collection_evict(...t){return ditto.ditto_collection_evict(...t)}function ditto_collection_evict_query_str(...t){return ditto.ditto_collection_evict_query_str(...t)}function ditto_collection_exec_query_str(...t){return ditto.ditto_collection_exec_query_str(...t)}function ditto_collection_get(...t){return ditto.ditto_collection_get(...t)}function ditto_collection_insert_value(...t){return ditto.ditto_collection_insert_value(...t)}function ditto_collection_remove(...t){return ditto.ditto_collection_remove(...t)}function ditto_collection_remove_query_str(...t){return ditto.ditto_collection_remove_query_str(...t)}function ditto_collection_update(...t){return ditto.ditto_collection_update(...t)}function ditto_collection_update_multiple(...t){return ditto.ditto_collection_update_multiple(...t)}function ditto_document_cbor(...t){return ditto.ditto_document_cbor(...t)}function ditto_document_free(...t){return ditto.ditto_document_free(...t)}function ditto_document_get_cbor(...t){return ditto.ditto_document_get_cbor(...t)}function ditto_document_id(...t){return ditto.ditto_document_id(...t)}function ditto_document_id_query_compatible(...t){return ditto.ditto_document_id_query_compatible(...t)}function ditto_document_increment_counter(...t){return ditto.ditto_document_increment_counter(...t)}function ditto_document_insert_cbor(...t){return ditto.ditto_document_insert_cbor(...t)}function ditto_document_pop_cbor(...t){return ditto.ditto_document_pop_cbor(...t)}function ditto_document_push_cbor(...t){return ditto.ditto_document_push_cbor(...t)}function ditto_document_remove(...t){return ditto.ditto_document_remove(...t)}function ditto_document_replace_with_counter(...t){return ditto.ditto_document_replace_with_counter(...t)}function ditto_document_replace_with_counter_with_timestamp(...t){return ditto.ditto_document_replace_with_counter_with_timestamp(...t)}function ditto_document_set_cbor(...t){return ditto.ditto_document_set_cbor(...t)}function ditto_document_set_cbor_with_timestamp(...t){return ditto.ditto_document_set_cbor_with_timestamp(...t)}function ditto_documents_hash(...t){return ditto.ditto_documents_hash(...t)}function ditto_documents_hash_mnemonic(...t){return ditto.ditto_documents_hash_mnemonic(...t)}function ditto_drop(...t){return ditto.ditto_drop(...t)}function ditto_error_message(...t){return ditto.ditto_error_message(...t)}function ditto_free_attachment_handle(...t){return ditto.ditto_free_attachment_handle(...t)}function ditto_get_collection_names(...t){return ditto.ditto_get_collection_names(...t)}function ditto_get_complete_attachment_path(...t){return ditto.ditto_get_complete_attachment_path(...t)}function ditto_get_sdk_version(...t){return ditto.ditto_get_sdk_version(...t)}function ditto_init_sdk_version(...t){return ditto.ditto_init_sdk_version(...t)}function ditto_live_query_register_str(...t){return ditto.ditto_live_query_register_str(...t)}function ditto_live_query_signal_available_next(...t){return ditto.ditto_live_query_signal_available_next(...t)}function ditto_live_query_start(...t){return ditto.ditto_live_query_start(...t)}function ditto_live_query_stop(...t){return ditto.ditto_live_query_stop(...t)}function ditto_live_query_webhook_register_str(...t){return ditto.ditto_live_query_webhook_register_str(...t)}function ditto_log(...t){return ditto.ditto_log(...t)}function ditto_logger_emoji_headings_enabled(...t){return ditto.ditto_logger_emoji_headings_enabled(...t)}function ditto_logger_emoji_headings_enabled_get(...t){return ditto.ditto_logger_emoji_headings_enabled_get(...t)}function ditto_logger_enabled(...t){return ditto.ditto_logger_enabled(...t)}function ditto_logger_enabled_get(...t){return ditto.ditto_logger_enabled_get(...t)}function ditto_logger_init(...t){return ditto.ditto_logger_init(...t)}function ditto_logger_minimum_log_level(...t){return ditto.ditto_logger_minimum_log_level(...t)}function ditto_logger_minimum_log_level_get(...t){return ditto.ditto_logger_minimum_log_level_get(...t)}function ditto_logger_set_custom_log_cb(...t){return ditto.ditto_logger_set_custom_log_cb(...t)}function ditto_logger_set_log_file(...t){return ditto.ditto_logger_set_log_file(...t)}function ditto_make(...t){return ditto.ditto_make(...t)}function ditto_new_attachment_from_bytes(...t){return ditto.ditto_new_attachment_from_bytes(...t)}function ditto_new_attachment_from_file(...t){return ditto.ditto_new_attachment_from_file(...t)}function ditto_presence_v1(...t){return ditto.ditto_presence_v1(...t)}function ditto_read_transaction(...t){return ditto.ditto_read_transaction(...t)}function ditto_read_transaction_free(...t){return ditto.ditto_read_transaction_free(...t)}function ditto_register_presence_v1_callback(...t){return ditto.ditto_register_presence_v1_callback(...t)}function ditto_register_transport_condition_changed_callback(...t){return ditto.ditto_register_transport_condition_changed_callback(...t)}function ditto_remove_multicast_transport(...t){return ditto.ditto_remove_multicast_transport(...t)}function ditto_remove_subscription(...t){return ditto.ditto_remove_subscription(...t)}function ditto_resolve_attachment(...t){return ditto.ditto_resolve_attachment(...t)}function ditto_run_garbage_collection(...t){return ditto.ditto_run_garbage_collection(...t)}function ditto_set_device_name(...t){return ditto.ditto_set_device_name(...t)}function ditto_set_sync_group(...t){return ditto.ditto_set_sync_group(...t)}function ditto_start_http_server(...t){return ditto.ditto_start_http_server(...t)}function ditto_start_tcp_server(...t){return ditto.ditto_start_tcp_server(...t)}function ditto_stop_http_server(...t){return ditto.ditto_stop_http_server(...t)}function ditto_stop_tcp_server(...t){return ditto.ditto_stop_tcp_server(...t)}function ditto_write_transaction(...t){return ditto.ditto_write_transaction(...t)}function ditto_write_transaction_commit(...t){return ditto.ditto_write_transaction_commit(...t)}function jsDocsToCDocs(...t){return ditto.jsDocsToCDocs(...t)}function refCStringToString(...t){return ditto.refCStringToString(...t)}function static_tcp_client_free_handle(...t){return ditto.static_tcp_client_free_handle(...t)}function uninitialized_ditto_make(...t){return ditto.uninitialized_ditto_make(...t)}function verify_license(...t){return ditto.verify_license(...t)}function websocket_client_free_handle(...t){return ditto.websocket_client_free_handle(...t)}function withOutBoxCBytes(...t){return ditto.withOutBoxCBytes(...t)}function withOutPtr$1(...t){return ditto.withOutPtr(...t)}function documentSetCBORWithTimestamp(t,e,n,i,r){ensureInitialized();const o=ditto_document_set_cbor_with_timestamp(t,bytesFromString(e),n,i,r);if(0!==o)throw new Error(errorMessage()||`ditto_document_set_cbor_with_timestamp() failed with error code: ${o}`)}function documentSetCBOR(t,e,n,i){ensureInitialized();const r=ditto_document_set_cbor(t,bytesFromString(e),n,i);if(0!==r)throw new Error(errorMessage()||`ditto_document_set_cbor() failed with error code: ${r}`)}function documentID(t){ensureInitialized();return boxCBytesIntoBuffer(ditto_document_id(t))}function documentCBOR(t){ensureInitialized();return boxCBytesIntoBuffer(ditto_document_cbor(t))}function documentGetCBOR(t,e){ensureInitialized();return boxCBytesIntoBuffer(ditto_document_get_cbor(t,bytesFromString(e)),e)}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 documentReplaceWithCounter(t,e){ensureInitialized();const n=ditto_document_replace_with_counter(t,bytesFromString(e)),i=errorMessage();if("InvalidPointer"===i)throw new Error(`Can't replace with counter, property does not exist at path or path is not valid: ${e}`);if(0!==n)throw new Error(i||`ditto_document_replace_with_counter() failed with error code: ${n}`)}function documentReplaceWithCounterWithTimestamp(t,e,n){ensureInitialized();const i=ditto_document_replace_with_counter_with_timestamp(t,bytesFromString(e),n),r=errorMessage();if("InvalidPointer"===r)throw new Error(`Can't replace with counter, property does not exist at path or path is not valid: ${e}`);if(0!==i)throw new Error(r||`ditto_document_replace_with_counter_with_timestamp() failed with error code: ${i}`)}function documentIncrementCounter(t,e,n){ensureInitialized();const i=ditto_document_increment_counter(t,bytesFromString(e),n);if(0!==i)throw new Error(errorMessage()||`ditto_document_increment_counter() failed with error code: ${i}`)}function documentPushCBOR(t,e,n){ensureInitialized();const i=ditto_document_push_cbor(t,bytesFromString(e),n);if(0!==i)throw new Error(errorMessage()||`ditto_document_push_cbor() failed with error code: ${i}`)}function documentPopCBOR(t,e){ensureInitialized();const n=bytesFromString(e);return boxCBytesIntoBuffer(withOutBoxCBytes((e=>{const i=ditto_document_pop_cbor(t,n,e);if(0!==i)throw new Error(errorMessage()||`ditto_document_pop_cbor() failed with error code: ${i}`);return e})))}function documentInsertCBOR(t,e,n){ensureInitialized();const i=ditto_document_insert_cbor(t,bytesFromString(e),n);if(0!==i)throw new Error(errorMessage()||`ditto_document_insert_cbor() failed with error code: ${i}`)}function documentFree(t){ensureInitialized(),ditto_document_free(t)}function documentIDQueryCompatible(t,e){ensureInitialized();return boxCStringIntoString(ditto_document_id_query_compatible(t,e))}function collectionGet(t,e,n,i){ensureInitialized();const r=bytesFromString(e),{status_code:o,document:s}=ditto_collection_get(t,r,n,i);if(o===NOT_FOUND_ERROR_CODE)return null;if(0!==o)throw new Error(errorMessage()||`ditto_collection_get() failed with error code: ${o}`);return s}function collectionInsertValue(t,e,n,i,r){ensureInitialized();const o=bytesFromString(e);let s;switch(r){case"merge":s="Merge";break;case"overwrite":s="Overwrite";break;case"insertIfAbsent":s="InsertIfAbsent";break;case"insertDefaultIfAbsent":s="InsertDefaultIfAbsent";break;default:throw new Error("Invalid write strategy provided")}const{status_code:a,id:c}=ditto_collection_insert_value(t,o,n,i,s,null);if(0!==a)throw new Error(errorMessage()||`ditto_collection_insert_value() failed with error code: ${a}`);return boxCBytesIntoBuffer(c)}function collectionRemove(t,e,n,i){ensureInitialized();const r=bytesFromString(e),{status_code:o,bool_value:s}=ditto_collection_remove(t,r,n,i);if(0!==o)throw new Error(errorMessage()||`ditto_collection_remove() failed with error code: ${o}`);return s}function collectionEvict(t,e,n,i){ensureInitialized();const r=bytesFromString(e),{status_code:o,bool_value:s}=ditto_collection_evict(t,r,n,i);if(0!==o)throw new Error(errorMessage()||`ditto_collection_evict() failed with error code: ${o}`);return s}function collectionUpdate(t,e,n,i){ensureInitialized();const r=ditto_collection_update(t,bytesFromString(e),n,i);if(0!==r)throw new Error(errorMessage()||`ditto_collection_update() failed with error code: ${r}`)}function collectionUpdateMultiple(t,e,n,i){ensureInitialized();const r=ditto_collection_update_multiple(t,bytesFromString(e),n,jsDocsToCDocs(i));if(0!==r)throw new Error(errorMessage()||`ditto_collection_update_multiple() failed with error code: ${r}`)}function collectionExecQueryStr(t,e,n,i,r,o,s,a){ensureInitialized();return ditto_collection_exec_query_str(t,bytesFromString(e),n,bytesFromString(i),r,o,s,a)}function collectionRemoveQueryStr(t,e,n,i,r,o,s,a){ensureInitialized();return ditto_collection_remove_query_str(t,bytesFromString(e),n,bytesFromString(i),r,o,s,a)}function collectionEvictQueryStr(t,e,n,i,r,o,s,a){ensureInitialized();return ditto_collection_evict_query_str(t,bytesFromString(e),n,bytesFromString(i),r,o,s,a)}function addSubscription(t,e,n,i){ensureInitialized();return ditto_add_subscription(t,bytesFromString(e),bytesFromString(n),i)}function removeSubscription(t,e,n,i){ensureInitialized();return ditto_remove_subscription(t,bytesFromString(e),bytesFromString(n),i)}function liveQueryRegister(t,e,n,i,r,o,s,a,c,d){ensureInitialized();const u=bytesFromString(e),l=bytesFromString(n),{status_code:h,i64:p}=ditto_live_query_register_str(t,u,l,i,r,o,s,a,wrapBackgroundCbForFFI(d,c));if(0!==h)throw new Error(errorMessage()||`\`ditto_live_query_register_str()\` failed with error code: ${h}`);return p}function liveQueryStart(t,e){ensureInitialized();const n=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)}function liveQueryWebhookRegister(t,e,n,i,r,o,s){ensureInitialized();const a=bytesFromString(e),c=bytesFromString(n),d=bytesFromString(s),{status_code:u,id:l}=ditto_live_query_webhook_register_str(t,a,c,i,r,o,d);if(0!==u)throw new Error(errorMessage()||`\`ditto_live_query_webhook_register_str()\` failed with error code: ${u}`);return boxCBytesIntoBuffer(l)}function readTransaction(t){ensureInitialized();const{status_code:e,txn:n}=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)}function writeTransaction(t){ensureInitialized();const{status_code:e,txn:n}=ditto_write_transaction(t);if(0!==e)throw new Error(errorMessage()||`ditto_write_transaction() failed with error code: ${e}`);return n}function writeTransactionCommit(t,e){ensureInitialized();const n=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 ditto_add_static_tcp_client(t,bytesFromString(e))}function staticTCPClientFreeHandle(t){static_tcp_client_free_handle(t)}function addWebsocketClient(t,e){ensureInitialized();return ditto_add_websocket_client(t,bytesFromString(e))}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 i=boxCStringIntoString(n);t(e,i)}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 dittoAuthClientMakeWithWeb(t,e,n,i){ensureInitialized();const r=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(n),{status_code:a,auth_client:c}=ditto_auth_client_make_with_web(r,o,s,i);if(0!==a)throw new Error(errorMessage()||`ditto_auth_client_make_with_web() failed with error code: ${a}`);return c}function dittoAuthClientMakeForDevelopment(t,e,n){ensureInitialized();const i=bytesFromString(t),r=bytesFromString(e),o=Number(n),{status_code:s,auth_client:a}=ditto_auth_client_make_for_development(i,r,o);if(0!==s)throw new Error(errorMessage()||`ditto_auth_client_make_for_development() failed with error code: ${s}`);return a}function dittoAuthClientMakeWithSharedKey(t,e,n,i){ensureInitialized();const r=bytesFromString(t),o=bytesFromString(e),s=bytesFromString(n),a=Number(i),{status_code:c,auth_client:d}=ditto_auth_client_make_with_shared_key(r,o,s,a);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:i}=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 i}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 i=bytesFromString(e),r=bytesFromString(n),o=await ditto_auth_client_login_with_token(t,i,r);if(0!==o)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${o}).`)}async function dittoAuthClientLoginWithUsernameAndPassword(t,e,n,i){ensureInitialized();const r=bytesFromString(e),o=bytesFromString(n),s=bytesFromString(i),a=await ditto_auth_client_login_with_credentials(t,r,o,s);if(0!==a)throw new Error(errorMessage()||`Ditto failed to authenticate (error code: ${a}).`)}function uninitializedDittoMake(t){ensureInitialized();return uninitialized_ditto_make(bytesFromString(t))}function dittoMake(t,e){return ensureInitialized(),ditto_make(t,e)}function dittoGetCollectionNames(t){ensureInitialized();const e=ditto_get_collection_names(t),n=e.status_code,i=e.names;if(0!==n)throw new Error(errorMessage()||`ditto_get_collection_names() failed with error code: ${n}`);return cStringVecToStringArray(i)}function dittoDrop(t){return ensureInitialized(),ditto_drop(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)}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){return ensureInitialized(),ditto_set_device_name(t,bytesFromString(e))}function dittoSetSyncGroup(t,e){return ensureInitialized(),ditto_set_sync_group(t,e)}function dittoNewAttachmentFromFile(t,e,n){ensureInitialized();const i={},r=ditto_new_attachment_from_file(t,bytesFromString(e),n,i);if(0!==r)throw new Error(errorMessage()||`ditto_new_attachment_from_file() failed with error code: ${r}`);return i}function dittoNewAttachmentFromBytes(t,e){ensureInitialized();const n={},i=ditto_new_attachment_from_bytes(t,e,n);if(0!==i)throw new Error(errorMessage()||`ditto_new_attachment_from_bytes() failed with error code: ${i}`);return n}function dittoResolveAttachment(t,e,n,i){ensureInitialized();const{onComplete:r,onProgress:o,onDelete:s}=n,{status_code:a,cancel_token:c}=ditto_resolve_attachment(t,e,wrapBackgroundCbForFFI(i,r),wrapBackgroundCbForFFI(i,o),wrapBackgroundCbForFFI(i,s));if(0!==a)throw new Error(errorMessage()||`ditto_resolve_attachment() failed with error code: ${a}`);return c}function dittoCancelResolveAttachment(t,e,n){ensureInitialized();const i=ditto_cancel_resolve_attachment(t,e,n);if(0!==i)throw new Error(errorMessage()||`ditto_cancel_resolve_attachment() failed with error code: ${i}`)}function freeAttachmentHandle(t){ensureInitialized(),ditto_free_attachment_handle(t)}function dittoGetCompleteAttachmentPath(t,e){ensureInitialized();return refCStringToString(ditto_get_complete_attachment_path(t,e))}function dittoGetSDKVersion(t){ensureInitialized();return boxCStringIntoString(ditto_get_sdk_version(t))}function dittoPresenceV1(t){ensureInitialized();return boxCStringIntoString(ditto_presence_v1(t))}function dittoStartTCPServer(t,e){ensureInitialized();return ditto_start_tcp_server(t,bytesFromString(e))}function dittoStopTCPServer(t){return ensureInitialized(),ditto_stop_tcp_server(t)}function dittoAddMulticastTransport(t){return ensureInitialized(),ditto_add_multicast_transport(t)}function dittoRemoveMulticastTransport(t){return ensureInitialized(),ditto_remove_multicast_transport(t)}function dittoStartHTTPServer(t,e,n,i,r,o){ensureInitialized();return ditto_start_http_server(t,bytesFromString(e),bytesFromString(n),i,bytesFromString(r),bytesFromString(o))}function dittoStopHTTPServer(t){return ensureInitialized(),ditto_stop_http_server(t)}function dittoRunGarbageCollection(t){return ensureInitialized(),ditto_run_garbage_collection(t)}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,((t,n)=>e(1===t,1===n))))}let withOutPtr,isInitialized=!1;function initSDKVersion(t,e,n){ensureInitialized(),bytesFromString(t),bytesFromString(e);const i=ditto_init_sdk_version(t,e,bytesFromString(n));if(void 0!==i&&0!==i)throw new Error(errorMessage()||`ditto_init_sdk_version() failed with error code: ${i}`)}function verifyLicense(t){ensureInitialized();const e=bytesFromString(t);let n;const i=boxCStringIntoString(withOutPtr("char *",(t=>(n=verify_license(e,t),t))));return{result:n,errorMessage:i}}isInitialized=!0,withOutPtr=wrapFFIOutFunction(withOutPtr$1);const NOT_FOUND_ERROR_CODE=-30798;function wrapBackgroundCbForFFI(t,e){return void 0===t&&(t=console.error),(n,...i)=>{let r;try{r=e(...i)}catch(e){try{t(e)}catch(t){console.error(`Internal error: \`onError()\` handler oughtn't throw, but it did throw ${t}`)}}return n(r)}}function wrapFFIOutFunction(t){return function(...e){let n,i,r=!1;const o=e[e.length-1],s=e.splice(0,e.length-1),a=t(...s,(t=>{try{i=o(t),r=i===t}catch(t){n=t}}));if(n)throw n;return r?a:i}}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)throw new Error("Ditto needs to be initialized before using any of its API, please make sure to call `await init()` first.")}let transports=null;if("undefined"!=typeof process&&"undefined"!=typeof require){const t=process.arch,e=process.platform;try{transports=require(`./transports.${e}-${t}.node`)}catch(t){}}function bleIsAvailable(t){return null!==transports&&transports.bleIsAvailable(t)}function bleCreate(t){if(null!==transports)return transports.bleCreate(t);throw new Error("Can't create BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}function bleDestroy(t){if(null!==transports)return transports.bleDestroy(t);throw new Error("Can't destroy BluetoothLE handle, P2P BluetoothLE is not supported on this platform.")}function lanIsAvailable(t){return null!==transports&&transports.lanIsAvailable(t)}function lanCreate(t){if(null!==transports)return transports.lanCreate(t);throw new Error("Can't create LAN handle, P2P LAN transport is not supported on this platform.")}function lanDestroy(t){if(null!==transports)return transports.lanDestroy(t);throw new Error("Can't destroy LAN handle, P2P LAN transport is not supported on this platform.")}function awdlIsAvailable(t){return null!==transports&&transports.awdlIsAvailable(t)}function awdlCreate(t){if(null!==transports)return transports.awdlCreate(t);throw new Error("Can't create AWDL handle, P2P AWDL transport is not supported on this platform.")}function awdlDestroy(t){if(null!==transports)return transports.awdlDestroy(t);throw new Error("Can't destroy AWDL handle, P2P AWDL transport is not supported on this platform.")}const fullBuildVersionString="1.0.17";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:"[::]",port:4040},http:{isEnabled:!1,interfaceIP:"[::]",port:80,websocketSync:!0}},this.global={syncGroup: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}static areListenTCPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port}static areListenHTTPsEqual(t,e){return t.isEnabled===e.isEnabled&&t.interfaceIP===e.interfaceIP&&t.port===e.port&&t.staticContentPath===e.staticContentPath&&t.websocketSync===e.websocketSync&&t.tlsKeyPath===e.tlsKeyPath&&t.tlsCertificatePath===e.tlsCertificatePath}}class OnlineWithAuthenticationAuthenticator{constructor(t){this.loginSupported=!0,this.authClientPointer=t,OnlineWithAuthenticationAuthenticator.finalizationRegistry.register(this,t)}async loginWithToken(t,e){await dittoAuthClientLoginWithToken(this.authClientPointer,t,e)}async loginWithUsernameAndPassword(t,e,n){await dittoAuthClientLoginWithUsernameAndPassword(this.authClientPointer,t,e,n)}isAuthenticated(){return dittoAuthClientIsWebValid(this.authClientPointer)}static finalize(t){dittoAuthClientFree(t)}get userID(){return dittoAuthClientUserID(this.authClientPointer)}}OnlineWithAuthenticationAuthenticator.finalizationRegistry=new FinalizationRegistry(OnlineWithAuthenticationAuthenticator.finalize);class NotAvailableAuthenticator{constructor(){this.loginSupported=!1}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.")}isAuthenticated(){return!1}get userID(){return null}}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}function decode(t,e,n){let i=new DataView(t),r=new Uint8Array(t),o=0,tagValueFunction=function(t,e){return t},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,r[o])}function readUint16(){return commitRead(2,i.getUint16(o))}function readUint32(){return commitRead(4,i.getUint32(o))}function readBreak(){return 255===r[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 s=function decodeItem(){let t,e,n=readUint8(),r=n>>5,s=31&n;if(7===r)switch(s){case 25:return function readFloat16(){let t=new ArrayBuffer(4),e=new DataView(t),n=readUint16(),i=32768&n,r=31744&n,o=1023&n;if(31744===r)r=261120;else if(0!==r)r+=114688;else if(0!==o)return(i?-1:1)*o*POW_2_24;return e.setUint32(0,i<<16|r<<13|o<<13),e.getFloat32(0)}();case 26:return function readFloat32(){return commitRead(4,i.getFloat32(o))}();case 27:return function readFloat64(){return commitRead(8,i.getFloat64(o))}()}if(e=readLength(s),e<0&&(r<2||6<r))throw new Error("Invalid length");switch(r){case 0:return e;case 1:return-1-e;case 2:if(e<0){let n=[],i=0;for(;(e=readIndefiniteStringLength(r))>=0;)i+=e,n.push(readArrayBuffer(e));let o=new Uint8Array(i),s=0;for(t=0;t<n.length;++t)o.set(n[t],s),s+=n[t].length;return o}return readArrayBuffer(e);case 3:let n=[];if(e<0)for(;(e=readIndefiniteStringLength(r))>=0;)appendUtf16Data(n,e);else appendUtf16Data(n,e);let i="";for(t=0;t<n.length;t+=8192)i+=String.fromCharCode.apply(null,n.slice(t,t+8192));return i;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 s={};for(t=0;t<e||e<0&&!readBreak();++t){s[decodeItem()]=decodeItem()}return s;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 s}function encode(t){let e,n=new ArrayBuffer(256),i=new DataView(n),r=new Uint8Array(n),o=0;function prepareWrite(t){let s=n.byteLength,a=o+t;for(;s<a;)s<<=1;if(s!==n.byteLength){let t=i;n=new ArrayBuffer(s),i=new DataView(n),r=new Uint8Array(n);let e=o+3>>2;for(let n=0;n<e;++n)i.setUint32(n<<2,t.getUint32(n<<2))}return e=t,i}function commitWrite(...t){o+=e}function writeUint8(t){commitWrite(prepareWrite(1).setUint8(o,t))}function writeUint8Array(t){prepareWrite(t.length),r.set(t,o),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),function writeUint16(t){commitWrite(prepareWrite(2).setUint16(o,t))}(e)):e<4294967296?(writeUint8(t<<5|26),function writeUint32(t){commitWrite(prepareWrite(4).setUint32(o,t))}(e)):(writeUint8(t<<5|27),function writeUint64(t){let e=t%POW_2_32,n=(t-e)/POW_2_32,i=prepareWrite(8);i.setUint32(o,n),i.setUint32(o+4,e),commitWrite()}(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 i=t.charCodeAt(e);i<128?n.push(i):i<2048?(n.push(192|i>>6),n.push(128|63&i)):i<55296||i>=57344?(n.push(224|i>>12),n.push(128|i>>6&63),n.push(128|63&i)):(i=(1023&i)<<10,i|=1023&t.charCodeAt(++e),i+=65536,n.push(240|i>>18),n.push(128|i>>12&63),n.push(128|i>>6&63),n.push(128|63&i))}return writeTypeAndLength(3,n.length),writeUint8Array(n);default:let i,r;if(Array.isArray(t))for(i=t.length,writeTypeAndLength(4,i),e=0;e<i;e+=1)encodeItem(t[e]);else if(t instanceof Uint8Array)writeTypeAndLength(2,t.length),writeUint8Array(t);else if(ArrayBuffer.isView(t))r=new Uint8Array(t.buffer),writeTypeAndLength(2,r.length),writeUint8Array(r);else if(t instanceof ArrayBuffer||"function"==typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer)r=new Uint8Array(t),writeTypeAndLength(2,r.length),writeUint8Array(r);else{let n=Object.keys(t);for(i=n.length,writeTypeAndLength(5,i),e=0;e<i;e+=1){let i=n[e];encodeItem(i),encodeItem(t[i])}}}}(t),"slice"in n)return n.slice(0,o);let s=new ArrayBuffer(o),a=new DataView(s);for(let t=0;t<o;++t)a.setUint8(t,i.getUint8(t));return s}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 Attachment{constructor(t,e){this.ditto=t,this.token=e}get metadata(){return this.token.metadata}getData(){{const t=dittoGetCompleteAttachmentPath(dittoBridge.pointerFor(this.ditto),attachmentBridge.pointerFor(this));return require("fs/promises").readFile(t)}}copyToPath(t){{const e=dittoGetCompleteAttachmentPath(dittoBridge.pointerFor(this.ditto),attachmentBridge.pointerFor(this)),n=require("fs/promises");return n.copyFile(e,t,n.COPYFILE_EXCL)}}}const attachmentBridge=new Bridge(Attachment,freeAttachmentHandle);class AttachmentToken{constructor(t){if("ditto_attachment"!==t._type)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 i=t._meta;if("object"!=typeof i)throw new Error("Invalid attachment token meta");this.id=e,this.len=n,this.metadata=i}}class AttachmentFetcher{constructor(t,e,n){this.ditto=t,this.token=e,this.eventHandler=n||null,this.cancelToken=null;const i=n||function(){};this.attachment=new Promise(((n,r)=>{const o=dittoBridge.pointerFor(t);this.cancelToken=dittoResolveAttachment(o,e.id,{onComplete:t=>{this.eventHandler=null,this.cancelToken=null;const e=new Attachment(this.ditto,this.token);attachmentBridge.bridge(t,(()=>e),{throwIfAlreadyBridged:!0}),i({type:"Completed",attachment:e}),n(e)},onProgress:(t,e)=>{i({type:"Progress",totalBytes:e,downloadedBytes:t})},onDelete:()=>{this.eventHandler=null,this.cancelToken=null,i({type:"Deleted"}),n(null)}},(t=>{this.eventHandler=null,this.cancelToken=null,r(t)}))}))}stop(){const t=this.cancelToken;if(t){this.cancelToken=null;dittoCancelResolveAttachment(dittoBridge.pointerFor(this.ditto),this.token.id,t)}}then(t,e){return this.attachment.then(t,e)}}class Subscription{constructor(t,e,n){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},Subscription.add(this,this.contextInfo)}get collectionName(){return this.collection.name}cancel(){this.isCancelled||(this.isCancelled=!0,Subscription.remove(this,this.contextInfo))}static add(t,e){addSubscription(dittoBridge.pointerFor(e.ditto),e.collectionName,e.query,e.queryArgsCBOR),this.finalizationRegistry.register(t,e,e)}static remove(t,e){removeSubscription(dittoBridge.pointerFor(e.ditto),e.collectionName,e.query,e.queryArgsCBOR),t&&this.finalizationRegistry.unregister(e)}}function __log(t,e){Logger.warning("Function __log() is deprecated, use Logger.log() & friends instead."),Logger.log(t,e)}Subscription.finalizationRegistry=new FinalizationRegistry((t=>{Subscription.remove(null,t)}));class Logger{constructor(){throw new Error("Logger can't be instantiated, use it's static properties & methods directly instead.")}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)}setLogFile(t){throw new Error("Deprecated, use Logger's static properties and methods directly instead.")}setLogFileURL(t){throw new Error("Deprecated, use Logger's static properties and methods directly instead.")}async setCustomLogCallback(t){throw new Error("Deprecated, use Logger's static properties and methods directly instead.")}static shared(){return Logger.warning("Logger.shared() is deprecated, use Logger's static properties & methods directly instead."),this}}class UpdateResult{constructor(t,e,n,i,r){this.type=t,this.docID=e,this.path=n,void 0!==i&&(this.value=i),void 0!==r&&(this.amount=r)}static set(t,e,n){return new UpdateResult("set",t,e,n,void 0)}static replacedWithCounter(t,e){return new UpdateResult("replacedWithCounter",t,e,void 0,void 0)}static incremented(t,e,n){return new UpdateResult("incremented",t,e,void 0,n)}static inserted(t,e,n){return new UpdateResult("inserted",t,e,n,void 0)}static removed(t,e){return new UpdateResult("removed",t,e,void 0,void 0)}static pushed(t,e,n){return new UpdateResult("pushed",t,e,n,void 0)}static popped(t,e,n){return new UpdateResult("popped",t,e,n,void 0)}}class Counter{constructor(t,e){this.value=t,this.isDefault=!!e}increment(t){if(!this.mutDoc)throw new Error("Can't increment counter, only possible within the closure of a collection's update() method.");this.mutDoc.at(this.path,!0).increment(t),this.value+=t}static __newInternal(t,e,n){const i=new Counter(n);return i.mutDoc=t,i.path=e,i}}class Value{constructor(t,e={}){this.value=t,this.isDefault=!!e.isDefault}}const validPathIdentifier=/^[A-Za-z0-9_]+$/,validPathFirstCharIdentifier=/^[A-Za-z_]/;function validateKeyPathComponent(t,e=!1){if(Number.isFinite(+t))return`[${t}]`;if("string"==typeof t)return validPathFirstCharIdentifier.test(t)&&validPathIdentifier.test(t)?e?t:`.${t}`:`['${t}']`;throw new Error(`Invalid path component: ${t}.`)}const arrayOps=["push","pop","splice","unshift","shift"];function set(t,e,n){let i=n,r=!1;const o=n instanceof Counter,s=n instanceof Value;(o||s)&&(i=n.value,r=!!n.isDefault);const a=i instanceof Counter,c=i instanceof Value;if(o&&a)throw`Can't set counter at path '${e}', nesting of Counter within Counter is forbidden.`;if(o&&c)throw`Can't set counter at path '${e}', nesting of Value within Counter is forbidden.`;if(s&&a)throw`Can't set value at path '${e}', nesting of Counter within Value is forbidden.`;if(s&&c)throw`Can't set value at path '${e}', nesting of Value within Value is forbidden.`;MutableDocument.pathAt(t,e,!0).set(i,r),o&&MutableDocument.pathAt(t,e,!0).replaceWithCounter(r)}function proxyFactory(t,e,n){return new Proxy(t,{get(t,i,r){if("symbol"==typeof i)return t[i];if("object"==typeof t&&""===n){if("_value"===i)return MutableDocument.value(r);if("_valueAt"===i)return t=>MutableDocument.valueAt(r,t);if("_pathAt"===i)return t=>MutableDocument.pathAt(r,t);if("string"==typeof i&&i.startsWith("@ditto."))return e[i]}if("_replaceWithCounterAt"===i)return t=>{const i=validateKeyPathComponent(t);return MutableDocument.replaceWithCounterAt(e,`${n}${i}`)};if("_incrementCounterAt"===i)return(t,i)=>{const r=validateKeyPathComponent(t);return MutableDocument.incrementCounterAt(e,`${n}${r}`,i)};if(t instanceof Counter)return t[i];const o=t[i],s=typeof o;if("undefined"!==s){if("function"===s&&arrayOps.includes(i)&&(t.__arrayOp=i),"object"!==s)return o;const r=validateKeyPathComponent(i,""===n);return proxyFactory(o,e,`${n}${r}`)}return o},set(t,i,r){const o=validateKeyPathComponent(i,""===n),s=`${n}${o}`;if("object"==typeof t&&""===n&&"string"==typeof i&&i.startsWith("@ditto."))return e[i]=r,!0;if("object"==typeof t&&Array.isArray(t)){if("length"===i){if(r===t.length-1){const i=t.__arrayOp;i&&"pop"===i&&(MutableDocument.pathAt(e,n,!0).pop(),t.pop())}return t[i]=r,delete t.__arrayOp,!0}const o=+i;if(isNaN(o))throw new Error(`Attempting to access a non-index property of an array. Property: ${i}.`);const a=t.__arrayOp;if(o===t.length&&a&&"push"===a)MutableDocument.pathAt(e,n,!0).push(r),t.push(r);else if(a){let n=t.__cachedSetOperations||[];if(o>t.length)n.push({index:o,value:r,path:s}),t.__cachedSetOperations=n;else{set(e,s,r),t[o]=r;let i=n.length;for(;i>0;){const r=n[i-1];r.index===t.length&&(set(e,r.path,r.value),t[r.index]=r.value,n.splice(i-1,1)),i--}}}else{if(!(o<=t.length))throw new Error(`Attempting to set an array index of ${o} but the array only has ${t.length} elements`);set(e,s,r),t[o]=r}}else{if(t instanceof Counter&&"value"===i);else{const n=+i;if(Number.isFinite(n))throw new Error(`Attempting to access an array index property (${n}) of an object: ${JSON.stringify(t)}.`);set(e,s,r)}t[i]=r}return!0},deleteProperty(t,i){if(i in t){const r=t.__arrayOp;if(r&&"pop"===r)return!0;const o=validateKeyPathComponent(i,""===n),s=`${n}${o}`;return MutableDocument.pathAt(e,s,!0).remove(),delete t[i],!0}return!1}})}function augmentJSONValue(t,e,n){let i={};if(""===n){for(const[n,r]of Object.entries(t))i[n]=augmentJSONValue(r,e,n);return i}if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,i)=>augmentJSONValue(t,e,`${n}[${i}]`)));if("ditto_counter"===t._type)return Counter.__newInternal(e,n,t._value);if("ditto_attachment"===t._type)return new AttachmentToken(t);for(const[i,r]of Object.entries(t))t[i]=augmentJSONValue(r,e,`${n}['${i}']`);return t}return t}function desugarJSObject(t,e){let n={};if(e){for(const[e,i]of Object.entries(t))n[e]=desugarJSObject(i,!1);return n}if(t&&"object"==typeof t){if(Array.isArray(t))return t.map(((t,e)=>desugarJSObject(t,!1)));if(t instanceof Counter)return t.value;if(t instanceof Attachment)return{_type:"ditto_attachment",_id:t.token.id,_len:t.token.len,_meta:t.token.metadata};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 i=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 r=this.withLeadingDot(t);if(!validKeyPathRegExp.test(r))throw new Error(`Key-path is not valid: ${t}`);return i?t:r}static evaluate(t,e,n={}){var i;const r=null!==(i=n.stopAtLastContainer)&&void 0!==i&&i,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:i,remainingPath:s}=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],i=e[1];return{nextPathComponentRaw:n,nextPathComponent:i,remainingPath:t.slice(i.length+1)}}const n=t.match(subscriptIndexRegExp);if(null!==n){const e=n[0],i=n[1];return{nextPathComponentRaw:e,nextPathComponent:parseInt(i),remainingPath:t.slice(i.length+2)}}const i=t.match(subscriptSingleQuoteKeyRegExp);if(null!==i){const e=i[0],n=i[1];return{nextPathComponentRaw:e,nextPathComponent:n,remainingPath:t.slice(n.length+4)}}const r=t.match(subscriptDoubleQuoteKeyRegExp);if(null!==r){const e=r[0],n=r[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=i,o.remainingPath=s,null===o.coveredPath||"number"==typeof n?o.coveredPath=n:o.coveredPath+=n,""===s&&r?(o.value=t,o):recurse(t[i],s)}(e,this.withLeadingDot(t))}constructor(){}}class DocumentPath{constructor(t,e){this.document=t,this.path=e}at(t){if("string"==typeof t){const e=t,n=KeyPath.validate(e);return new DocumentPath(this.document,`${this.path}${n}`)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"DocumentPath.atIndex() validation failed index:"});return new DocumentPath(this.document,`${this.path}[${e.toString()}]`)}throw new Error(`Can't return document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}value(){return Document.valueAt(this.document,this.path)}atIndex(t){return Logger.warning("Method DocumentPath.atIndex() is deprecated, use DocumentPath.at() instead."),this.at(t)}}class MutableDocumentPath{constructor(t,e){this.mutableDocument=t,this.path=e}at(t){if("string"==typeof t){const e=t;return KeyPath.validate(e),new MutableDocumentPath(this.mutableDocument,`${this.path}.${e}`)}if("number"==typeof t){const e=validateNumber(t,{integer:!0,min:0,errorMessagePrefix:"MutableDocumentPath.atIndex() validation failed index:"});return new MutableDocumentPath(this.mutableDocument,`${this.path}[${e.toString()}]`)}throw new Error(`Can't return mutable document path at key-path or index, string or number expected but got ${typeof t}: ${t}`)}value(){return MutableDocument.valueAt(this.mutableDocument,this.path)}set(t,e){const n=mutableDocumentBridge.pointerFor(this.mutableDocument),i=desugarJSObject(t,!1),r=CBOR.encode(i);e?documentSetCBORWithTimestamp(n,this.path,r,!0,0):documentSetCBOR(n,this.path,r,!0),this.updateInMemoryByReloadingLastPathComponent();const o=augmentJSONValue(CBOR.decode(r),this.mutableDocument,this.path),s=UpdateResult.set(MutableDocument.id(this.mutableDocument),this.path,o);this.recordUpdateResult(s)}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(MutableDocument.id(this.mutableDocument),this.path);this.recordUpdateResult(t)}replaceWithCounter(t){const e=mutableDocumentBridge.pointerFor(this.mutableDocument);t?documentReplaceWithCounterWithTimestamp(e,this.path,0):documentReplaceWithCounter(e,this.path),this.updateInMemoryByReloadingLastPathComponent();const n=UpdateResult.replacedWithCounter(MutableDocument.id(this.mutableDocument),this.path);this.recordUpdateResult(n)}increment(t){documentIncrementCounter(mutableDocumentBridge.pointerFor(this.mutableDocument),this.path,t),this.updateInMemoryByReloadingLastPathComponent();const e=UpdateResult.incremented(MutableDocument.id(this.mutableDocument),this.path,t);this.recordUpdateResult(e)}push(t){const e=mutableDocumentBridge.pointerFor(this.mutableDocument),n=desugarJSObject(t,!1),i=CBOR.encode(n);documentPushCBOR(e,this.path,i),this.updateInMemory(((e,n)=>{const i=e[n];if(!Array.isArray(i))throw new Error(`Can't push value, object at key-path ${this.path} is not an array.`);i.push(t)}));const r=augmentJSONValue(CBOR.decode(i),this.mutableDocument,this.path),o=UpdateResult.pushed(MutableDocument.id(this.mutableDocument),this.path,r);this.recordUpdateResult(o)}pop(){const t=documentPopCBOR(mutableDocumentBridge.pointerFor(this.mutableDocument),this.path),e=augmentJSONValue(CBOR.decode(t),this.mutableDocument,this.path);this.updateInMemory(((t,e)=>{const n=t[e];if(!Array.isArray(n))throw new Error(`Can't pop, object at key-path ${this.path} is not an array.`);n.pop()}));const n=UpdateResult.popped(MutableDocument.id(this.mutableDocument),this.path,e);return this.recordUpdateResult(n),e}insert(t){const e=mutableDocumentBridge.pointerFor(this.mutableDocument),n=desugarJSObject(t),i=CBOR.encode(n);documentInsertCBOR(e,this.path,i),this.updateInMemory(((e,n)=>{const i=e[n],r=n;if(!Array.isArray(i))throw new Error(`Can't insert value, object at key-path ${this.path} is not an array.`);if("number"==typeof r)throw new Error(`Can't insert value, last path component in key-path ${this.path} is not a number.`);i.splice(r,0,t)}));const r=augmentJSONValue(CBOR.decode(i),this.mutableDocument,this.path),o=UpdateResult.inserted(MutableDocument.id(this.mutableDocument),this.path,r);this.recordUpdateResult(o)}updateInMemory(t){const e=MutableDocument.value(this.mutableDocument),n=KeyPath.evaluate(this.path,e,{stopAtLastContainer:!0});t(n.value,n.nextPathComponent)}updateInMemoryByReloadingLastPathComponent(){const t=mutableDocumentBridge.pointerFor(this.mutableDocument);this.updateInMemory(((e,n)=>{const i=documentGetCBOR(t,this.path),r=augmentJSONValue(CBOR.decode(i),this.mutableDocument,this.path);e[n]=r}))}recordUpdateResult(t){const e=this.mutableDocument["@ditto.updateResults"].slice();e.push(t),Object.freeze(e),this.mutableDocument["@ditto.updateResults"]=e}atIndex(t){return Logger.warning("Method MutableDocumentPath.atIndex() is deprecated, use MutableDocumentPath.at() instead."),this.at(t)}}class Document{static id(t){let e=t["@ditto.id"];if(void 0===e){const n=documentID(documentBridge.pointerFor(t));e=CBOR.decode(n),t["@ditto.id"]=e}return e}static value(t){let e=t["@ditto.value"];if(void 0===e){const n=documentCBOR(documentBridge.pointerFor(t));e=augmentJSONValue(CBOR.decode(n),void 0,""),t["@ditto.value"]=e}return e}static stringForID(t){return documentIDQueryCompatible(CBOR.encode(t),"WithQuotes")}static base64StringForID(t){const e=CBOR.encode(t);return btoa(String.fromCharCode.apply(null,e))}static valueAt(t,e){const n=this.value(t);return KeyPath.evaluate(e,n).value}static pathAt(t,e,n=!1){const i=n?e:KeyPath.validate(e,{isInitial:!0});return new DocumentPath(t,i)}static hash(t){return documentsHash(documentsFrom(t).map((t=>documentBridge.pointerFor(t))))}static hashMnemonic(t){return documentsHashMnemonic(documentsFrom(t).map((t=>documentBridge.pointerFor(t))))}constructor(){return new Proxy(this,{get:function(t,e,n){if("symbol"==typeof e)return t[e];if("_id"===e)return Document.id(n);if("_value"===e)return Document.value(n);if("_valueAt"===e)return t=>Document.valueAt(n,t);if("_pathAt"===e)return t=>Document.pathAt(n,t);if("constructor"===e)return Reflect.get(t,e,n);if("string"==typeof e&&e.startsWith("@ditto."))return Reflect.get(t,e,n);const i=Document.value(t);return i.hasOwnProperty(e)?Reflect.get(i,e,n):Reflect.get(t,e,n)},ownKeys:function(t){return Reflect.ownKeys(Document.value(t))},set:function(t,e,n){if("string"==typeof e&&e.startsWith("@ditto."))return Reflect.set(t,e,n);throw new Error("Document is immutable and can't be mutated.")}})}}class MutableDocument{constructor(){this["@ditto.updateResults"]=[]}static id(t){let e=t["@ditto.id"];if(void 0===e){const n=documentID(mutableDocumentBridge.pointerFor(t));e=CBOR.decode(n),t["@ditto.id"]=e}return e}static value(t){let e=t["@ditto.value"];if(void 0===e){const n=documentCBOR(mutableDocumentBridge.pointerFor(t));e=augmentJSONValue(CBOR.decode(n),this,""),t["@ditto.value"]=e}return e}static valueAt(t,e){const n=this.value(t);return KeyPath.evaluate(e,n).value}static pathAt(t,e,n=!1){const i=n?e:KeyPath.validate(e,{isInitial:!0});return new MutableDocumentPath(t,i)}static replaceWithCounterAt(t,e,n=!1){this.pathAt(t,e,n).replaceWithCounter()}static incrementCounterAt(t,e,n,i=!1){this.pathAt(t,e,i).increment(n)}}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{constructor(t,e){const n=t.map((t=>Document.stringForID(t))).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}}get(t){const e=Document.stringForID(t);return this.updateResultsByDocumentIDString[e]}keys(){return this.documentIDs.slice()}}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{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}hash(t){return documentsHash(t.map((t=>documentBridge.pointerFor(t))))}hashMnemonic(t){return documentsHashMnemonic(t.map((t=>documentBridge.pointerFor(t))))}}class SingleDocumentLiveQueryEvent{constructor(t,e){this.isInitial=t,this.oldDocument=e}hash(t){return documentsHash(null===t?[]:[documentBridge.pointerFor(t)])}hashMnemonic(t){return documentsHashMnemonic(null===t?[]:[documentBridge.pointerFor(t)])}}class LiveQuery{constructor(t,e,n,i,r,o,s,a,c,d){this.query=t,this.queryArgs=e?Object.freeze({...e}):null,this.queryArgsCBOR=n,this.orderBys=i,this.limit=r,this.offset=o,this.collection=s,this.waitsForNextSignal=c,this.handler=d,a&&(this.subscription=a);const u=dittoBridge.pointerFor(s.store.ditto),l=s.name,h=c?"WhenSignalled":"Always";let p;const signalNext=async()=>{await liveQuerySignalAvailableNext(u,p)};if(p=liveQueryRegister(u,l,t,n,this.orderBys,r,o,h,(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?d(e,n,signalNext):d(e,n)})),!p)throw new Error("Internal inconsistency, couldn't create a valid live query ID.");this.liveQueryID=p,liveQueryStart(u,p)}get collectionName(){return this.collection.name}stop(){var t;const e=dittoBridge.pointerFor(this.collection.store.ditto);null===(t=this.subscription)||void 0===t||t.cancel(),liveQueryStop(e,this.liveQueryID)}async signalNext(){if(this.waitsForNextSignal){const t=dittoBridge.pointerFor(this.collection.store.ditto);await liveQuerySignalAvailableNext(t,this.liveQueryID)}}}class PendingCursorOperation{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}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)}observe(t){return this._observe(t,!0,!1)}observeWithNextSignal(t){return this._observe(t,!0,!0)}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),n=writeTransaction(e),i=collectionRemoveQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return writeTransactionCommit(e,n),i.map((t=>CBOR.decode(t)))}async evict(){const t=this.query,e=dittoBridge.pointerFor(this.collection.store.ditto),n=writeTransaction(e),i=collectionEvictQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return writeTransactionCommit(e,n),i.map((t=>CBOR.decode(t)))}async exec(){const t=this.query,e=dittoBridge.pointerFor(this.collection.store.ditto),n=writeTransaction(e),i=collectionExecQueryStr(e,this.collection.name,n,t,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset);return writeTransactionCommit(e,n),i.map((t=>documentBridge.bridge(t)))}async update(t){const e=this.query,n=dittoBridge.pointerFor(this.collection.store.ditto),i=writeTransaction(n),r=collectionExecQueryStr(n,this.collection.name,i,e,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset),o=r.map((t=>mutableDocumentBridge.bridge(t,(()=>new MutableDocument))));t(o.map((t=>proxyFactory(MutableDocument.value(t),t,""))));const s=[],a={};for(const t of o){const e=MutableDocument.id(t),n=Document.stringForID(e),i=t["@ditto.updateResults"];if(a[n])throw new Error(`Internal inconsistency, update results for document ID as string already exist: ${n}`);s.push(e),a[n]=i,mutableDocumentBridge.pointerFor(t),mutableDocumentBridge.unregister(t)}return collectionUpdateMultiple(n,this.collection.name,i,r),writeTransactionCommit(n,i),new UpdateResultsMap(s,a)}then(t,e){return this.exec().then(t,e)}_observe(t,e,n){const i=e?this.subscribe():null;return new LiveQuery(this.query,this.queryArgs,this.queryArgsCBOR,this.orderBys,this.currentLimit,this.currentOffset,this.collection,i,n,t)}}class PendingIDSpecificOperation{constructor(t,e){this.documentID=t,this.collection=e,this.documentIDCBOR=CBOR.encode(t)}subscribe(){return new Subscription(this.collection,this.query,null)}observe(t){return this._observe(t,!0,!1)}observeWithNextSignal(t){return this._observe(t,!0,!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),e=writeTransaction(t),n=collectionRemove(t,this.collection.name,e,this.documentIDCBOR);return writeTransactionCommit(t,e),n}async evict(){const t=dittoBridge.pointerFor(this.collection.store.ditto),e=writeTransaction(t),n=collectionEvict(t,this.collection.name,e,this.documentIDCBOR);return writeTransactionCommit(t,e),n}async exec(){const t=dittoBridge.pointerFor(this.collection.store.ditto),e=readTransaction(t),n=collectionGet(t,this.collection.name,this.documentIDCBOR,e);let i;return n&&(i=documentBridge.bridge(n)),readTransactionFree(e),i}async update(t){const e=dittoBridge.pointerFor(this.collection.store.ditto),n=readTransaction(e),i=await collectionGet(e,this.collection.name,this.documentIDCBOR,n);if(readTransactionFree(n),!i)throw new Error(`Can't update, document with ID '${this.documentID}' not found in collection named '${this.collection.name}'`);const r=mutableDocumentBridge.bridge(i,(()=>new MutableDocument));t(proxyFactory(MutableDocument.value(r),r,"")),mutableDocumentBridge.unregister(r);const o=writeTransaction(e);return await collectionUpdate(e,this.collection.name,o,i),await writeTransactionCommit(e,o),r["@ditto.updateResults"].slice()}then(t,e){return this.exec().then(t,e)}get query(){return`_id == ${Document.stringForID(this.documentID)}`}_observe(t,e,n){const i=e?this.subscribe():null;return new LiveQuery(this.query,null,null,[],-1,0,this.collection,i,n,((e,i,r)=>{if(e.length>1){const t=e.map((t=>Document.base64StringForID(t._id)));throw new Error(`Internal inconsistency, single document live query returned more than one document. Query: ${this.query}, documentIDs: ${t.join(", ")}.`)}if(!1===i.isInitial&&i.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===i.isInitial&&i.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===i.isInitial&&i.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===i.isInitial&&i.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===i.isInitial&&i.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===i.isInitial?0:i.insertions.length+i.deletions.length+i.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,s=!0===i.isInitial?void 0:i.oldDocuments[0],a=new SingleDocumentLiveQueryEvent(i.isInitial,s);n?t(o,a,r):t(o,a)}))}}class Collection{constructor(t,e){this.name=t,this.store=e}find(t,e){return new PendingCursorOperation(t,null!=e?e:null,this)}findAll(){return this.find("true")}findByID(t){const e=validateDocumentID(t);return new PendingIDSpecificOperation(e,this)}async insert(t,e={}){var n,i,r;const o=null!==(n=e.id)&&void 0!==n?n:t._id,s=null!==(i=e.isDefault)&&void 0!==i&&i,a=null!==(r=e.writeStrategy)&&void 0!==r?r:s?"insertDefaultIfAbsent":"overwrite";if(s&&e.writeStrategy&&"insertDefaultIfAbsent"!==e.writeStrategy)throw new Error("Incompatible isDefault and writeStrategy options.");const c=this.store.ditto,d=dittoBridge.pointerFor(c),u=void 0===o?void 0:validateDocumentID(o),l=void 0===u?null:CBOR.encode(u),h=desugarJSObject(t,!0),p=CBOR.encode(h),_=collectionInsertValue(d,this.name,p,l,a);return CBOR.decode(_)}newAttachment(t,e={}){const n=this.store.ditto,i=dittoBridge.pointerFor(n),{id:r,len:o,handle:s}=function(){if("string"==typeof t)return dittoNewAttachmentFromFile(i,t,"Copy");if(t instanceof Uint8Array)return dittoNewAttachmentFromBytes(i,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}`)}(),a=new AttachmentToken({_type:"ditto_attachment",_id:r,_len:o,_meta:{...e}}),c=new Attachment(n,a);return attachmentBridge.bridge(s,(()=>c),{throwIfAlreadyBridged:!0})}fetchAttachment(t,e){const n=this.store.ditto;return new AttachmentFetcher(n,t,e)}}function validateDocumentID(t){if(void 0===t)throw new Error(`Invalid document ID: ${t}`);return t}class CollectionsEvent{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}static initial(t){return new CollectionsEvent({isInitial:!0,collections:t,oldCollections:[],insertions:[],deletions:[],updates:[],moves:[]})}}class PendingCollectionsOperation{constructor(t){this.pendingCursorOperation=new PendingCursorOperation("true",null,new Collection("__collections",t)),this.store=t}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()}observe(t){return this.pendingCursorOperation.observe(((e,n)=>{const i=collectionsFromDocuments(e,this.store);let r;if(!0===n.isInitial)r=CollectionsEvent.initial(i);else{const t=collectionsFromDocuments(n.oldDocuments,this.store);r=new CollectionsEvent({isInitial:!1,collections:i,oldCollections:t,insertions:n.insertions,deletions:n.deletions,updates:n.updates,moves:n.moves})}t(r)}))}async exec(){return collectionsFromDocuments(await this.pendingCursorOperation.exec(),this.store)}then(t,e){return this.exec().then(t,e)}}function collectionsFromDocuments(t,e){const n=[];return t.forEach((t=>{const i=t.name;void 0!==i&&"string"==typeof i&&n.push(new Collection(i,e))})),n}class Store{constructor(t){this.ditto=t}collection(t){return new Collection(t,this)}collections(){return new PendingCollectionsOperation(this.ditto.store)}collectionNames(){return dittoGetCollectionNames(dittoBridge.pointerFor(this.ditto))}registerLiveQueryWebhook(t,e,n){const i=validateQuery(e),r=liveQueryWebhookRegister(dittoBridge.pointerFor(this.ditto),t,i,[],0,0,n);return CBOR.decode(r)}}class Observer{constructor(t,e){this.observerManager=t,this.token=e,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 PresenceManager{constructor(t){this.ditto=t,this.isRegistered=!1,this.currentRemotePeers=[],this.callbacksByPresenceToken={}}addObserver(t){this.registerIfNeeded();const e=this.generatePresenceToken();return this.callbacksByPresenceToken[e]=t,t(this.currentRemotePeers),e}removeObserver(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=[]}}generatePresenceToken(){let t;do{t=Math.ceil(Math.random()*Number.MAX_SAFE_INTEGER)}while(this.callbacksByPresenceToken.hasOwnProperty(t));return t}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 ObserverManager{constructor(t){this.ditto=t,this.isRegistered=!1,this.callbacksByToken={}}addObserver(t){this.registerIfNeeded();const e=this.generateToken();return this.callbacksByToken[e]=t,e}removeObserver(t){delete this.callbacksByToken[t],this.unregisterIfNeeded()}register(t,e){throw new Error("ObserverManager.register() is abstract and must either be assigned or implemented in a subclass.")}unregister(t){throw new Error("ObserverManager.unregister() is abstract and must either be assigned or implemented in a subclass.")}processCallback(...t){throw new Error("ObserverManager.processCallback() is abstract and must either be assigned or implemented in a subclass.")}hasObservers(){return Object.keys(this.callbacksByToken).length>0}registerIfNeeded(){if(!this.isRegistered){this.isRegistered=!0;const t=dittoBridge.pointerFor(this.ditto);this.register(t,this.handleCallback.bind(this))}}unregisterIfNeeded(){if(!this.hasObservers()&&this.isRegistered){this.isRegistered=!1;const t=dittoBridge.pointerFor(this.ditto);this.unregister(t)}}generateToken(){let t;do{t=Math.ceil(Math.random()*Number.MAX_SAFE_INTEGER)}while(this.callbacksByToken.hasOwnProperty(t));return t}handleCallback(...t){const e=this.processCallback(...t);this.notify(...e)}notify(...t){for(const e in this.callbacksByToken){(0,this.callbacksByToken[e])(...t)}}async finalize(t){await this.removeObserver(t)}}class TransportConditionsManager extends ObserverManager{register(t,e){return dittoRegisterTransportConditionChangedCallback(t,e)}unregister(t){return dittoRegisterTransportConditionChangedCallback(t,null)}processCallback(t,e){let n,i;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":i="Unknown";break;case"Ok":i="OK";break;case"GenericFailure":i="GenericFailure";break;case"AppInBackground":i="AppInBackground";break;case"MdnsFailure":i="MDNSFailure";break;case"TcpListenFailure":i="TCPListenFailure";break;case"NoBleCentralPermission":i="NoBLECentralPermission";break;case"NoBlePeripheralPermission":i="NoBLEPeripheralPermission";break;case"CannotEstablishConnection":i="CannotEstablishConnection";break;case"BleDisabled":i="BLEDisabled";break;case"NoBleHardware":i="NoBLEHardware";break;case"WifiDisabled":i="WiFiDisabled";break;case"TemporarilyUnavailable":i="TemporarilyUnavailable"}return[i,n]}}class Sync{constructor(t){this.bluetoothLETransportPointer=null,this.awdlTransportPointer=null,this.lanTransportPointer=null;const e={identity:t.identity,transportConfig:new TransportConfig,isWebValid:!1,isX509Valid:!1,isSyncEnabled:!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.updateGlobal(e,n),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.state=n}updatePeerToPeerBluetoothLE(t,e){const n=dittoBridge.pointerFor(this.ditto),i=t.effectiveTransportConfig.peerToPeer.bluetoothLE,r=e.effectiveTransportConfig.peerToPeer.bluetoothLE,o=!i.isEnabled&&r.isEnabled,s=i.isEnabled&&!r.isEnabled;if(o&&this.bluetoothLETransportPointer)throw new Error("Internal inconsistency, when starting BLE transport, no BLE transport pointer should exist.");if(s&&!this.bluetoothLETransportPointer)throw new Error("Internal inconsistency, when stopping BLE transport, a BLE transport pointer should exist.");if("linux"!==process.platform){if(o){if(!bleIsAvailable(n))throw new Error("Can't start P2P BluetoothLE transport because not available.");this.bluetoothLETransportPointer=bleCreate(n)}s&&(bleDestroy(this.bluetoothLETransportPointer),delete this.bluetoothLETransportPointer)}else{if(o){const t={clientTransport:ditto_add_internal_ble_client_transport(n),serverTransport:ditto_add_internal_ble_server_transport(n)};this.bluetoothLETransportPointer=t}if(s){const t=this.bluetoothLETransportPointer,{clientTransport:e,serverTransport:n}=t;ble_server_free_handle(n),ble_client_free_handle(e),this.bluetoothLETransportPointer=null}}}updatePeerToPeerAWDL(t,e){const n=dittoBridge.pointerFor(this.ditto),i=t.effectiveTransportConfig.peerToPeer.awdl,r=e.effectiveTransportConfig.peerToPeer.awdl,o=!i.isEnabled&&r.isEnabled,s=i.isEnabled&&!r.isEnabled;if(o&&this.awdlTransportPointer)throw new Error("Internal inconsistency, when starting AWDL transport, no AWDL transport pointer should exist.");if(s&&!this.awdlTransportPointer)throw new Error("Internal inconsistency, when stopping AWDL transport, an AWDL transport pointer should exist.");if(o){if(!awdlIsAvailable(n))throw new Error("Can't start P2P AWDL transport because not available.");this.awdlTransportPointer=awdlCreate(n)}s&&(awdlDestroy(this.awdlTransportPointer),this.awdlTransportPointer=null)}updatePeerToPeerLAN(t,e){const n=dittoBridge.pointerFor(this.ditto),i=t.effectiveTransportConfig.peerToPeer.lan,r=e.effectiveTransportConfig.peerToPeer.lan;if(i.isEnabled&&(i.isMdnsEnabled&&(lanDestroy(this.lanTransportPointer),delete this.lanTransportPointer),i.isMulticastEnabled&&dittoRemoveMulticastTransport(n)),r.isEnabled){if(r.isMdnsEnabled){if(!lanIsAvailable(n))throw new Error("Can't start P2P LAN transport because not available.");this.lanTransportPointer=lanCreate(n)}r.isMulticastEnabled&&dittoAddMulticastTransport(n)}}updateListenTCP(t,e){const n=t.effectiveTransportConfig.listen.tcp,i=e.effectiveTransportConfig.listen.tcp;if(TransportConfig.areListenTCPsEqual(i,n))return;const r=dittoBridge.pointerFor(this.ditto);n.isEnabled&&dittoStopTCPServer(r),i.isEnabled&&dittoStartTCPServer(r,`${i.interfaceIP}:${i.port}`)}updateListenHTTP(t,e){const n=t.effectiveTransportConfig.listen.http,i=e.effectiveTransportConfig.listen.http;if(TransportConfig.areListenHTTPsEqual(n,i))return;const r=dittoBridge.pointerFor(this.ditto);n.isEnabled&&dittoStopHTTPServer(r),i.isEnabled&&dittoStartHTTPServer(r,`${i.interfaceIP}:${i.port}`,i.staticContentPath||null,i.websocketSync?"Enabled":"Disabled",i.tlsCertificatePath||null,i.tlsKeyPath||null)}updateConnectTCPServers(t,e){const n=Object.getOwnPropertyNames(this.staticTCPClientsByAddress),i=e.effectiveTransportConfig.connect.tcpServers,r=new Set(i);for(const t of n)r.delete(t);const o=new Set(n);for(const t of i)o.delete(t);const s=r.values(),a=o.values();for(const t of s){const e=addStaticTCPClient(dittoBridge.pointerFor(this.ditto),t),n=staticTCPClientBridge.bridge(e);this.staticTCPClientsByAddress[t]=n}for(const t of a){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),i=e.effectiveTransportConfig.connect.websocketURLs.slice(),r=new Set(i);for(const t of n)r.delete(t);const o=new Set(n);for(const t of i)o.delete(t);const s=r.values(),a=o.values();for(const t of s){const e=addWebsocketClient(dittoBridge.pointerFor(this.ditto),t),n=websocketClientBridge.bridge(e);this.websocketClientsByURL[t]=n}for(const t of a){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){const e=t.transportConfig.copy(),n=t.identity,i=t.isSyncEnabled,r=t.isX509Valid,o=t.isWebValid;return e.connect.tcpServers,e.connect.websocketURLs,i&&r||(e.peerToPeer.bluetoothLE.isEnabled=!1,e.peerToPeer.awdl.isEnabled=!1,e.peerToPeer.lan.isEnabled=!1,e.listen.tcp.isEnabled=!1,e.connect.tcpServers=[]),i&&o||(e.listen.http.isEnabled=!1,e.connect.websocketURLs=[]),i&&o&&("online"===n.type||"onlinePlayground"===n.type)&&n.enableDittoCloudSync&&e.connect.websocketURLs.push(`wss://${n.appID}.cloud.ditto.live`),e.peerToPeer.lan.isEnabled&&!e.listen.tcp.isEnabled&&(e.listen.tcp.isEnabled=!0,e.listen.tcp.interfaceIP="[::]",e.listen.tcp.port=0),{underlyingSyncParameters:t,effectiveTransportConfig:e.freeze()}}class Ditto{constructor(t,e){this.isWebValid=!1,this.isX509Valid=!1;const n=e&&e.trim().length>0?e:"ditto",i=Object.freeze(this.validateIdentity(t));this.identity=Object.freeze(i),this.path=n;require("fs").mkdirSync(n,{recursive:!0});{const t=require("os");this.deviceName=t.hostname()}const r=uninitializedDittoMake(n);let o=null;const s=(()=>{var t,e;if("development"===i.type||"offlinePlayground"===i.type)return dittoAuthClientMakeForDevelopment(n,i.appID,null!==(t=i.siteID)&&void 0!==t?t:0);if("manual"===i.type||"production"===i.type)return dittoAuthClientMakeWithStaticX509(i.certificate);if("sharedKey"===i.type)return dittoAuthClientMakeWithSharedKey(n,i.appID,i.sharedKey,i.siteID);if("onlinePlayground"===i.type)return dittoAuthClientMakeForDevelopment(n,i.appID,0);if("onlineWithAuthentication"===i.type||"online"===i.type){const t=null!==(e=i.customAuthURL)&&void 0!==e?e:`https://${i.appID}.cloud.ditto.live`,r=dittoAuthClientMakeLoginProvider((t=>{this.auth?this.authenticationExpiring(t):o=t}));return dittoAuthClientMakeWithWeb(n,i.appID,t,r)}throw new Error(`Can't create Ditto, unsupported identity type: ${i}`)})();dittoAuthClientSetValidityListener(s,this.authClientValidityChanged.bind(this));const a=dittoAuthClientIsWebValid(s),c=dittoAuthClientIsX509Valid(s),d=dittoAuthClientGetSiteID(s),u=dittoMake(r,s);["onlineWithAuthentication","online"].includes(i.type)?this.auth=new OnlineWithAuthenticationAuthenticator(s):(dittoAuthClientFree(s),this.auth=new NotAvailableAuthenticator);const l=new TransportConfig;this.siteID=d,this.transportConfig=l.copy().freeze(),this.isX509Valid=c,this.isWebValid=a,this.sync=new Sync(this),this.sync.update({isSyncEnabled:!1,isX509Valid:c,isWebValid:a,identity:i,transportConfig:l}),this.isActivated=false,this.store=new Store(this),this.presenceManager=new PresenceManager(this),this.transportConditionsManager=new TransportConditionsManager(this);const h=dittoBridge.bridge(u,(()=>this));return null!==o&&this.authenticationExpiring(o),h}get sdkVersion(){return dittoGetSDKVersion(dittoBridge.pointerFor(this))}setLicenseToken(t){const{result:e,errorMessage:n}=verifyLicense(t);if("LicenseOk"!==e)throw this.isActivated=false,new Error(n);this.isActivated=!0}setAccessLicense(t){Logger.warning("Ditto.setAccessLicense() is deprecated, use setLicenseToken() instead."),this.setLicenseToken(t)}setTransportConfig(t){this.transportConfig,this.transportConfig=t.copy().freeze();const e=this.transportConfig,n=this.identity,i=this.isWebValid,r=this.isX509Valid;this.sync.update({transportConfig:e,identity:n,isWebValid:i,isX509Valid:r,isSyncEnabled:this.isSyncEnabled})}updateTransportConfig(t){const e=this.transportConfig.copy();return t(e),this.setTransportConfig(e),this}tryStartSync(){this.startSync()}startSync(){this.setSyncEnabled(!0)}stopSync(){this.setSyncEnabled(!1)}observePeers(t){const e=this.presenceManager.addObserver(t);return new Observer(this.presenceManager,e)}observeTransportConditions(t){const e=this.transportConditionsManager.addObserver(t);return new Observer(this.transportConditionsManager,e)}runGarbageCollection(){dittoRunGarbageCollection(dittoBridge.pointerFor(this))}authenticationExpiring(t){if("online"!==this.identity.type&&"onlineWithAuthentication"!==this.identity.type)throw new Error(`Internal inconsistency, authenticationExpiring() should only be called for identities of type 'onlineWithAuthentication' or 'online', but current identity is: ${this.identity.type}`);const e=this.auth,n=this.identity.authHandler;t>0?n.authenticationExpiringSoon(e,t):n.authenticationRequired(e)}authClientValidityChanged(t,e){const n=this.transportConfig,i=this.identity,r=this.isSyncEnabled;this.isX509Valid,this.isWebValid,this.isX509Valid=e,this.isWebValid=t,this.sync.update({transportConfig:n,identity:i,isWebValid:t,isX509Valid:e,isSyncEnabled:r})}validateIdentity(t){const e={...t};if(!["development","offlinePlayground","sharedKey","production","manual","onlinePlayground","online","onlineWithAuthentication"].includes(t.type))throw new Error(`Can't create Ditto instance, unknown identity type: ${t.type}`);if("development"!==t.type&&"offlinePlayground"!==t.type&&"sharedKey"!==t.type||void 0===t.appName||void 0===t.appID||(Logger.warning("Properties .appID and .appName (deprecated) are both given for identity, .appID will be used and .appName will be ignored."),delete e.appName),"development"!==t.type&&"offlinePlayground"!==t.type&&"sharedKey"!==t.type||void 0===t.appName||void 0!==t.appID||(Logger.warning("Property .appName of IdentityDevelopment and IdentitySharedKey is deprecated, use .appID instead."),e.appID=t.appName,delete e.appName),("development"===t.type||"offlinePlayground"===t.type||"sharedKey"===t.type)&&void 0===t.appName&&void 0===t.appID)throw new Error("Property .appID or the deprecated .appName must be given for identity, but aren't.");if(("development"===t.type||"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")}return t.type,"production"===t.type&&Logger.warning("IdentityProduction (type: 'production') is deprecated, please use IdentityManual instead."),t.type,t.type,"online"===t.type||t.type,e}setSyncEnabled(t){if(t&&!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 `setLicenseToken`. If you need to obtain a license token then please visit https://portal.ditto.live.");const e=dittoBridge.pointerFor(this);this.isSyncEnabled=t;const n=this.isWebValid,i=this.isX509Valid,r=this.identity,o=this.transportConfig;dittoSetDeviceName(e,this.deviceName),this.sync.update({identity:r,transportConfig:o,isWebValid:n,isX509Valid:i,isSyncEnabled:!!t})}}Ditto.webAssemblyModule=null;const dittoBridge=new Bridge(Ditto,dittoDrop);async function init(t={}){}switch(process.platform){case"android":initSDKVersion("Android","JavaScript","1.0.17");break;case"darwin":initSDKVersion("Mac","JavaScript","1.0.17");break;case"linux":initSDKVersion("Linux","JavaScript","1.0.17");break;case"win32":initSDKVersion("Windows","JavaScript","1.0.17");break;default:initSDKVersion("Unknown","JavaScript","1.0.17")}loggerInit(),exports.Attachment=Attachment,exports.AttachmentFetcher=AttachmentFetcher,exports.AttachmentToken=AttachmentToken,exports.Collection=Collection,exports.CollectionsEvent=CollectionsEvent,exports.Counter=Counter,exports.Ditto=Ditto,exports.Document=Document,exports.DocumentPath=DocumentPath,exports.LiveQuery=LiveQuery,exports.LiveQueryEventInitial=LiveQueryEventInitial,exports.LiveQueryEventUpdate=LiveQueryEventUpdate,exports.Logger=Logger,exports.MutableDocument=MutableDocument,exports.MutableDocumentPath=MutableDocumentPath,exports.NotAvailableAuthenticator=NotAvailableAuthenticator,exports.Observer=Observer,exports.OnlineWithAuthenticationAuthenticator=OnlineWithAuthenticationAuthenticator,exports.PendingCursorOperation=PendingCursorOperation,exports.PendingIDSpecificOperation=PendingIDSpecificOperation,exports.SingleDocumentLiveQueryEvent=SingleDocumentLiveQueryEvent,exports.Store=Store,exports.Subscription=Subscription,exports.TransportConfig=TransportConfig,exports.UpdateResult=UpdateResult,exports.UpdateResultsMap=UpdateResultsMap,exports.Value=Value,exports.__log=__log,exports.attachmentBridge=attachmentBridge,exports.dittoBridge=dittoBridge,exports.documentBridge=documentBridge,exports.init=init,exports.mutableDocumentBridge=mutableDocumentBridge;
2
2
  //# sourceMappingURL=ditto.cjs.js.map, content=
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dittolive/ditto",
3
- "version": "1.0.14",
3
+ "version": "1.0.17",
4
4
  "description": "Ditto is a cross-platform embeddable NoSQL database that can sync with or without an internet connection.",
5
5
  "homepage": "https://ditto.live",
6
6
  "license": "SEE LICENSE IN LICENSE.md",
package/playground.cjs CHANGED
@@ -27,16 +27,15 @@ and interact with Ditto directly, Example:
27
27
  const cars = ditto.store.collection('cars')
28
28
 
29
29
  // Insert an entry:
30
- const fordBlackID = new Ditto.DocumentID('ford-black-123')
31
- const fordBlack = {_id: fordBlackID, model: "Ford", color: "black"}
30
+ const fordBlack = {_id: 'ford-black-123', model: "Ford", color: "black"}
32
31
  await cars.insert(fordBlack)
33
32
 
34
33
  // Find an entry by ID:
35
- const foundFordBlack = await cars.findByID(fordBlackID)
34
+ const foundFordBlack = await cars.findByID('ford-black-123')
36
35
  console.log(foundFordBlack)
37
36
 
38
37
  // Remove an entry:
39
- await cars.findByID(fordBlackID).remove()
38
+ await cars.findByID('ford-black-123').remove()
40
39
  ----------------------------------------------
41
40
 
42
41
  `)