@interncom/diplomatic 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,7 +6,7 @@ import { EntIDB } from "./entdb/idb";
6
6
  import { EntDBMemory } from "./entdb/memory";
7
7
  import { useClient, useClientState, useClientXferState, useSyncOnResume } from "./react/useClient";
8
8
  import useStateWatcher, { useStateWatcherSuspense } from "./react/useStateWatcher";
9
- import { btoh, htob } from "./shared/binary";
9
+ import { b64tob, btob64, btoh, htob } from "./shared/binary";
10
10
  import { Clock } from "./shared/clock";
11
11
  import { Decoder, Encoder } from "./shared/codec";
12
12
  import { eidCodec, genSingletonEID } from "./shared/codecs/eid";
@@ -29,5 +29,5 @@ export declare function genWebClient(stateMgr: IStateManager, url: URL): Promise
29
29
  client: SyncClient<URL>;
30
30
  setSeed: (seedHex: string) => Promise<void>;
31
31
  }>;
32
- export { APLD_APPLIED, APLD_ERROR, APLD_PENDING, apldFromStored, btoh, CachedEntDB, Clock, crypto, Decoder, defaultPeekProgressEvery, eidCodec, Encoder, EntDBMemory, EntIDB, EntitiesQuery, EntityID, entStateManager, genSingletonEID, GroupID, hostHTTPTransport, htob, HTTPTransport, IDBStore, idleProgress, IEntDB, IEntity, isApldState, isPendingApply, isTerminalApplyFailure, IStore, MasterSeed, MemoryStore, nullEntDB, nullStateManager, openDiplomaticClient, openEntDB, openIDBStore, revFromEntity, revFromHead, setApld, shouldEmitItemProgress, SingletonStateManager, StateManager, Status, SyncClient, TypedEventEmitter, useClient, useClientState, useClientXferState, useStateWatcher, useStateWatcherSuspense, useSyncOnResume, WorkerClient, };
32
+ export { APLD_APPLIED, APLD_ERROR, APLD_PENDING, apldFromStored, b64tob, btob64, btoh, CachedEntDB, Clock, crypto, Decoder, defaultPeekProgressEvery, eidCodec, Encoder, EntDBMemory, EntIDB, EntitiesQuery, EntityID, entStateManager, genSingletonEID, GroupID, hostHTTPTransport, htob, HTTPTransport, IDBStore, idleProgress, IEntDB, IEntity, isApldState, isPendingApply, isTerminalApplyFailure, IStore, MasterSeed, MemoryStore, nullEntDB, nullStateManager, openDiplomaticClient, openEntDB, openIDBStore, revFromEntity, revFromHead, setApld, shouldEmitItemProgress, SingletonStateManager, StateManager, Status, SyncClient, TypedEventEmitter, useClient, useClientState, useClientXferState, useStateWatcher, useStateWatcherSuspense, useSyncOnResume, WorkerClient, };
33
33
  export type { ApldState, Applier, HostHandle, IClient, ICrypto, IDeleteParams, IDiplomaticClientState, IEntRev, IHostConnectionInfo, IHostRow, IMessage, IMutateOp, IOp, IStateManager, IStoredMessage, IStoredMessageData, IStoredMessageWrite, ITransport, IUpdateParams, OpenDiplomaticClientMainOptions, OpenDiplomaticClientOptions, OpenDiplomaticClientWorkerOptions, OpenedDiplomaticClient, OpenEntDBOptions, SyncProgressEvent, WorkerClientOptions, };
@@ -1 +1 @@
1
- function r$(V){let $=V.length,Q=0,Z=0;while(Z<$){let J=V.charCodeAt(Z++);if((J&4294967168)===0){Q++;continue}else if((J&4294965248)===0)Q+=2;else{if(J>=55296&&J<=56319){if(Z<$){let I=V.charCodeAt(Z);if((I&64512)===56320)++Z,J=((J&1023)<<10)+(I&1023)+65536}}if((J&4294901760)===0)Q+=3;else Q+=4}}return Q}function JZ(V,$,Q){let Z=V.length,J=Q,I=0;while(I<Z){let W=V.charCodeAt(I++);if((W&4294967168)===0){$[J++]=W;continue}else if((W&4294965248)===0)$[J++]=W>>6&31|192;else{if(W>=55296&&W<=56319){if(I<Z){let Y=V.charCodeAt(I);if((Y&64512)===56320)++I,W=((W&1023)<<10)+(Y&1023)+65536}}if((W&4294901760)===0)$[J++]=W>>12&15|224,$[J++]=W>>6&63|128;else $[J++]=W>>18&7|240,$[J++]=W>>12&63|128,$[J++]=W>>6&63|128}$[J++]=W&63|128}}var IZ=new TextEncoder,WZ=50;function YZ(V,$,Q){IZ.encodeInto(V,$.subarray(Q))}function c$(V,$,Q){if(V.length>WZ)YZ(V,$,Q);else JZ(V,$,Q)}var XZ=4096;function pV(V,$,Q){let Z=$,J=Z+Q,I=[],W="";while(Z<J){let Y=V[Z++];if((Y&128)===0)I.push(Y);else if((Y&224)===192){let X=V[Z++]&63;I.push((Y&31)<<6|X)}else if((Y&240)===224){let X=V[Z++]&63,G=V[Z++]&63;I.push((Y&31)<<12|X<<6|G)}else if((Y&248)===240){let X=V[Z++]&63,G=V[Z++]&63,K=V[Z++]&63,w=(Y&7)<<18|X<<12|G<<6|K;if(w>65535)w-=65536,I.push(w>>>10&1023|55296),w=56320|w&1023;I.push(w)}else I.push(Y);if(I.length>=XZ)W+=String.fromCharCode(...I),I.length=0}if(I.length>0)W+=String.fromCharCode(...I);return W}var GZ=new TextDecoder,KZ=200;function MZ(V,$,Q){let Z=V.subarray($,$+Q);return GZ.decode(Z)}function d$(V,$,Q){if(Q>KZ)return MZ(V,$,Q);else return pV(V,$,Q)}class y0{type;data;constructor(V,$){this.type=V,this.data=$}}class e extends Error{constructor(V){super(V);let $=Object.create(e.prototype);Object.setPrototypeOf(this,$),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}}var b0=4294967295;function o$(V,$,Q){let Z=Q/4294967296,J=Q;V.setUint32($,Z),V.setUint32($+4,J)}function NV(V,$,Q){let Z=Math.floor(Q/4294967296),J=Q;V.setUint32($,Z),V.setUint32($+4,J)}function RV(V,$){let Q=V.getInt32($),Z=V.getUint32($+4);return Q*4294967296+Z}function a$(V,$){let Q=V.getUint32($),Z=V.getUint32($+4);return Q*4294967296+Z}var wZ=-1,NZ=4294967295,RZ=17179869183;function zZ({sec:V,nsec:$}){if(V>=0&&$>=0&&V<=RZ)if($===0&&V<=NZ){let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,V),Q}else{let Q=V/4294967296,Z=V&4294967295,J=new Uint8Array(8),I=new DataView(J.buffer);return I.setUint32(0,$<<2|Q&3),I.setUint32(4,Z),J}else{let Q=new Uint8Array(12),Z=new DataView(Q.buffer);return Z.setUint32(0,$),NV(Z,4,V),Q}}function FZ(V){let $=V.getTime(),Q=Math.floor($/1000),Z=($-Q*1000)*1e6,J=Math.floor(Z/1e9);return{sec:Q+J,nsec:Z-J*1e9}}function UZ(V){if(V instanceof Date){let $=FZ(V);return zZ($)}else return null}function OZ(V){let $=new DataView(V.buffer,V.byteOffset,V.byteLength);switch(V.byteLength){case 4:{let Q=$.getUint32(0),Z=0;return{sec:Q,nsec:0}}case 8:{let Q=$.getUint32(0),Z=$.getUint32(4),J=(Q&3)*4294967296+Z,I=Q>>>2;return{sec:J,nsec:I}}case 12:{let Q=RV($,4),Z=$.getUint32(0);return{sec:Q,nsec:Z}}default:throw new e(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${V.length}`)}}function qZ(V){let $=OZ(V);return new Date($.sec*1000+$.nsec/1e6)}var s$={type:wZ,encode:UZ,decode:qZ};class p0{static defaultCodec=new p0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(s$)}register({type:V,encode:$,decode:Q}){if(V>=0)this.encoders[V]=$,this.decoders[V]=Q;else{let Z=-1-V;this.builtInEncoders[Z]=$,this.builtInDecoders[Z]=Q}}tryToEncode(V,$){for(let Q=0;Q<this.builtInEncoders.length;Q++){let Z=this.builtInEncoders[Q];if(Z!=null){let J=Z(V,$);if(J!=null){let I=-1-Q;return new y0(I,J)}}}for(let Q=0;Q<this.encoders.length;Q++){let Z=this.encoders[Q];if(Z!=null){let J=Z(V,$);if(J!=null)return new y0(Q,J)}}if(V instanceof y0)return V;return null}decode(V,$,Q){let Z=$<0?this.builtInDecoders[-1-$]:this.decoders[$];if(Z)return Z(V,$,Q);else return new y0($,V)}}function HZ(V){return V instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&V instanceof SharedArrayBuffer}function t0(V){if(V instanceof Uint8Array)return V;else if(ArrayBuffer.isView(V))return new Uint8Array(V.buffer,V.byteOffset,V.byteLength);else if(HZ(V))return new Uint8Array(V);else return Uint8Array.from(V)}var PZ=100,CZ=2048;class zV{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??p0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.maxDepth=V?.maxDepth??PZ,this.initialBufferSize=V?.initialBufferSize??CZ,this.sortKeys=V?.sortKeys??!1,this.forceFloat32=V?.forceFloat32??!1,this.ignoreUndefined=V?.ignoreUndefined??!1,this.forceIntegerToFloat=V?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new zV({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(V){if(this.entered)return this.clone().encodeSharedRef(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(V){if(this.entered)return this.clone().encode(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(V,$){if($>this.maxDepth)throw Error(`Too deep objects in depth ${$}`);if(V==null)this.encodeNil();else if(typeof V==="boolean")this.encodeBoolean(V);else if(typeof V==="number")if(!this.forceIntegerToFloat)this.encodeNumber(V);else this.encodeNumberAsFloat(V);else if(typeof V==="string")this.encodeString(V);else if(this.useBigInt64&&typeof V==="bigint")this.encodeBigInt64(V);else this.encodeObject(V,$)}ensureBufferSizeToWrite(V){let $=this.pos+V;if(this.view.byteLength<$)this.resizeBuffer($*2)}resizeBuffer(V){let $=new ArrayBuffer(V),Q=new Uint8Array($),Z=new DataView($);Q.set(this.bytes),this.view=Z,this.bytes=Q}encodeNil(){this.writeU8(192)}encodeBoolean(V){if(V===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber(V){if(!this.forceIntegerToFloat&&Number.isSafeInteger(V))if(V>=0)if(V<128)this.writeU8(V);else if(V<256)this.writeU8(204),this.writeU8(V);else if(V<65536)this.writeU8(205),this.writeU16(V);else if(V<4294967296)this.writeU8(206),this.writeU32(V);else if(!this.useBigInt64)this.writeU8(207),this.writeU64(V);else this.encodeNumberAsFloat(V);else if(V>=-32)this.writeU8(224|V+32);else if(V>=-128)this.writeU8(208),this.writeI8(V);else if(V>=-32768)this.writeU8(209),this.writeI16(V);else if(V>=-2147483648)this.writeU8(210),this.writeI32(V);else if(!this.useBigInt64)this.writeU8(211),this.writeI64(V);else this.encodeNumberAsFloat(V);else this.encodeNumberAsFloat(V)}encodeNumberAsFloat(V){if(this.forceFloat32)this.writeU8(202),this.writeF32(V);else this.writeU8(203),this.writeF64(V)}encodeBigInt64(V){if(V>=BigInt(0))this.writeU8(207),this.writeBigUint64(V);else this.writeU8(211),this.writeBigInt64(V)}writeStringHeader(V){if(V<32)this.writeU8(160+V);else if(V<256)this.writeU8(217),this.writeU8(V);else if(V<65536)this.writeU8(218),this.writeU16(V);else if(V<4294967296)this.writeU8(219),this.writeU32(V);else throw Error(`Too long string: ${V} bytes in UTF-8`)}encodeString(V){let Q=r$(V);this.ensureBufferSizeToWrite(5+Q),this.writeStringHeader(Q),c$(V,this.bytes,this.pos),this.pos+=Q}encodeObject(V,$){let Q=this.extensionCodec.tryToEncode(V,this.context);if(Q!=null)this.encodeExtension(Q);else if(Array.isArray(V))this.encodeArray(V,$);else if(ArrayBuffer.isView(V))this.encodeBinary(V);else if(typeof V==="object")this.encodeMap(V,$);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply(V)}`)}encodeBinary(V){let $=V.byteLength;if($<256)this.writeU8(196),this.writeU8($);else if($<65536)this.writeU8(197),this.writeU16($);else if($<4294967296)this.writeU8(198),this.writeU32($);else throw Error(`Too large binary: ${$}`);let Q=t0(V);this.writeU8a(Q)}encodeArray(V,$){let Q=V.length;if(Q<16)this.writeU8(144+Q);else if(Q<65536)this.writeU8(220),this.writeU16(Q);else if(Q<4294967296)this.writeU8(221),this.writeU32(Q);else throw Error(`Too large array: ${Q}`);for(let Z of V)this.doEncode(Z,$+1)}countWithoutUndefined(V,$){let Q=0;for(let Z of $)if(V[Z]!==void 0)Q++;return Q}encodeMap(V,$){let Q=Object.keys(V);if(this.sortKeys)Q.sort();let Z=this.ignoreUndefined?this.countWithoutUndefined(V,Q):Q.length;if(Z<16)this.writeU8(128+Z);else if(Z<65536)this.writeU8(222),this.writeU16(Z);else if(Z<4294967296)this.writeU8(223),this.writeU32(Z);else throw Error(`Too large map object: ${Z}`);for(let J of Q){let I=V[J];if(!(this.ignoreUndefined&&I===void 0))this.encodeString(J),this.doEncode(I,$+1)}}encodeExtension(V){if(typeof V.data==="function"){let Q=V.data(this.pos+6),Z=Q.length;if(Z>=4294967296)throw Error(`Too large extension object: ${Z}`);this.writeU8(201),this.writeU32(Z),this.writeI8(V.type),this.writeU8a(Q);return}let $=V.data.length;if($===1)this.writeU8(212);else if($===2)this.writeU8(213);else if($===4)this.writeU8(214);else if($===8)this.writeU8(215);else if($===16)this.writeU8(216);else if($<256)this.writeU8(199),this.writeU8($);else if($<65536)this.writeU8(200),this.writeU16($);else if($<4294967296)this.writeU8(201),this.writeU32($);else throw Error(`Too large extension object: ${$}`);this.writeI8(V.type),this.writeU8a(V.data)}writeU8(V){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,V),this.pos++}writeU8a(V){let $=V.length;this.ensureBufferSizeToWrite($),this.bytes.set(V,this.pos),this.pos+=$}writeI8(V){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,V),this.pos++}writeU16(V){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,V),this.pos+=2}writeI16(V){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,V),this.pos+=2}writeU32(V){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,V),this.pos+=4}writeI32(V){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,V),this.pos+=4}writeF32(V){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,V),this.pos+=4}writeF64(V){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,V),this.pos+=8}writeU64(V){this.ensureBufferSizeToWrite(8),o$(this.view,this.pos,V),this.pos+=8}writeI64(V){this.ensureBufferSizeToWrite(8),NV(this.view,this.pos,V),this.pos+=8}writeBigUint64(V){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,V),this.pos+=8}writeBigInt64(V){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,V),this.pos+=8}}function m0(V,$){return new zV($).encodeSharedRef(V)}function FV(V){return`${V<0?"-":""}0x${Math.abs(V).toString(16).padStart(2,"0")}`}var TZ=16,DZ=16;class lV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(V=TZ,$=DZ){this.maxKeyLength=V,this.maxLengthPerKey=$,this.caches=[];for(let Q=0;Q<this.maxKeyLength;Q++)this.caches.push([])}canBeCached(V){return V>0&&V<=this.maxKeyLength}find(V,$,Q){let Z=this.caches[Q-1];V:for(let J of Z){let I=J.bytes;for(let W=0;W<Q;W++)if(I[W]!==V[$+W])continue V;return J.str}return null}store(V,$){let Q=this.caches[V.length-1],Z={bytes:V,str:$};if(Q.length>=this.maxLengthPerKey)Q[Math.random()*Q.length|0]=Z;else Q.push(Z)}decode(V,$,Q){let Z=this.find(V,$,Q);if(Z!=null)return this.hit++,Z;this.miss++;let J=pV(V,$,Q),I=Uint8Array.prototype.slice.call(V,$,$+Q);return this.store(I,J),J}}var hV="array",VV="map_key",e$="map_value",AZ=(V)=>{if(typeof V==="string"||typeof V==="number")return V;throw new e("The type of key must be string or number but "+typeof V)};class VQ{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(V){let $=this.getUninitializedStateFromPool();$.type=hV,$.position=0,$.size=V,$.array=Array(V)}pushMapState(V){let $=this.getUninitializedStateFromPool();$.type=VV,$.readCount=0,$.size=V,$.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let V={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(V)}return this.stack[this.stackHeadPosition]}release(V){if(this.stack[this.stackHeadPosition]!==V)throw Error("Invalid stack state. Released state is not on top of the stack.");if(V.type===hV){let Q=V;Q.size=0,Q.array=void 0,Q.position=0,Q.type=void 0}if(V.type===VV||V.type===e$){let Q=V;Q.size=0,Q.map=void 0,Q.readCount=0,Q.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var e0=-1,rV=new DataView(new ArrayBuffer(0)),_Z=new Uint8Array(rV.buffer);try{rV.getInt8(0)}catch(V){if(!(V instanceof RangeError))throw Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var t$=RangeError("Insufficient data"),jZ=new lV;class UV{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=rV;bytes=_Z;headByte=e0;stack=new VQ;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??p0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.rawStrings=V?.rawStrings??!1,this.maxStrLength=V?.maxStrLength??b0,this.maxBinLength=V?.maxBinLength??b0,this.maxArrayLength=V?.maxArrayLength??b0,this.maxMapLength=V?.maxMapLength??b0,this.maxExtLength=V?.maxExtLength??b0,this.keyDecoder=V?.keyDecoder!==void 0?V.keyDecoder:jZ,this.mapKeyConverter=V?.mapKeyConverter??AZ}clone(){return new UV({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=e0,this.stack.reset()}setBuffer(V){let $=t0(V);this.bytes=$,this.view=new DataView($.buffer,$.byteOffset,$.byteLength),this.pos=0}appendBuffer(V){if(this.headByte===e0&&!this.hasRemaining(1))this.setBuffer(V);else{let $=this.bytes.subarray(this.pos),Q=t0(V),Z=new Uint8Array($.length+Q.length);Z.set($),Z.set(Q,$.length),this.setBuffer(Z)}}hasRemaining(V){return this.view.byteLength-this.pos>=V}createExtraByteError(V){let{view:$,pos:Q}=this;return RangeError(`Extra ${$.byteLength-Q} of ${$.byteLength} byte(s) found at buffer[${V}]`)}decode(V){if(this.entered)return this.clone().decode(V);try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);let $=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return $}finally{this.entered=!1}}*decodeMulti(V){if(this.entered){yield*this.clone().decodeMulti(V);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(V){if(this.entered)return this.clone().decodeAsync(V);try{this.entered=!0;let $=!1,Q;for await(let W of V){if($)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(W);try{Q=this.doDecodeSync(),$=!0}catch(Y){if(!(Y instanceof RangeError))throw Y}this.totalPos+=this.pos}if($){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Q}let{headByte:Z,pos:J,totalPos:I}=this;throw RangeError(`Insufficient data in parsing ${FV(Z)} at ${I} (${J} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(V){return this.decodeMultiAsync(V,!0)}decodeStream(V){return this.decodeMultiAsync(V,!1)}async*decodeMultiAsync(V,$){if(this.entered){yield*this.clone().decodeMultiAsync(V,$);return}try{this.entered=!0;let Q=$,Z=-1;for await(let J of V){if($&&Z===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(J),Q)Z=this.readArraySize(),Q=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--Z===0)break}catch(I){if(!(I instanceof RangeError))throw I}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){V:while(!0){let V=this.readHeadByte(),$;if(V>=224)$=V-256;else if(V<192)if(V<128)$=V;else if(V<144){let Z=V-128;if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V<160){let Z=V-144;if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else{let Z=V-160;$=this.decodeString(Z,0)}else if(V===192)$=null;else if(V===194)$=!1;else if(V===195)$=!0;else if(V===202)$=this.readF32();else if(V===203)$=this.readF64();else if(V===204)$=this.readU8();else if(V===205)$=this.readU16();else if(V===206)$=this.readU32();else if(V===207)if(this.useBigInt64)$=this.readU64AsBigInt();else $=this.readU64();else if(V===208)$=this.readI8();else if(V===209)$=this.readI16();else if(V===210)$=this.readI32();else if(V===211)if(this.useBigInt64)$=this.readI64AsBigInt();else $=this.readI64();else if(V===217){let Z=this.lookU8();$=this.decodeString(Z,1)}else if(V===218){let Z=this.lookU16();$=this.decodeString(Z,2)}else if(V===219){let Z=this.lookU32();$=this.decodeString(Z,4)}else if(V===220){let Z=this.readU16();if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else if(V===221){let Z=this.readU32();if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else if(V===222){let Z=this.readU16();if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V===223){let Z=this.readU32();if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V===196){let Z=this.lookU8();$=this.decodeBinary(Z,1)}else if(V===197){let Z=this.lookU16();$=this.decodeBinary(Z,2)}else if(V===198){let Z=this.lookU32();$=this.decodeBinary(Z,4)}else if(V===212)$=this.decodeExtension(1,0);else if(V===213)$=this.decodeExtension(2,0);else if(V===214)$=this.decodeExtension(4,0);else if(V===215)$=this.decodeExtension(8,0);else if(V===216)$=this.decodeExtension(16,0);else if(V===199){let Z=this.lookU8();$=this.decodeExtension(Z,1)}else if(V===200){let Z=this.lookU16();$=this.decodeExtension(Z,2)}else if(V===201){let Z=this.lookU32();$=this.decodeExtension(Z,4)}else throw new e(`Unrecognized type byte: ${FV(V)}`);this.complete();let Q=this.stack;while(Q.length>0){let Z=Q.top();if(Z.type===hV)if(Z.array[Z.position]=$,Z.position++,Z.position===Z.size)$=Z.array,Q.release(Z);else continue V;else if(Z.type===VV){if($==="__proto__")throw new e("The key __proto__ is not allowed");Z.key=this.mapKeyConverter($),Z.type=e$;continue V}else if(Z.map[Z.key]=$,Z.readCount++,Z.readCount===Z.size)$=Z.map,Q.release(Z);else{Z.key=null,Z.type=VV;continue V}}return $}}readHeadByte(){if(this.headByte===e0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=e0}readArraySize(){let V=this.readHeadByte();switch(V){case 220:return this.readU16();case 221:return this.readU32();default:if(V<160)return V-144;else throw new e(`Unrecognized array type byte: ${FV(V)}`)}}pushMapState(V){if(V>this.maxMapLength)throw new e(`Max length exceeded: map length (${V}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(V)}pushArrayState(V){if(V>this.maxArrayLength)throw new e(`Max length exceeded: array length (${V}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(V)}decodeString(V,$){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String(V,$);return this.decodeBinary(V,$)}decodeUtf8String(V,$){if(V>this.maxStrLength)throw new e(`Max length exceeded: UTF-8 byte length (${V}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+$+V)throw t$;let Q=this.pos+$,Z;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached(V))Z=this.keyDecoder.decode(this.bytes,Q,V);else Z=d$(this.bytes,Q,V);return this.pos+=$+V,Z}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===VV;return!1}decodeBinary(V,$){if(V>this.maxBinLength)throw new e(`Max length exceeded: bin length (${V}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(V+$))throw t$;let Q=this.pos+$,Z=this.bytes.subarray(Q,Q+V);return this.pos+=$+V,Z}decodeExtension(V,$){if(V>this.maxExtLength)throw new e(`Max length exceeded: ext length (${V}) > maxExtLength (${this.maxExtLength})`);let Q=this.view.getInt8(this.pos+$),Z=this.decodeBinary(V,$+1);return this.extensionCodec.decode(Z,Q,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let V=this.view.getUint8(this.pos);return this.pos++,V}readI8(){let V=this.view.getInt8(this.pos);return this.pos++,V}readU16(){let V=this.view.getUint16(this.pos);return this.pos+=2,V}readI16(){let V=this.view.getInt16(this.pos);return this.pos+=2,V}readU32(){let V=this.view.getUint32(this.pos);return this.pos+=4,V}readI32(){let V=this.view.getInt32(this.pos);return this.pos+=4,V}readU64(){let V=a$(this.view,this.pos);return this.pos+=8,V}readI64(){let V=RV(this.view,this.pos);return this.pos+=8,V}readU64AsBigInt(){let V=this.view.getBigUint64(this.pos);return this.pos+=8,V}readI64AsBigInt(){let V=this.view.getBigInt64(this.pos);return this.pos+=8,V}readF32(){let V=this.view.getFloat32(this.pos);return this.pos+=4,V}readF64(){let V=this.view.getFloat64(this.pos);return this.pos+=8,V}}function cV(V,$){return new UV($).decode(V)}class C0{listeners=new Map;addEventListener(V,$){let Q=this.listeners.get(V);if(!Q)Q=new Set,this.listeners.set(V,Q);return Q.add($),()=>{this.removeEventListener(V,$)}}removeEventListener(V,$){let Q=this.listeners.get(V);if(Q){if(Q.delete($),Q.size===0)this.listeners.delete(V)}}emit(V,$){let Q=this.listeners.get(V);if(Q){let Z=Array.from(Q);for(let J of Z)J($)}}emitAll(V){let $=Array.from(this.listeners.keys());for(let Q of $)this.emit(Q,V)}}class G0{getter;static eventName="update";emitter;constructor(V){this.getter=V;this.emitter=new C0}get=()=>this.getter();async emit(){let V=await this.getter();queueMicrotask(()=>this.emitter.emit(G0.eventName,V))}listen(V){return this.emitter.addEventListener(G0.eventName,V),()=>{this.emitter.removeEventListener(G0.eventName,V)}}}var T0=64;var $Q=32,D0=8;var OV=32;var QQ=30000,ZQ=512,_;((C)=>{C[C.Success=0]="Success";C[C.InvalidSignature=3]="InvalidSignature";C[C.ClockOutOfSync=4]="ClockOutOfSync";C[C.UserNotRegistered=5]="UserNotRegistered";C[C.ServerMisconfigured=6]="ServerMisconfigured";C[C.MissingBody=7]="MissingBody";C[C.ExtraBodyContent=8]="ExtraBodyContent";C[C.MissingParam=9]="MissingParam";C[C.InvalidParam=10]="InvalidParam";C[C.InvalidRequest=11]="InvalidRequest";C[C.InternalError=12]="InternalError";C[C.NotFound=13]="NotFound";C[C.InvalidMessage=14]="InvalidMessage";C[C.NoChange=15]="NoChange";C[C.DatabaseClosed=16]="DatabaseClosed";C[C.StorageError=17]="StorageError";C[C.DatabaseError=18]="DatabaseError";C[C.HashMismatch=19]="HashMismatch";C[C.DecryptionError=20]="DecryptionError";C[C.NotImplemented=21]="NotImplemented";C[C.MissingSeed=22]="MissingSeed";C[C.OutOfBounds=23]="OutOfBounds";C[C.HostError=24]="HostError";C[C.CommunicationError=25]="CommunicationError";C[C.VarLimitExceeded=26]="VarLimitExceeded";C[C.InvalidResponse=27]="InvalidResponse";C[C.ConnectionClosed=28]="ConnectionClosed"})(_||={});function q(V){return[V,0]}function M(V){return[void 0,V]}function LZ(V){if(V<0)console.info("N",V),console.trace();if(typeof V!=="bigint")V=BigInt(V);if(V<0n)return M(10);let $=[];while(V>0n){let Q=Number(V&0x7fn);if(V>>=7n,V>0n)$.push(Q|128);else $.push(Q)}if($.length===0)return q(new Uint8Array([0]));if($.length>8)return M(26);return q(new Uint8Array($))}function mZ(V,$=0){let Q=0n,Z=0,J=$;while(!0){if(J>=V.length)return M(14);let I=V[J++];if(I===void 0)return M(14);if(Q|=BigInt(I&127)<<BigInt(Z),(I&128)===0){if(J-$>8)return M(26);return q({value:Q>0x1fffffffffffffn?Q:Number(Q),bytesRead:J-$})}if(Z+=7,Z>=56)return M(26)}}class f{data;pos=0;constructor(V){this.data=V}static async fromResponse(V){let $=await V.arrayBuffer(),Q=new Uint8Array($);return new f(Q)}readBigInt(){if(this.pos+8>this.data.length)return M(7);let V=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,q(V)}readDate(){let[V,$]=this.readVarInt();if($!==0)return M($);return q(new Date(V))}readVarInt(){let[V,$]=mZ(this.data,this.pos);if($!==0)return M($);this.pos+=V.bytesRead;let Q=V.value;return q(typeof Q==="bigint"?Number(Q):Q)}readVarString(){let[V,$]=this.readVarInt();if($!==0)return M($);let[Q,Z]=this.readBytes(V);if(Z!==0)return M(Z);let J=new TextDecoder().decode(Q);return q(J)}readBytes(V){if(V<0)return M(10);if(this.pos+V>this.data.length)return M(23);let $=this.data.slice(this.pos,this.pos+V);return this.pos+=V,q($)}readVarBytes(){let[V,$]=this.readVarInt();if($!==0)return M($);return this.readBytes(V)}readStruct(V){return V.decode(this)}readStructs(V){let $=[];while(!this.done()){let[Q,Z]=this.readStruct(V);if(Z!==0)return M(Z);$.push(Q)}return q($)}readBytesSeq(V){let $=[];while(!this.done()){let[Q,Z]=this.readBytes(V);if(Z!==0)return M(Z);$.push(Q)}return q($)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class k{parts=[];writeBigInt(V){let $=new Uint8Array(8);new DataView($.buffer).setBigUint64(0,V,!1),this.parts.push($)}writeDate(V){let $=V.getTime();return this.writeVarInt($)}writeVarInt(V){let[$,Q]=LZ(V);if(Q!==0)return Q;return this.parts.push($),0}writeVarString(V){let $=new TextEncoder().encode(V),Q=this.writeVarInt($.length);if(Q!==0)return Q;return this.writeBytes($),0}prependBytes(V){this.parts.unshift(V)}writeBytes(V){this.parts.push(V)}writeVarBytes(V){let $=this.writeVarInt(V.length);if($!==0)return $;return this.writeBytes(V),0}writeStruct(V,$){return V.encode(this,$)}writeStructs(V,$){for(let Q of $){let Z=this.writeStruct(V,Q);if(Z!==0)return Z}return 0}writeBytesSeq(V){for(let $ of V)this.writeBytes($)}result(){let V=this.parts.reduce((Z,J)=>Z+J.length,0),$=new Uint8Array(V),Q=0;for(let Z of this.parts)$.set(Z,Q),Q+=Z.length;return $}*scan(){for(let V of this.parts)yield V}}async function dV(V,$,Q){let Z=new k,J=Z.writeDate($);if(J!==0)return M(J);let I=Z.result(),W=await Q.signEd25519(I,V.privateKey);return q({pubKey:V.publicKey,sig:W,timestamp:$})}async function A0(V,$,Q){let Z=Q.now().getTime(),J=V.timestamp.getTime();if(Math.abs(Z-J)>QQ)return 4;let W=new k;W.writeDate(V.timestamp);let Y=W.result();if(!await $.checkSigEd25519(V.sig,Y,V.pubKey))return 3;return 0}var r={encode(V,$){let Q=V.writeVarBytes($.id);if(Q!==0)return Q;let Z=V.writeDate($.ts);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return M(Q);let[Z,J]=V.readDate();if(J!==0)return M(J);return q({id:$,ts:Z})}};function l0(V){let $=new k,Q=$.writeStruct(r,V);if(Q!==0)return M(Q);let Z=$.result();return q(Z)}async function EZ(V){return l0({id:V,ts:new Date(0)})}var Y0={encode(V,$){let Q=V.writeVarBytes($.eid);if(Q!==0)return Q;let Z=V.writeVarInt($.off);if(Z!==0)return Z;let J=V.writeVarInt($.ctr);if(J!==0)return J;let I=V.writeVarInt($.len);if(I!==0)return I;if($.hsh)V.writeBytes($.hsh);return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return M(Q);let Z=new f($),[,J]=r.decode(Z);if(J!==0)return M(J);let[I,W]=V.readVarInt();if(W!==0)return M(W);let[Y,X]=V.readVarInt();if(X!==0)return M(X);let[G,K]=V.readVarInt();if(K!==0)return M(K);let w;if(G>0){let[N,z]=V.readBytes(OV);if(z!==0)return M(z);w=N}return q({eid:$,off:I,ctr:Y,len:G,hsh:w})}};function a(V){return Array.from(V).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}function _0(V){if(V.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(V.length/2);for(let Q=0;Q<V.length;Q+=2)$[Q/2]=Number.parseInt(V.substr(Q,2),16);return $}function s(V,$){if(V===$)return!0;if(V.byteLength!==$.byteLength)return!1;return V.every((Q,Z)=>Q===$[Z])}var L;if(typeof Uint8Array.prototype.toBase64==="function")L=(V)=>V.toBase64();else L=(V)=>btoa(String.fromCharCode(...V));var X0;if(typeof Uint8Array.fromBase64==="function")X0=(V)=>Uint8Array.fromBase64(V);else X0=(V)=>Uint8Array.from(atob(V),($)=>$.charCodeAt(0));function $V(V,$){let Q=new Uint8Array(V.length+$.length);return Q.set(V,0),Q.set($,V.length),Q}function JQ(V,$,Q){return Q.checkSigEd25519(V.sig,V.headCph,$)}async function oV(V,$,Q){let Z=$V($.privateKey,V);return(await Q.blake3(Z)).slice(0,D0)}async function IQ(V,$,Q,Z){let J;if(V.bod&&V.len>0)J=await Q.blake3(V.bod);let I=new k,W=Y0.encode(I,{...V,hsh:J});if(W!==0)return M(W);let Y=I.result(),X=await oV(Y,$,Q),G=await Z.deriveFromKDM(X),K=await Q.encryptXSalsa20Poly1305Combined(Y,G),w=V.bod?await Q.encryptXSalsa20Poly1305Combined(V.bod,G):new Uint8Array(0),N=await Q.signEd25519(K,$.privateKey);return q({sig:N,kdm:X,headCph:K,bodyCph:w})}async function aV(V,$,Q,Z,J){let I=new f(V),[W,Y]=Y0.decode(I);if(Y!==0)return M(14);let X;try{X=$&&$.length>0?await Z.decryptXSalsa20Poly1305Combined($,Q):void 0}catch{return M(20)}let G=W.hsh&&X===void 0,K=W.hsh===void 0&&X!==void 0;if(G||K)return M(19);if(W.hsh&&X){let N=await Z.blake3(X);if(!s(N,W.hsh))return M(19)}let w=J??await Z.blake3(V);return q({msgHead:W,bod:X,headHash:w})}class R0{now(){return new Date}}function WQ(V,$,Q,Z){let J=$.getTime()-V.getTime(),I=Q.getTime()-Z.getTime();return(J+I)/2}var QV={encode(V,$){if(V.writeVarInt($.quota),$.quota>0){if($.usage===void 0)return 9;V.writeVarInt($.usage)}return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return M(Q);let Z;if($>0){let[J,I]=V.readVarInt();if(I!==0)return M(I);Z=J}return q({quota:$,usage:Z})}};var sV={encode(V,$){V.writeBytes(new Uint8Array([$.status]));let Q=V.writeDate($.timeRcvd);if(Q!==0)return Q;let Z=V.writeDate($.timeSent);if(Z!==0)return Z;let J=V.writeVarInt($.subscription.term);if(J!==0)return J;let I=V.writeVarInt($.subscription.elapsed);if(I!==0)return I;let W=V.writeStruct(QV,$.subscription.stat);if(W!==0)return W;let Y=V.writeStruct(QV,$.subscription.dyn);if(Y!==0)return Y;return 0},decode(V){let[$,Q]=V.readBytes(1);if(Q!==0)return M(Q);let Z=$[0],[J,I]=V.readDate();if(I!==0)return M(I);let[W,Y]=V.readDate();if(Y!==0)return M(Y);let[X,G]=V.readVarInt();if(G!==0)return M(G);let[K,w]=V.readVarInt();if(w!==0)return M(w);let[N,z]=V.readStruct(QV);if(z!==0)return M(z);let[F,R]=V.readStruct(QV);if(R!==0)return M(R);return q({status:Z,timeRcvd:J,timeSent:W,subscription:{term:X,elapsed:K,stat:N,dyn:F}})}};async function tV(V,$,Q){let{crypto:Z,enclave:J}=V,I=await J.derive($,Q);return await Z.deriveEd25519KeyPair(I)}var eV={encode(V,$){let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarInt($.seq);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return M(Q);let[Z,J]=V.readVarInt();if(J!==0)return M(J);return q({headCph:$,seq:Z})}};var Z0={encode(V,$){V.writeBytes($.pubKey),V.writeBytes($.sig);let Q=V.writeDate($.timestamp);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readBytes($Q);if(Q!==0)return M(Q);let[Z,J]=V.readBytes(T0);if(J!==0)return M(J);let[I,W]=V.readDate();if(W!==0)return M(W);return q({pubKey:$,sig:Z,timestamp:I})}};var YQ={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct(Z0,Q);if(I!==0)return I;for(let W of Z)J.writeVarInt(W);return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct(Z0);if(Y!==0)return Y;let X=await A0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W,[K,w]=await I.hasUser(G);if(w!==0)return w;if(!K)return 5;let[N,z]=$.readVarInt();if(z!==0)return z;if(!$.done())return 8;let[F,R]=await I.listHeads(G,N);if(R!==0)return R;return Q.writeStructs(eV,F)},decodeResp(V){return V.readStructs(eV)}};var V$={encode(V,$){V.writeVarInt($.seq);let Q=V.writeVarBytes($.bodyCph);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return M(Q);let[Z,J]=V.readVarBytes();if(J!==0)return M(J);return q({seq:$,bodyCph:Z})}};var XQ={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct(Z0,Q);if(I!==0)return I;for(let W of Z){let Y=J.writeVarInt(W);if(Y!==0)return Y}return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct(Z0);if(Y!==0)return Y;let X=await A0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W,[K,w]=await I.hasUser(G);if(w!==0)return w;if(!K)return 5;let N=[];while(!$.done()){let[R,U]=$.readVarInt();if(U!==0)return U;N.push(R)}console.info(`PULL: ${N.length} bags`);let[z,F]=await I.getBodies(G,N);if(F!==0)return F;if(!z)return 17;for(let{seq:R,bodyCph:U}of z){let H={seq:R,bodyCph:U},P=Q.writeStruct(V$,H);if(P!==0)return P}return 0},decodeResp(V){return V.readStructs(V$)}};var $$={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarBytes($.bodyCph);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readBytes(T0);if(Q!==0)return M(Q);let[Z,J]=V.readBytes(D0);if(J!==0)return M(J);let[I,W]=V.readVarBytes();if(W!==0)return M(W);let[Y,X]=V.readVarBytes();if(X!==0)return M(X);return q({sig:$,kdm:Z,headCph:I,bodyCph:Y})}};var qV={encode(V,$){let Q=V.writeVarInt($.seq);if(Q!==0)return Q;let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=$.bodyCph?$.bodyCph.length:0,I=V.writeVarInt(J);if(I!==0)return I;if(J>0){if(!$.bodyCph)return 10;V.writeBytes($.bodyCph)}return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return M(Q);let[Z,J]=V.readVarBytes();if(J!==0)return M(J);let[I,W]=V.readVarInt();if(W!==0)return M(W);let Y;if(I>0){let[X,G]=V.readBytes(I);if(G!==0)return M(G);Y=X}return q({seq:$,headCph:Z,bodyCph:Y})}};var HV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readBytes(T0);if(Q!==0)return M(Q);let[Z,J]=V.readBytes(D0);if(J!==0)return M(J);let[I,W]=V.readVarBytes();if(W!==0)return M(W);return q({sig:$,kdm:Z,headCph:I})}};var PV={encode(V,$){if(V.writeVarInt($.idx),V.writeBytes(new Uint8Array([$.status])),$.status===0)V.writeVarInt($.seq);return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return M(Q);let[Z,J]=V.readBytes(1);if(J!==0)return M(J);let I=Z[0];if(I!==0)return q({idx:$,status:I});let[W,Y]=V.readVarInt();if(Y!==0)return M(Y);return q({idx:$,status:I,seq:W})}};var GQ={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct(Z0,Q);if(I!==0)return I;let W=J.writeStructs($$,Z);if(W!==0)return W;return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I,notifier:W}=V,[Y,X]=$.readStruct(Z0);if(X!==0)return X;let G=await A0(Y,J,Z);if(G!==0)return G;let{pubKey:K}=Y,[w,N]=await I.hasUser(K);if(N!==0)return N;if(!w)return 5;let[z,F]=$.readStructs($$);if(F!==0)return F;console.info(`PUSH: ${z.length} bags`);let R=[],U=[];for(let O=0;O<z.length;O++){let A=z[O];if(!await JQ(A,K,J)){let x={idx:O,status:3},S=Q.writeStruct(PV,x);if(S!==0)return S;continue}R.push(O),U.push(A)}let[H,P]=await I.setBags(K,U);if(P!==0)return P;if(!H||H.length!==U.length)return 17;let D=[];for(let O=0;O<U.length;O++){let A=U[O],m=R[O],x=H[O],S=new k,E=S.writeStruct(HV,A);if(E!==0)return E;let B=S.result(),C={seq:x,headCph:B};if(z.length===1&&A.bodyCph.length<=ZQ)C.bodyCph=A.bodyCph;D.push(C);let g={idx:m,status:0,seq:x},v=Q.writeStruct(PV,g);if(v!==0)return v}if(D.length>0){let O=new k,A=O.writeStructs(qV,D);if(A!==0)return A;let m=O.result();await Promise.resolve(W.push(K,m))}return 0},decodeResp(V){return V.readStructs(PV)}};var KQ={async encodeReq(V,$,Q,Z,J){return J.writeStruct(Z0,Q)},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct(Z0);if(Y!==0)return Y;let X=await A0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W;if(!$.done())return 8;let[K,w]=await I.addUser(G);if(w!==0)return w;return 0},decodeResp(V){return q(void 0)}};class Q${url;websocket;constructor(V){this.url=V}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(V,$,Q=()=>{},Z=()=>{}){let{url:J}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let I=new k;I.writeStruct(Z0,V);let W=I.result(),Y=a(W);return J.searchParams.set("t",Y),this.websocket=new WebSocket(J),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),Z()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Q()},this.websocket.onmessage=(X)=>{let G=new Uint8Array(X.data);$(G)},this.websocket.onerror=(X)=>{console.log(`ERROR: ${JSON.stringify(X)}`),this.websocket=void 0,Q()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var c={user:{path:"/user",endpoint:KQ,name:0},push:{path:"/push",endpoint:GQ,name:2},peek:{path:"/peek",endpoint:YQ,name:1},pull:{path:"/pull",endpoint:XQ,name:3}},SZ={0:c.user,2:c.push,1:c.peek,3:c.pull},fY={[c.user.path]:c.user,[c.push.path]:c.push,[c.peek.path]:c.peek,[c.pull.path]:c.pull};class Z${url;listener;constructor(V){this.url=V;this.listener=new Q$(V)}async call(V,$){let{path:Q}=SZ[V],Z=new URL(Q,this.url);try{return await fZ(Z,$)}catch{return M(25)}}}var CV=(V)=>{return new Z$(V.handle)};async function fZ(V,$){let Q=await fetch(V,{method:"POST",body:$.result().slice()});if(!Q.ok)return M(24);let Z=await f.fromResponse(Q);return q(Z)}class TV{enclave;crypto;host;clock;transport;updateHostMeta;constructor(V,$,Q,Z,J,I){this.enclave=V;this.crypto=$;this.host=Q;this.clock=Z;this.transport=J;this.updateHostMeta=I}async call(V,$){let{clock:Q,crypto:Z,transport:J}=this,{endpoint:I,name:W}=V,Y=await this.keys(),X=Q.now(),[G,K]=await dV(Y,X,Z);if(K!==0)return M(K);let w=new k,N=await I.encodeReq(this,Y,G,$,w);if(N!==0)return M(N);let z=Q.now(),[F,R]=await J.call(W,w),U=Q.now();if(R!==0)return M(R);let[H,P]=F.readStruct(sV);if(P!==0)return M(P);if(H.status!==0)return M(H.status);let O={clockOffset:WQ(z,H.timeRcvd,H.timeSent,U),subscription:H.subscription},A=await this.updateHostMeta(O);if(A!==0)return M(A);return I.decodeResp(F)}keys=()=>{let{host:V}=this;return tV(this,V.label,V.idx)};seal=async(V)=>{let{crypto:$,enclave:Q}=this,Z=await this.keys();return IQ(V,Z,$,Q)};register=()=>this.call(c.user,[]);peek=(V)=>this.call(c.peek,[V]);push=(V)=>this.call(c.push,V);pull=(V)=>this.call(c.pull,V);listen=async(V,$,Q)=>{let{clock:Z,crypto:J,host:I,transport:W}=this,{listener:Y}=W,X=await tV(this,I.label,I.idx),G=Z.now(),[K,w]=await dV(X,G,J);if(w!==0)return w;return await Y.connect(K,V,$,Q)};isConnected(){let V=this.transport?.listener;if(V&&typeof V.connected==="function")return V.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var J$={encode(V,$){let Q=V.writeVarString($.lbl);if(Q!==0)return Q;let Z=V.writeVarInt($.idx);if(Z!==0)return Z;let J=V.writeVarInt($.num);if(J!==0)return J;return V.writeBytes($.hsh),V.writeBytes($.sig),0},decode(V){let[$,Q]=V.readVarString();if(Q!==0)return M(Q);let[Z,J]=V.readVarInt();if(J!==0)return M(J);let[I,W]=V.readVarInt();if(W!==0)return M(W);let[Y,X]=V.readBytes(OV);if(X!==0)return M(X);let[G,K]=V.readBytes(T0);if(K!==0)return M(K);return q({lbl:$,idx:Z,num:I,hsh:Y,sig:G})}};var I$={encode(V,$){let Q=V.writeStruct(J$,$.head);if(Q!==0)return Q;let Z=V.writeVarBytes($.indexEnc);if(Z!==0)return Z;let J=V.writeVarBytes($.bodyEnc);if(J!==0)return J;return 0},decode(V){let[$,Q]=V.readStruct(J$);if(Q!==0)return M(Q);let[Z,J]=V.readVarBytes();if(J!==0)return M(J);let[I,W]=V.readVarBytes();if(W!==0)return M(W);return q({head:$,indexEnc:Z,bodyEnc:I})}};var W$={encode(V,$){V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarInt($.lenBody);if(Z!==0)return Z;if($.lenBody>0&&$.offBody!==void 0){let J=V.writeVarInt($.offBody);if(J!==0)return J}return 0},decode(V){let[$,Q]=V.readBytes(D0);if(Q!==0)return M(Q);let[Z,J]=V.readVarBytes();if(J!==0)return M(J);let[I,W]=V.readVarInt();if(W!==0)return M(W);let Y;if(I>0){let[X,G]=V.readVarInt();if(G!==0)return M(G);Y=X}return q({kdm:$,headCph:Z,lenBody:I,offBody:Y})}};async function MQ(V,$,Q,Z,J){let I=await J.derive(V,$),W=await Z.deriveEd25519KeyPair(I),Y=new k,X=new k,G=0,K=0;for(let P of Q){let D=new k,O=D.writeStruct(Y0,P.head);if(O!==0)return M(O);let A=D.result(),m=await oV(A,W,Z),x=await J.deriveFromKDM(m),S=await Z.encryptXSalsa20Poly1305Combined(A,x),E=P.body?await Z.encryptXSalsa20Poly1305Combined(P.body,x):new Uint8Array(0),B=P.head.len>0&&P.head.hsh!==void 0?E.length:0,C={kdm:m,headCph:S,lenBody:B,offBody:B>0?K:void 0},g=Y.writeStruct(W$,C);if(g!==0)return M(g);if(P.body)X.writeBytes(E),K+=E.length;G++}let w=X.result(),N=Y.result(),z=await Z.blake3(N),F=await Z.signEd25519(z,W.privateKey),R={lbl:V,idx:$,num:G,hsh:z,sig:F},U=new k;U.writeStruct(I$,{head:R,indexEnc:N,bodyEnc:w});let H=U.result();return q(H)}async function wQ(V,$,Q){let[Z,J]=I$.decode(new f(V));if(J!==0)return M(J);let{head:I,indexEnc:W,bodyEnc:Y}=Z,X=await Q.derive(I.lbl,I.idx),G=await $.deriveEd25519KeyPair(X);if(!await $.checkSigEd25519(I.sig,I.hsh,G.publicKey))return M(3);let w=await $.blake3(W);if(!s(w,I.hsh))return M(19);let N=new f(W),z=[];for(let R=0;R<I.num;R++){let[U,H]=N.readStruct(W$);if(H!==0)return M(H);z.push(U)}if(z.length!==I.num)return M(14);let F=[];for(let R of z){let U=await Q.deriveFromKDM(R.kdm),H=await $.decryptXSalsa20Poly1305Combined(R.headCph,U),[P,D]=Y0.decode(new f(H));if(D!==0)return M(D);let O;if(R.lenBody>0&&R.offBody!==void 0){if(P.hsh===void 0)return M(14);let A=Y.slice(R.offBody,R.offBody+R.lenBody);O=await $.decryptXSalsa20Poly1305Combined(A,U);let m=await $.blake3(O);if(!s(m,P.hsh))return M(19)}F.push({head:P,body:O})}return q(F)}async function NQ({now:V,bod:$,crypto:Q}){let Z=await Q.genRandomBytes(8),J=new k,I=J.writeStruct(r,{id:Z,ts:V});if(I!==0)return M(I);let W=J.result();return DV({now:V,eid:W,ctr:0,bod:$,crypto:Q})}async function DV({now:V,eid:$,ctr:Q,bod:Z,crypto:J}){let I=new f($),[W,Y]=r.decode(I);if(Y!==0)return M(Y);let X=V.getTime()-W.ts.getTime(),G,K=Z?.length??0;if(Z&&K>0)G=await J.blake3(Z);return q({eid:$,off:X,ctr:Q,len:K,hsh:G})}var CX=Symbol("EntityID");function RQ(V){return"type"in V}var TX=Symbol("MasterSeed"),DX=Symbol("DerivationSeed"),AX=Symbol("PublicKey"),_X=Symbol("PrivateKey"),jX=Symbol("HostSpecificKeyPair"),LX=Symbol("Hash");function xZ(V){if(!V)return!1;if(typeof V!=="object")return!1;if("body"in V===!1)return!1;if("type"in V===!1)return!1;return!0}function kZ(V){if(!V.bod||V.bod.length===0){let Z={off:V.off,ctr:V.ctr,eid:V.eid};return q(Z)}let $=cV(V.bod);if(xZ($)===!1)return console.warn("msg body invalid",$),M(14);let Q={off:V.off,ctr:V.ctr,eid:V.eid,gid:$.gid,pid:$.pid,type:$.type,body:$.body};return q(Q)}class ZV{applier;emitter=new C0;clearer;onDirtyEids;cacheDriven;peerIngest;constructor(V,$,Q,Z){this.applier=V;this.clearer=$,this.onDirtyEids=Q,this.cacheDriven=Z?.cacheDriven??!1,this.peerIngest=Z?.peerIngest}apply=async(V)=>{let $=[],Q=[];for(let Y of V){let[X,G]=kZ(Y);if(Q.push(G),G!==0)continue;$.push(X)}let{stats:Z,types:J,eids:I}=await this.applier($),W=[];for(let Y=0;Y<V.length;Y++){let X=Q[Y],G=Z[Y];if(X!==0){W.push(X);continue}if(G!==0){W.push(G);continue}W.push(0)}if(!this.cacheDriven)for(let Y of J)this.emitter.emit(Y,null);if(I.length>0)this.onDirtyEids?.(I);return W};clear=async()=>{let V=await this.clearer();if(V!==0)return V;return this.emitter.emitAll(null),V};notify=(V)=>{for(let $ of V)this.emitter.emit($,null)};refresh=async(V)=>{if(this.peerIngest){await this.peerIngest(V);return}};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}var Y$={apply:async function(V){return V.map(()=>0)},clear:async function(){return 0},notify:function(V){},refresh:async function(V){},on:function(V,$){},off:function(V,$){}};var n="entities",AV="entity_type_created_at",X$="entity_type_updated_at",G$="entity_type_group_id",K$="entity_type_parent_id";function BZ(V){let $={bod:V.body,crd:V.createdAt,...V.ctr!==0?{ctr:V.ctr}:{},eid:L(V.eid),gid:V.gid,pid:V.pid?L(V.pid):void 0,typ:V.type,upd:V.updatedAt};if($.gid===void 0)delete $.gid;if($.pid===void 0)delete $.pid;if($.ctr===void 0)delete $.ctr;return $}function h0(V){return{body:V.bod,createdAt:V.crd,updatedAt:V.upd,ctr:V.ctr??0,type:V.typ,eid:X0(V.eid),gid:V.gid,pid:V.pid?X0(V.pid):void 0}}class M${db;async init(){this.db=await new Promise((V,$)=>{let Q=indexedDB.open("db",11);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!J)throw Error("Transaction is null during upgrade");if(!Z.objectStoreNames.contains(n))Z.createObjectStore(n,{keyPath:"eid",autoIncrement:!1});let I=J.objectStore(n);if(!I.indexNames.contains(AV))I.createIndex(AV,["typ","crd"],{unique:!1});if(!I.indexNames.contains(X$))I.createIndex(X$,["typ","upd"],{unique:!1});if(!I.indexNames.contains(G$))I.createIndex(G$,["typ","gid"],{unique:!1});if(!I.indexNames.contains(K$))I.createIndex(K$,["typ","pid"],{unique:!1})},Q.onsuccess=()=>V(Q.result),Q.onerror=()=>$(Q.error)})}apply=async(V)=>{let $=new Set,Q=[];if(!this.db)return{stats:V.map(()=>16),types:$,eids:Q};let Z=this.db.transaction(n,"readwrite"),J=Z.objectStore(n);return new Promise((I)=>{let W=Array(V.length).fill(0);if(V.length<1){I({stats:[],types:$,eids:Q});return}Z.oncomplete=()=>{I({stats:W,types:$,eids:Q})},Z.onerror=()=>{for(let X=0;X<W.length;X++)if(W[X]===void 0)W[X]=18;I({stats:W,types:$,eids:Q})};let Y=new Map;for(let X=0;X<V.length;X++){let G=V[X],K=L(G.eid),w={op:G,index:X},N=Y.get(K);if(N)N.push(w);else Y.set(K,[w])}for(let[X,G]of Y){if(G.length<1)continue;let K=J.get(X);K.onsuccess=()=>{let w=K.result,N=w?h0(w):void 0,z=!1;for(let{op:F,index:R}of G){let[U,H]=r0(N,F);if(H!==0){W[R]=H;continue}if(z=!0,U)$.add(U.type);else if(N)$.add(N.type);N=U}if(z)Q.push(G[0].op.eid);if(N){let F=BZ(N),R=J.put(F);R.onerror=(U)=>{U.preventDefault();for(let{index:H}of G)W[H]=18}}else{let F=J.delete(X);F.onerror=()=>{for(let{index:R}of G)W[R]=18}}},K.onerror=()=>{for(let{index:w}of G)W[w]=18}}})};async clear(){if(!this.db)return 16;let V=this.db.transaction(n,"readwrite"),$=V.objectStore(n);return new Promise((Q)=>{V.oncomplete=()=>Q(0),V.onerror=()=>Q(18),$.clear()})}async getEnt(V){if(!this.db)return M(16);let $=L(V),Z=this.db.transaction(n,"readonly").objectStore(n);return new Promise((J)=>{let I=Z.get($);I.onsuccess=()=>{let W=I.result;if(!W)J(q(void 0));else{let Y=h0(W);J(q(Y))}},I.onerror=()=>J(M(18))})}async getAllOfTypeUpdatedBetween(V,$,Q){if(!this.db)return M(16);let J=this.db.transaction(n,"readonly").objectStore(n).index(X$);return new Promise((I)=>{let W=J.getAll(IDBKeyRange.bound([V,$],[V,Q]));W.onsuccess=()=>{let Y=W.result;I(q(Y.map(h0)))},W.onerror=()=>I(M(18))})}async getGroupMembers(V,$){if(!this.db)return M(16);let Z=this.db.transaction(n,"readonly").objectStore(n).index(G$);return new Promise((J)=>{let I=Z.getAll(IDBKeyRange.only([V,$]));I.onsuccess=()=>{let W=I.result;J(q(W.map(h0)))},I.onerror=()=>J(M(18))})}async getAllOfType(V){if(!this.db)return M(16);let Q=this.db.transaction(n,"readonly").objectStore(n).index(AV);return new Promise((Z)=>{let J=Q.getAll(IDBKeyRange.bound([V],[V,[]]));J.onsuccess=()=>{let I=J.result;Z(q(I.map(h0)))},J.onerror=()=>Z(M(18))})}async getAllEntities(V){if(!this.db)return M(16);if("pid"in V){let $=L(V.pid),Z=this.db.transaction(n,"readonly").objectStore(n).index(K$);return new Promise((J)=>{let I=Z.getAll(IDBKeyRange.only([V.type,$]));I.onsuccess=()=>{let Y=I.result.map(h0);J(q(Y))},I.onerror=()=>J(M(18))})}else if("gid"in V)return await this.getGroupMembers(V.type,V.gid);else if("updatedBetween"in V)return await this.getAllOfTypeUpdatedBetween(V.type,V.updatedBetween.start,V.updatedBetween.end);return await this.getAllOfType(V.type)}async getEntities(V){let[$,Q]=await this.getAllEntities(V);if(Q!==0)return M(Q);return q($)}async countEntities({type:V}){if(!this.db)return M(16);let Q=this.db.transaction(n,"readonly").objectStore(n).index(AV);return new Promise((Z)=>{let J=IDBKeyRange.bound([V],[V,[]]),I=Q.count(J);I.onsuccess=()=>Z(q(I.result)),I.onerror=()=>Z(M(18))})}}async function zQ(){let V=new M$;return await V.init(),V}class _V{ents=new Map;constructor(V=[]){for(let $ of V){let Q=L($.eid);this.ents.set(Q,$)}}async apply(V){let $=new Set,Q=[],Z=[];for(let J of V){let I=L(J.eid),W=this.ents.get(I),[Y,X]=r0(W,J);if(X!==0){Z.push(X);continue}if(Y)$.add(Y.type);else if(W)$.add(W.type);if(Y)this.ents.set(I,Y);else this.ents.delete(I);Q.push(J.eid),Z.push(0)}return{stats:Z,types:$,eids:Q}}async clear(){return this.ents.clear(),0}async getEnt(V){let $=L(V),Q=this.ents.get($);return q(Q)}async getAllEntities({type:V,gid:$,pid:Q,updatedBetween:Z}){let J=[];if(Q!==void 0){for(let I of this.ents.values())if(I.type===V&&I.pid&&s(I.pid,Q))J.push(I)}else if($!==void 0){for(let I of this.ents.values())if(I.type===V&&(typeof I.gid==="string"&&I.gid===$))J.push(I)}else if(Z!==void 0){for(let I of this.ents.values())if(I.type===V&&I.updatedAt>=Z.start&&I.updatedAt<=Z.end)J.push(I)}else for(let I of this.ents.values())if(I.type===V)J.push(I);return q(J)}async getEntities(V){let[$,Q]=await this.getAllEntities(V);if(Q!==0)return M(Q);return q($)}async countEntities({type:V}){let $=0;for(let Q of this.ents.values())if(Q.type===V)$+=1;return q($)}}async function w$(V){let $=await zQ();if(V?.cache===!1)return $;return new JV($)}class JV{mem;durable;warmed=new Set;listeners=new Set;chain=Promise.resolve();constructor(V,$){if(this.durable=V,this.mem=new _V($??[]),$)for(let Q of $)this.warmed.add(Q.type)}subscribe(V){return this.listeners.add(V),()=>{this.listeners.delete(V)}}emit(V){if(V.size<1)return;for(let $ of this.listeners)$(V)}run(V){let $=this.chain.then(V,V);return this.chain=$.then(()=>{return},()=>{return}),$}apply(V){return this.run(async()=>{let $=nZ(this.mem.ents,V);this.emit($.types);let Q=await this.durable.apply(V),{changed:Z,status:J}=await this.pullEids(V.map((I)=>I.eid));this.emit(Z);for(let I of Q.types)this.warmed.add(I);if(J!==0)return{stats:V.map(()=>J),types:Q.types,eids:Q.eids};return Q})}clear(){return this.run(async()=>{let V=await this.durable.clear();if(V!==0)return V;let $=this.mem.ents.size>0;return await this.mem.clear(),this.warmed.clear(),0})}ingestFromDurable(V){return this.run(async()=>{let{changed:$,status:Q}=await this.pullEids(V);return this.emit($),Q})}async pullEids(V){let $=new Set,Q=new Set;for(let Z of V){let J=L(Z);if(Q.has(J))continue;Q.add(J);let I=this.mem.ents.get(J),[W,Y]=await this.durable.getEnt(Z);if(Y!==0)return{changed:$,status:Y};if(W){if(this.mem.ents.set(J,W),this.warmed.add(W.type),!I||!gZ(I,W)){if($.add(W.type),I&&I.type!==W.type)$.add(I.type)}}else if(I)this.mem.ents.delete(J),$.add(I.type)}return{changed:$,status:0}}async warmType(V){if(this.warmed.has(V))return 0;let[$,Q]=await this.durable.getEntities({type:V});if(Q!==0)return Q;if($)for(let Z of $){let J=L(Z.eid),I=this.mem.ents.get(J);if(!I||uZ(Z,I))this.mem.ents.set(J,Z)}return this.warmed.add(V),0}async getEnt(V){let $=L(V);if(this.mem.ents.has($))return this.mem.getEnt(V);return this.run(async()=>{if(this.mem.ents.has($))return this.mem.getEnt(V);let[Q,Z]=await this.durable.getEnt(V);if(Z!==0)return M(Z);if(Q)this.mem.ents.set($,Q),this.warmed.add(Q.type);return q(Q)})}async getEntities(V){let $=await this.run(()=>this.warmType(V.type));if($!==0)return M($);return this.mem.getEntities(V)}async countEntities({type:V}){let $=await this.run(()=>this.warmType(V));if($!==0)return M($);return this.mem.countEntities({type:V})}}function gZ(V,$){if(V.ctr!==$.ctr)return!1;if(V.updatedAt.getTime()!==$.updatedAt.getTime())return!1;if(V.createdAt.getTime()!==$.createdAt.getTime())return!1;if(V.type!==$.type)return!1;if(V.gid!==$.gid)return!1;if(!s(V.eid,$.eid))return!1;if(!iZ(V.pid,$.pid))return!1;return vZ(V.body,$.body)}function iZ(V,$){if(V===void 0&&$===void 0)return!0;if(V===void 0||$===void 0)return!1;return s(V,$)}function vZ(V,$){if(Object.is(V,$))return!0;if(V instanceof Uint8Array&&$ instanceof Uint8Array)return s(V,$);if(V instanceof Date&&$ instanceof Date)return V.getTime()===$.getTime();try{return s(m0(V),m0($))}catch{return!1}}function uZ(V,$){let Q=V.updatedAt.getTime(),Z=$.updatedAt.getTime();if(Q!==Z)return Q>Z;return V.ctr>$.ctr}function nZ(V,$){let Q=new Set,Z=[];for(let J of $){let I=L(J.eid),W=V.get(I),[Y,X]=r0(W,J);if(X!==0){Z.push(X);continue}if(Y)Q.add(Y.type);else if(W)Q.add(W.type);if(Y)V.set(I,Y);else V.delete(I);Z.push(0)}return{stats:Z,types:Q}}function jV(V){if(V instanceof JV){let $=new ZV((Q)=>V.apply(Q),()=>V.clear(),void 0,{cacheDriven:!0,peerIngest:async(Q)=>{await V.ingestFromDurable(Q)}});return V.subscribe((Q)=>$.notify(Q)),$}return new ZV(($)=>V.apply($),()=>V.clear())}function yZ(V){return{eid:V.eid,ctr:V.ctr,updatedAt:V.updatedAt}}function N$(V){let $=new f(V.eid),[Q,Z]=$.readStruct(r);if(Z!==0)return M(Z);return q({eid:V.eid,ctr:V.ctr,updatedAt:new Date(Q.ts.getTime()+V.off)})}function r0(V,$){let Q=new f($.eid),[Z,J]=Q.readStruct(r);if(J!==0)return M(J);let I=new Date(Z.ts.getTime()+$.off);if(V!==void 0&&I<=V.updatedAt)return M(15);if(RQ($))return q({eid:$.eid,gid:$.gid,pid:$.pid,type:$.type,createdAt:Z.ts,updatedAt:I,ctr:$.ctr,body:$.body});else return q(void 0)}var bZ={getEnt:async()=>M(21),getEntities:async(V)=>M(21),countEntities:async()=>M(21),apply:async(V)=>({stats:V.map(()=>21),types:new Set,eids:[]}),clear:async()=>21};class LV{inflight=null;again=!1;run(V){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain(V),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain(V){try{this.again=!1;let $=await V();while(this.again)this.again=!1,$=await V();return $}finally{this.inflight=null}}}var mV=100;class IV{timer=null;delayMs;work;tail=new LV;constructor(V,$){this.delayMs=V<0?0:V,this.work=$}schedule(){if(this.delayMs<=0){this.fire();return}if(this.timer!==null)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=null,this.fire()},this.delayMs)}async flush(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null,this.fire();await this.tail.flush()}cancel(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null}fire(){return this.tail.run(this.work)}}function FQ(V){let $=new f(V.eid),[Q,Z]=r.decode($);if(Z!==0)return;return Q.ts.getTime()+V.off}function pZ(V,$){let Q=FQ(V),Z=FQ($);if(Q===void 0&&Z===void 0)return 0;if(Q===void 0)return 1;if(Z===void 0)return-1;if(Z!==Q)return Z-Q;return $.ctr-V.ctr}function WV(V,$){return V.slice().sort((Q,Z)=>pZ($(Q),$(Z)))}var E0={phase:"idle"},YV=50;function R$(V,$,Q){if(V<=0||$<=0)return!1;if(V===1||V===$)return!0;return V%Q===0}function EV(V,$){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(V,$);return}let Q=URL.createObjectURL(V),Z=document.createElement("a");Z.href=Q,Z.download=$,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(Q)}function UQ(V,$,Q){let Z=[],J=[],I=0;for(let W of V){let Y=$(W);if(J.length>0&&I+Y>Q)Z.push(J),J=[],I=0;if(J.push(W),I+=Y,I>=Q)Z.push(J),J=[],I=0}if(J.length>0)Z.push(J);return Z}async function OQ(V,$,Q){let Z=V.length;if(Z<1)return[];let J=Array(Z),I=0,W=Math.min(Math.max(1,$),Z),Y=async()=>{while(!0){let G=I;if(I+=1,G>=Z)return;J[G]=await Q(V[G],G)}},X=[];for(let G=0;G<W;G++)X.push(Y());return await Promise.all(X),J}async function z$(V,$,Q,Z){let J=new f(V.headCph),[I,W]=J.readStruct(HV);if(W!==0)return M(W);let{sig:Y,kdm:X,headCph:G}=I;if(!await Z.checkSigEd25519(Y,G,$.publicKey))return M(3);let w=await Q.deriveFromKDM(X),N;try{N=await Z.decryptXSalsa20Poly1305Combined(G,w)}catch{return M(20)}return q({kdm:X,headEnc:N})}var z0="f",j0="t",K0="e";function lZ(V){return V===z0||V===j0||V===K0}function XV(V){if(V===!0||V===j0)return j0;if(V===K0)return K0;return z0}function hZ(V){return XV(V.apld)===z0}function F$(V){return V!==0&&V!==15&&V!==18&&V!==17}function S0(V,$,Q){if(V.apld=$,$===K0&&Q!==void 0)V.err=Q;else delete V.err}async function L0(V,$,Q){let Z=XV($.apld),J=$.body,I=J?.length??0,W;if(J&&I>0)W=await Q.blake3(J);let Y={eid:$.eid,off:$.off??0,ctr:$.ctr??0,len:I,hsh:W},X={hash:V,head:Y,apld:Z};if(J!==void 0)X.body=J;if(Z===K0&&$.err!==void 0)X.err=$.err;return X}var U$=1048576,O$=1048576,rZ=64;function cZ(V){return V.sig.length+V.kdm.length+V.headCph.length+V.bodyCph.length}async function dZ(V,$,Q,Z,J){if(Z.length<1)return 0;let[I,W]=await V.push(Z);if(W!==0)return W;if(!I)return 27;for(let X of I){if(X.status!==0){console.error("push err",X);continue}let G=J[X.idx];if(!G){console.error("no hash",X);continue}await $.uploads.deq(Q,[G])}let Y=await $.hosts.get(Q);if(Y){let X=Y.lastSeq,G=X,K=[];for(let w of I)if(w.status===0)K.push(w.seq);K.sort((w,N)=>w-N);for(let w of K)if(w===X+1)X=w;if(X>G)await $.hosts.touch(Q,X)}return 0}async function qQ(V,$){if($.length<1)return q([]);let Q=new Map,Z=[];for(let Y of $)Q.set(Y.seq,Y),Z.push(Y.seq);let[J,I]=await V.pull(Z);if(I!==0)return M(I);if(!J)return M(27);let W=[];for(let{seq:Y,bodyCph:X}of J){let G=Q.get(Y);if(!G)continue;W.push({dl:G,bodyCph:X})}return q(W)}async function oZ(V,$,Q,Z){if(Z.length<1)return q({parts:[],hashes:[]});let J=[],I=[],W=[],Y=new Map;for(let{dl:G,bodyCph:K}of Z){let{head:w,kdm:N,seq:z,host:F}=G,[R,U]=await HQ(G,Q);if(U!==0||!R){let E=Y.get(F)??[];E.push(z),Y.set(F,E);continue}let{headEnc:H,headEncHash:P}=R,D=await $.deriveFromKDM(N),[O,A]=await aV(H,K,D,Q,P);if(A!==0||!O){let E=Y.get(F)??[];E.push(z),Y.set(F,E);continue}let m={head:w,body:O.bod},x=O.headHash;W.push({key:x,data:AQ(m)}),J.push(m),I.push(x);let S=Y.get(F)??[];S.push(z),Y.set(F,S)}let X=await V.messages.add(W);for(let[G,K]of Y)await V.downloads.deq(G,K);for(let G=0;G<X.length;G++){let K=X[G];if(K!==0&&K!==15)console.error("ERR storing",_[K],"for message",G)}return q({parts:J,hashes:I})}async function HQ(V,$){let Q=V.headEnc;if(!Q){let J=new k,I=J.writeStruct(Y0,V.head);if(I!==0)return M(I);Q=J.result()}if(V.headEncHash)return q({headEnc:Q,headEncHash:V.headEncHash});let Z=await $.blake3(Q);return q({headEnc:Q,headEncHash:Z})}async function PQ(V,$,Q){let Z=new Set;for(let W of $)Z.add(L(W));if(Z.size<1)return;let J=Array.from(await V.downloads.list());if(J.length<1)return;let I=new Map;for(let W of J){let Y;if(W.headEncHash)Y=L(W.headEncHash);else{let[G,K]=await HQ(W,Q);if(K!==0||!G)continue;Y=L(G.headEncHash)}if(!Z.has(Y))continue;let X=I.get(W.host)??[];X.push(W.seq),I.set(W.host,X)}for(let[W,Y]of I)await V.downloads.deq(W,Y)}async function CQ({conn:V,store:$,enclave:Q,host:Z,crypto:J,onProgress:I,peekProgressEvery:W,peekConcurrency:Y}){let X=await V.keys(),G=[],[K,w]=await V.peek(Z.lastSeq);if(w!==0)return w;let N=K.length,z=W??YV,F=Y??rZ;if(I&&N>0)I({phase:"peek",host:Z.label,done:0,total:N});let R=0,U=await OQ(K,F,async(H)=>{let[P,D]=await z$(H,X,Q,J),O;if(D!==0||!P)O={ok:!1,seq:H.seq,stat:D};else{let A=await J.blake3(P.headEnc);O={ok:!0,seq:H.seq,kdm:P.kdm,headEnc:P.headEnc,headEncHash:A}}if(R+=1,I&&R$(R,N,z))I({phase:"peek",host:Z.label,done:R,total:N});return O});for(let H of U){if(!H.ok){console.error("peek: decrypting item head",H.stat);continue}if(await $.messages.has(H.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await $.uploads.deq(Z.label,[H.headEncHash]),await $.downloads.deq(Z.label,[H.seq]);continue}let D=new f(H.headEnc),[O,A]=D.readStruct(Y0);if(A!==0){console.error("peek: reading item head",A);continue}G.push({kdm:H.kdm,head:O,seq:H.seq,host:Z.label,headEnc:H.headEnc,headEncHash:H.headEncHash})}if(await $.downloads.enq(G),K.length>0){let H=Math.max(...K.map((P)=>P.seq));await $.hosts.touch(Z.label,H)}if(I)I({phase:"peek",host:Z.label,done:N,total:N});return 0}async function TQ({conn:V,store:$,host:Q,maxPushBytes:Z,onProgress:J}){let I=Z??U$,W=await $.uploads.list(Q.label),Y=W.length,X=0;if(J&&Y>0)J({phase:"push",host:Q.label,done:0,total:Y});let G=[],K=[],w=0,N=async()=>{if(G.length<1)return 0;let z=G.length,F=await dZ(V,$,Q.label,G,K);if(G=[],K=[],w=0,F===0){if(X+=z,J)J({phase:"push",host:Q.label,done:X,total:Y})}return F};for(let z of W){let F=await $.messages.get(z);if(!F){X+=1;continue}let R={...F.head,bod:F.body},[U,H]=await V.seal(R);if(H!==0)return H;if(!U)return 12;let P=cZ(U);if(G.length>0&&w+P>I){let D=await N();if(D!==0)return D}if(G.push(U),K.push(z),w+=P,w>=I){let D=await N();if(D!==0)return D}}return N()}async function DQ({conn:V,store:$,enclave:Q,host:Z,crypto:J,maxPullBytes:I,onProgress:W},Y){let X=I??O$,G=await $.downloads.list(),K=Array.from(G).filter((U)=>U.host===Z.label);if(K.length<1)return 15;let w=WV(K,(U)=>U.head),N=UQ(w,(U)=>U.head.len,X),z=w.length,F=0;if(W)W({phase:"pull",host:Z.label,done:0,total:z});let R=qQ(V,N[0]);for(let U=0;U<N.length;U++){let[H,P]=await R;if(P!==0||!H)return P;if(F+=N[U].length,W)W({phase:"pull",host:Z.label,done:F,total:z});let D=N[U+1];if(D)R=qQ(V,D);if(W)W({phase:"open",host:Z.label,done:F,total:z});let O=WV(H,(m)=>m.dl.head),[,A]=await oZ($,Q,J,O);if(A!==0)return A;if(Y){if(W)W({phase:"exec",host:Z.label,done:F,total:z});await Y()}}return 0}function AQ({head:V,body:$}){let Q={eid:V.eid,body:$,apld:z0};if(V.off!==0)Q.off=V.off;if(V.ctr!==0)Q.ctr=V.ctr;return Q}async function _Q(V,{conn:$,store:Q,enclave:Z,host:J,crypto:I,onProgress:W},Y){let X=J.label,G=await $.keys(),K=new f(V),[w,N]=K.readStructs(qV);if(N!==0){console.error("Failed decoding notif",_[N]);return}let z=!1,R=(await Q.hosts.get(X))?.lastSeq,U=[],H=!1;for(let O of w){let[A,m]=await z$({seq:O.seq,headCph:O.headCph},G,Z,I);if(m!==0){console.error("Failed decrypting notif",_[m]);continue}let x=await I.blake3(A.headEnc);if(await Q.messages.has(x))continue;let S=new f(A.headEnc),[E,B]=S.readStruct(Y0);if(B!==0){console.error("Failed to parse head",_[B]);continue}if(!O.bodyCph&&E.len>0)H=!0,await Q.downloads.enq([{seq:O.seq,host:X,kdm:A.kdm,head:E,headEnc:A.headEnc,headEncHash:x}]);else U.push({...A,head:E,bodyCph:O.bodyCph,headEncHash:x});if(R===void 0||O.seq!==R+1)console.log("out of seq",O.seq,R),z=!0;else R=O.seq}if(R!==void 0)await Q.hosts.touch(J.label,R);let P=[];for(let O of U){let A=await Z.deriveFromKDM(O.kdm),[m,x]=await aV(O.headEnc,O.bodyCph,A,I);if(x!==0){console.error("Failed to open body",_[x]);continue}P.push({key:O.headEncHash,data:AQ({head:O.head,body:m.bod})})}let D=await Q.messages.add(P);for(let O=0;O<D.length;O++){let A=D[O];if(A!==0&&A!==15)console.error("ERR storing",_[A],"for message",O)}if(W&&P.length>0)W({phase:"open",host:J.label,done:P.length,total:P.length});if(z||H||P.length>0)Y()}class f0{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new LV;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=YV;lastProgress=E0;scheduledSync;constructor(V,$,Q,Z,J,I=!0,W=U$,Y=O$,X){this.clock=V;this.state=$;this.store=Q;this.transport=Z;this.crypto=J;this.forceSkewHandlingByDefault=I;this.onScheduleSync=X;this.maxPushBytes=W,this.maxPullBytes=Y,this.clientState=new G0(()=>this.getClientState()),this.xferState=new G0(()=>this.getXferState()),this.scheduledSync=new IV(mV,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(G){console.error("Debounced sync failed:",G)}})}emitProgress=(V)=>{this.lastProgress=V,this.xferState.emit()};async setSeed(V){await this.store.seed.save(V),this.clientState.emit()}async getClientState(){let{store:V,connections:$}=this,Q=await V.seed.load(),Z=await V.hosts.list(),J=!1;for(let I of $.values())if(I.isConnected()){J=!0;break}return{hasSeed:Q!==void 0,hasHost:Array.from(Z).length>0,connected:J}}async getXferState(){let{uploads:V,downloads:$}=this.store,Q=await V.count();return{numDownloads:await $.count(),numUploads:Q,progress:this.lastProgress}}apply=(V,$)=>{return this.enqueueApplyJob(()=>this.doApply(V,$))};async doApply(V,$={enqueueUpload:!0,triggerUpload:!0}){let Q=[],Z=[];for(let{head:I,body:W}of V){let Y=new k;Y.writeStruct(Y0,I);let X=Y.result(),G=await this.crypto.blake3(X),K={eid:I.eid,body:W,apld:z0};if(I.off!==0)K.off=I.off;if(I.ctr!==0)K.ctr=I.ctr;Q.push(G),Z.push({key:G,data:K})}await this.store.messages.add(Z),await PQ(this.store,Q,this.crypto);let J=await this.doApplyHashes(Q);if($.enqueueUpload){let I=[];for(let W=0;W<Q.length;W++){let Y=J[W];if(Y===0||Y===15)I.push(Q[W])}if(I.length>0){let W=await this.store.hosts.list();for(let Y of W)await this.store.uploads.enq(Y.label,I);this.xferState.emit()}}if($.triggerUpload)this.scheduleSync();return J}enqueueApplyJob(V){let $=this.applyChain.then(V,V);return this.applyChain=$.then(()=>{return},()=>{return}),$}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let V=await this.store.messages.list(z0);if(V.length<1)return[];let $=WV(V,(Q)=>Q.head);return this.applyStored($)}applyHashes=(V)=>{return this.enqueueApplyJob(()=>this.doApplyHashes(V))};async doApplyHashes(V){let $=[];for(let J of V){let I=await this.store.messages.get(J);if(I)$.push(I)}let Q=await this.applyStored($),Z=new Map;for(let J=0;J<$.length;J++)Z.set(L($[J].hash),Q[J]??12);return V.map((J)=>Z.get(L(J))??13)}async applyStored(V){if(V.length<1)return[];let $=V.map((I)=>({...I.head,bod:I.body})),Q=await this.state.apply($),Z=[],J=[];for(let I=0;I<V.length;I++){let W=Q[I];if(W===0||W===15)Z.push(V[I].hash);else if(W!==void 0&&F$(W))J.push({key:V[I].hash,err:W})}if(Z.length>0)await this.store.messages.markApplied(Z);if(J.length>0)await this.store.messages.markFailed(J);return Q}async insertRaw(V){let{clock:$,crypto:Q}=this,[Z,J]=await NQ({now:$.now(),bod:V,crypto:Q});if(J!==0)return M(J);let W=(await this.apply([{head:Z,body:V}]))[0];if(W!==0&&W!==15)return M(W??12);return q(Z)}async makeUpdate(V,$){let{clock:Q,crypto:Z}=this,J=Q.now();if(V.updatedAt.getTime()>J.getTime())return M(4);let I=V.ctr+1,[W,Y]=await DV({now:J,eid:V.eid,ctr:I,bod:$,crypto:Z});if(Y!==0)return M(Y);return q({head:W,body:$})}async updateWithSkew(V,$,Q){if(Q===!1)return M(4);let{clock:Z,crypto:J}=this,I=Z.now(),W=new f(V.eid),[Y,X]=W.readStruct(r);if(X!==0)return M(X);let G=V.updatedAt.getTime()-Y.ts.getTime(),K={eid:V.eid,off:G+1,ctr:V.ctr+1,len:0},N=(await this.apply([{head:K,body:void 0}]))[0];if(N!==0&&N!==15)return M(N??12);if($===void 0)return q(K);let[z,F]=l0({id:Y.id,ts:I});if(F!==0)return M(F);let[R,U]=await DV({now:I,eid:z,ctr:0,bod:$,crypto:J});if(U!==0)return M(U);let P=(await this.apply([{head:R,body:$}]))[0];if(P!==0&&P!==15)return M(P??12);return q(R)}async updateRaw(V,$,Q=this.forceSkewHandlingByDefault){if(V.updatedAt.getTime()>this.clock.now().getTime())return this.updateWithSkew(V,$,Q);return this.enqueueApplyJob(async()=>{let[Z,J]=await this.makeUpdate(V,$);if(J!==0)return M(J);let W=(await this.doApply([Z]))[0];if(W!==0&&W!==15)return M(W??12);return q(Z.head)})}async insert(V){let{body:$,type:Q,gid:Z,pid:J}=V,W=m0({body:$,type:Q,gid:Z,pid:J});return this.insertRaw(W)}async update(V){let{prior:$,body:Q,type:Z,gid:J,pid:I,force:W}=V,X=m0({body:Q,type:Z,gid:J,pid:I});return this.updateRaw($,X,W??this.forceSkewHandlingByDefault)}async delete(V){let $=V.force??!0;if("prior"in V)return this.updateRaw(V.prior,void 0,$);let[Q,Z]=await this.revFromArchive(V.eid);if(Z!==0)return M(Z);return this.updateRaw(Q,void 0,$)}async revFromArchive(V){let $=await this.store.messages.last(V);if($)return N$($.head);let Q=new f(V),[Z,J]=Q.readStruct(r);if(J!==0)return M(J);return q({eid:V,ctr:-1,updatedAt:Z.ts})}async genEID(V){let{clock:$,crypto:Q}=this,Z=$.now();if(V!==void 0)return l0({id:V,ts:Z});let J=await Q.genRandomBytes(8);return l0({id:J,ts:Z})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:V,crypto:$,store:Q}=this,Z=await Q.seed.load();if(!Z)return 22;await this.drainApplyQueue();for(let[J,I]of V){let W=await Q.hosts.get(J);if(!W)continue;let Y={conn:I,store:Q,enclave:Z,host:W,crypto:$,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},X=await CQ(Y);if(X!==0)return console.error(`Failed to peek: ${X}`),X;this.xferState.emit();let G=await TQ(Y);if(G!==0)return console.error(`Failed to push: ${G}`),G;this.xferState.emit();let K=await DQ(Y,async()=>{await this.drainApplyQueue()});if(K!==0&&K!==15)return console.error(`Failed to pull: ${K}`),K;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async wipe(){this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush(),await this.store.wipe(),await this.state.clear(),this.lastProgress=E0,this.clientState.emit(),this.xferState.emit()}import=async(V,$)=>{let{crypto:Q,store:Z}=this,J=$?.onProgress,I=await Z.seed.load();if(!I)return 22;console.time("import: decoding file...");let W=await V.bytes(),[Y,X]=await wQ(W,Q,I);if(X!==0)return X;console.timeEnd("import: decoding file...");let G=0;while(G<Y.length){let K=0,w=0,N=G;for(let R=G;R<Y.length&&w<100&&K<102400;R++)K+=Y[R].head.len,w++,N=R+1;let z=Y.slice(G,N);console.time(`import: applying [${G}, ${N}]`);let F=await this.apply(z,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${G}, ${N}]`);for(let R=0;R<z.length;R++){let U=F[R];if(U!==0&&U!==15)console.warn(`failed to import msg ${G+R}: ${_[U]}`)}if(J)queueMicrotask(()=>J(N,Y.length,0));this.emitProgress({phase:"import",done:N,total:Y.length}),G=N}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:V,store:$}=this,Q=await $.seed.load();if(!Q)return M(22);let Z=await $.messages.list();return MQ("export",0,Z,V,Q)}async export(V){let[$,Q]=await this.exportBytes();if(Q!==0)return Q;if(!$)return 12;let Z=new Blob([$.slice()]);return EV(Z,V),0}async link(V,$=!0){if(await this.store.hosts.add(V),this.clientState.emit(),$){let Q=await this.store.hosts.get(V.label);if(Q)await this.connectToHost(Q)}}async unlink(V){await this.store.hosts.del(V),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async(V,$=!0,Q=!0)=>{let{clock:Z,connections:J,crypto:I,store:W,transport:Y}=this,X=J.get(V.label);if(X){if(X.isConnected())return;try{X.closeListener()}catch{}J.delete(V.label)}let G=await W.seed.load();if(!G)return;console.info(`Connecting to ${V.handle} (${V.label})`);let K=new TV(G,I,V,Z,Y(V),(w)=>W.hosts.set(V.label,w));if(await K.register(),$)await K.listen(async(w)=>{let N={conn:K,store:W,enclave:G,host:V,crypto:I,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return _Q(w,N,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(J.set(V.label,K),this.clientState.emit(),Q)this.scheduleSync()};async connect(V=!0,$=!0){let{connectToHost:Q,scheduleSync:Z,store:J}=this;if(!await J.seed.load())return;await this.drainApplyQueue();let W=await J.hosts.list();for(let Y of W)await Q(Y,V,!1);if($)Z()}disconnect=async()=>{for(let V of this.connections.values())try{V.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var x0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function SV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function q$(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function h(V,...$){if(!q$(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function H$(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function jQ(V,$){h(V);let Q=$.outputLen;if(V.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function P$(V){if(typeof V!=="boolean")throw Error(`boolean expected, not ${V}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var F0=(V)=>new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4));var aZ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!aZ)throw Error("Non little-endian hardware is not supported");function sZ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function fV(V){if(typeof V==="string")V=sZ(V);else if(q$(V))V=xV(V);else throw Error("Uint8Array expected, got "+typeof V);return V}function LQ(V,$){if($==null||typeof $!=="object")throw Error("options must be defined");return Object.assign(V,$)}function mQ(V,$){if(V.length!==$.length)return!1;let Q=0;for(let Z=0;Z<V.length;Z++)Q|=V[Z]^$[Z];return Q===0}var EQ=(V,$)=>{function Q(Z,...J){if(h(Z),V.nonceLength!==void 0){let K=J[0];if(!K)throw Error("nonce / iv required");if(V.varSizeNonce)h(K);else h(K,V.nonceLength)}let I=V.tagLength;if(I&&J[1]!==void 0)h(J[1]);let W=$(Z,...J),Y=(K,w)=>{if(w!==void 0){if(K!==2)throw Error("cipher output not supported");h(w)}},X=!1;return{encrypt(K,w){if(X)throw Error("cannot encrypt() twice with same key + nonce");return X=!0,h(K),Y(W.encrypt.length,w),W.encrypt(K,w)},decrypt(K,w){if(h(K),I&&K.length<I)throw Error("invalid ciphertext length: smaller than tagLength="+I);return Y(W.decrypt.length,w),W.decrypt(K,w)}}}return Object.assign(Q,V),Q};function C$(V,$,Q=!0){if($===void 0)return new Uint8Array(V);if($.length!==V)throw Error("invalid output length, expected "+V+", got: "+$.length);if(Q&&!tZ($))throw Error("invalid output, must be aligned");return $}function tZ(V){return V.byteOffset%4===0}function xV(V){return Uint8Array.from(V)}function M0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function kV(V=32){if(x0&&typeof x0.getRandomValues==="function")return x0.getRandomValues(new Uint8Array(V));if(x0&&typeof x0.randomBytes==="function")return x0.randomBytes(V);throw Error("crypto.getRandomValues must be defined")}var fQ=(V)=>Uint8Array.from(V.split("").map(($)=>$.charCodeAt(0))),eZ=fQ("expand 16-byte k"),VJ=fQ("expand 32-byte k"),$J=F0(eZ),QJ=F0(VJ);function T(V,$){return V<<$|V>>>32-$}function T$(V){return V.byteOffset%4===0}var BV=64,ZJ=16,xQ=4294967295,SQ=new Uint32Array;function JJ(V,$,Q,Z,J,I,W,Y){let X=J.length,G=new Uint8Array(BV),K=F0(G),w=T$(J)&&T$(I),N=w?F0(J):SQ,z=w?F0(I):SQ;for(let F=0;F<X;W++){if(V($,Q,Z,K,W,Y),W>=xQ)throw Error("arx: counter overflow");let R=Math.min(BV,X-F);if(w&&R===BV){let U=F/4;if(F%4!==0)throw Error("arx: invalid block position");for(let H=0,P;H<ZJ;H++)P=U+H,z[P]=N[P]^K[H];F+=BV;continue}for(let U=0,H;U<R;U++)H=F+U,I[H]=J[H]^G[U];F+=R}}function kQ(V,$){let{allowShortKeys:Q,extendNonceFn:Z,counterLength:J,counterRight:I,rounds:W}=LQ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},$);if(typeof V!=="function")throw Error("core must be a function");return SV(J),SV(W),P$(I),P$(Q),(Y,X,G,K,w=0)=>{h(Y),h(X),h(G);let N=G.length;if(K===void 0)K=new Uint8Array(N);if(h(K),SV(w),w<0||w>=xQ)throw Error("arx: counter overflow");if(K.length<N)throw Error(`arx: output (${K.length}) is shorter than data (${N})`);let z=[],F=Y.length,R,U;if(F===32)z.push(R=xV(Y)),U=QJ;else if(F===16&&Q)R=new Uint8Array(32),R.set(Y),R.set(Y,16),U=$J,z.push(R);else throw Error(`arx: invalid 32-byte key, got length=${F}`);if(!T$(X))z.push(X=xV(X));let H=F0(R);if(Z){if(X.length!==24)throw Error("arx: extended nonce must be 24 bytes");Z(U,H,F0(X.subarray(0,16)),H),X=X.subarray(16)}let P=16-J;if(P!==X.length)throw Error(`arx: nonce must be ${P} or 16 bytes`);if(P!==12){let O=new Uint8Array(12);O.set(X,I?0:12-X.length),X=O,z.push(X)}let D=F0(X);return JJ(V,U,H,D,G,K,w,W),M0(...z),K}}var d=(V,$)=>V[$++]&255|(V[$++]&255)<<8;class BQ{constructor(V){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,V=fV(V),h(V,32);let $=d(V,0),Q=d(V,2),Z=d(V,4),J=d(V,6),I=d(V,8),W=d(V,10),Y=d(V,12),X=d(V,14);this.r[0]=$&8191,this.r[1]=($>>>13|Q<<3)&8191,this.r[2]=(Q>>>10|Z<<6)&7939,this.r[3]=(Z>>>7|J<<9)&8191,this.r[4]=(J>>>4|I<<12)&255,this.r[5]=I>>>1&8190,this.r[6]=(I>>>14|W<<2)&8191,this.r[7]=(W>>>11|Y<<5)&8065,this.r[8]=(Y>>>8|X<<8)&8191,this.r[9]=X>>>5&127;for(let G=0;G<8;G++)this.pad[G]=d(V,16+2*G)}process(V,$,Q=!1){let Z=Q?0:2048,{h:J,r:I}=this,W=I[0],Y=I[1],X=I[2],G=I[3],K=I[4],w=I[5],N=I[6],z=I[7],F=I[8],R=I[9],U=d(V,$+0),H=d(V,$+2),P=d(V,$+4),D=d(V,$+6),O=d(V,$+8),A=d(V,$+10),m=d(V,$+12),x=d(V,$+14),S=J[0]+(U&8191),E=J[1]+((U>>>13|H<<3)&8191),B=J[2]+((H>>>10|P<<6)&8191),C=J[3]+((P>>>7|D<<9)&8191),g=J[4]+((D>>>4|O<<12)&8191),v=J[5]+(O>>>1&8191),y=J[6]+((O>>>14|A<<2)&8191),b=J[7]+((A>>>11|m<<5)&8191),p=J[8]+((m>>>8|x<<8)&8191),l=J[9]+(x>>>5|Z),j=0,o=j+S*W+E*(5*R)+B*(5*F)+C*(5*z)+g*(5*N);j=o>>>13,o&=8191,o+=v*(5*w)+y*(5*K)+b*(5*G)+p*(5*X)+l*(5*Y),j+=o>>>13,o&=8191;let t=j+S*Y+E*W+B*(5*R)+C*(5*F)+g*(5*z);j=t>>>13,t&=8191,t+=v*(5*N)+y*(5*w)+b*(5*K)+p*(5*G)+l*(5*X),j+=t>>>13,t&=8191;let Q0=j+S*X+E*Y+B*W+C*(5*R)+g*(5*F);j=Q0>>>13,Q0&=8191,Q0+=v*(5*z)+y*(5*N)+b*(5*w)+p*(5*K)+l*(5*G),j+=Q0>>>13,Q0&=8191;let i=j+S*G+E*X+B*Y+C*W+g*(5*R);j=i>>>13,i&=8191,i+=v*(5*F)+y*(5*z)+b*(5*N)+p*(5*w)+l*(5*K),j+=i>>>13,i&=8191;let N0=j+S*K+E*G+B*X+C*Y+g*W;j=N0>>>13,N0&=8191,N0+=v*(5*R)+y*(5*F)+b*(5*z)+p*(5*N)+l*(5*w),j+=N0>>>13,N0&=8191;let g0=j+S*w+E*K+B*G+C*X+g*Y;j=g0>>>13,g0&=8191,g0+=v*W+y*(5*R)+b*(5*F)+p*(5*z)+l*(5*N),j+=g0>>>13,g0&=8191;let i0=j+S*N+E*w+B*K+C*G+g*X;j=i0>>>13,i0&=8191,i0+=v*Y+y*W+b*(5*R)+p*(5*F)+l*(5*z),j+=i0>>>13,i0&=8191;let v0=j+S*z+E*N+B*w+C*K+g*G;j=v0>>>13,v0&=8191,v0+=v*X+y*Y+b*W+p*(5*R)+l*(5*F),j+=v0>>>13,v0&=8191;let u0=j+S*F+E*z+B*N+C*w+g*K;j=u0>>>13,u0&=8191,u0+=v*G+y*X+b*Y+p*W+l*(5*R),j+=u0>>>13,u0&=8191;let n0=j+S*R+E*F+B*z+C*N+g*w;j=n0>>>13,n0&=8191,n0+=v*K+y*G+b*X+p*Y+l*W,j+=n0>>>13,n0&=8191,j=(j<<2)+j|0,j=j+o|0,o=j&8191,j=j>>>13,t+=j,J[0]=o,J[1]=t,J[2]=Q0,J[3]=i,J[4]=N0,J[5]=g0,J[6]=i0,J[7]=v0,J[8]=u0,J[9]=n0}finalize(){let{h:V,pad:$}=this,Q=new Uint16Array(10),Z=V[1]>>>13;V[1]&=8191;for(let W=2;W<10;W++)V[W]+=Z,Z=V[W]>>>13,V[W]&=8191;V[0]+=Z*5,Z=V[0]>>>13,V[0]&=8191,V[1]+=Z,Z=V[1]>>>13,V[1]&=8191,V[2]+=Z,Q[0]=V[0]+5,Z=Q[0]>>>13,Q[0]&=8191;for(let W=1;W<10;W++)Q[W]=V[W]+Z,Z=Q[W]>>>13,Q[W]&=8191;Q[9]-=8192;let J=(Z^1)-1;for(let W=0;W<10;W++)Q[W]&=J;J=~J;for(let W=0;W<10;W++)V[W]=V[W]&J|Q[W];V[0]=(V[0]|V[1]<<13)&65535,V[1]=(V[1]>>>3|V[2]<<10)&65535,V[2]=(V[2]>>>6|V[3]<<7)&65535,V[3]=(V[3]>>>9|V[4]<<4)&65535,V[4]=(V[4]>>>12|V[5]<<1|V[6]<<14)&65535,V[5]=(V[6]>>>2|V[7]<<11)&65535,V[6]=(V[7]>>>5|V[8]<<8)&65535,V[7]=(V[8]>>>8|V[9]<<5)&65535;let I=V[0]+$[0];V[0]=I&65535;for(let W=1;W<8;W++)I=(V[W]+$[W]|0)+(I>>>16)|0,V[W]=I&65535;M0(Q)}update(V){H$(this);let{buffer:$,blockLen:Q}=this;V=fV(V);let Z=V.length;for(let J=0;J<Z;){let I=Math.min(Q-this.pos,Z-J);if(I===Q){for(;Q<=Z-J;J+=Q)this.process(V,J);continue}if($.set(V.subarray(J,J+I),this.pos),this.pos+=I,J+=I,this.pos===Q)this.process($,0,!1),this.pos=0}return this}destroy(){M0(this.h,this.r,this.buffer,this.pad)}digestInto(V){H$(this),jQ(V,this),this.finished=!0;let{buffer:$,h:Q}=this,{pos:Z}=this;if(Z){$[Z++]=1;for(;Z<16;Z++)$[Z]=0;this.process($,0,!0)}this.finalize();let J=0;for(let I=0;I<8;I++)V[J++]=Q[I]>>>0,V[J++]=Q[I]>>>8;return V}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Q=V.slice(0,$);return this.destroy(),Q}}function IJ(V){let $=(Z,J)=>V(J).update(fV(Z)).digest(),Q=V(new Uint8Array(32));return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=(Z)=>V(Z),$}var D$=IJ((V)=>new BQ(V));function WJ(V,$,Q,Z,J,I=20){let W=V[0],Y=$[0],X=$[1],G=$[2],K=$[3],w=V[1],N=Q[0],z=Q[1],F=J,R=0,U=V[2],H=$[4],P=$[5],D=$[6],O=$[7],A=V[3],m=W,x=Y,S=X,E=G,B=K,C=w,g=N,v=z,y=F,b=R,p=U,l=H,j=P,o=D,t=O,Q0=A;for(let N0=0;N0<I;N0+=2)B^=T(m+j|0,7),y^=T(B+m|0,9),j^=T(y+B|0,13),m^=T(j+y|0,18),b^=T(C+x|0,7),o^=T(b+C|0,9),x^=T(o+b|0,13),C^=T(x+o|0,18),t^=T(p+g|0,7),S^=T(t+p|0,9),g^=T(S+t|0,13),p^=T(g+S|0,18),E^=T(Q0+l|0,7),v^=T(E+Q0|0,9),l^=T(v+E|0,13),Q0^=T(l+v|0,18),x^=T(m+E|0,7),S^=T(x+m|0,9),E^=T(S+x|0,13),m^=T(E+S|0,18),g^=T(C+B|0,7),v^=T(g+C|0,9),B^=T(v+g|0,13),C^=T(B+v|0,18),l^=T(p+b|0,7),y^=T(l+p|0,9),b^=T(y+l|0,13),p^=T(b+y|0,18),j^=T(Q0+t|0,7),o^=T(j+Q0|0,9),t^=T(o+j|0,13),Q0^=T(t+o|0,18);let i=0;Z[i++]=W+m|0,Z[i++]=Y+x|0,Z[i++]=X+S|0,Z[i++]=G+E|0,Z[i++]=K+B|0,Z[i++]=w+C|0,Z[i++]=N+g|0,Z[i++]=z+v|0,Z[i++]=F+y|0,Z[i++]=R+b|0,Z[i++]=U+p|0,Z[i++]=H+l|0,Z[i++]=P+j|0,Z[i++]=D+o|0,Z[i++]=O+t|0,Z[i++]=A+Q0|0}function YJ(V,$,Q,Z){let J=V[0],I=$[0],W=$[1],Y=$[2],X=$[3],G=V[1],K=Q[0],w=Q[1],N=Q[2],z=Q[3],F=V[2],R=$[4],U=$[5],H=$[6],P=$[7],D=V[3];for(let A=0;A<20;A+=2)X^=T(J+U|0,7),N^=T(X+J|0,9),U^=T(N+X|0,13),J^=T(U+N|0,18),z^=T(G+I|0,7),H^=T(z+G|0,9),I^=T(H+z|0,13),G^=T(I+H|0,18),P^=T(F+K|0,7),W^=T(P+F|0,9),K^=T(W+P|0,13),F^=T(K+W|0,18),Y^=T(D+R|0,7),w^=T(Y+D|0,9),R^=T(w+Y|0,13),D^=T(R+w|0,18),I^=T(J+Y|0,7),W^=T(I+J|0,9),Y^=T(W+I|0,13),J^=T(Y+W|0,18),K^=T(G+X|0,7),w^=T(K+G|0,9),X^=T(w+K|0,13),G^=T(X+w|0,18),R^=T(F+z|0,7),N^=T(R+F|0,9),z^=T(N+R|0,13),F^=T(z+N|0,18),U^=T(D+P|0,7),H^=T(U+D|0,9),P^=T(H+U|0,13),D^=T(P+H|0,18);let O=0;Z[O++]=J,Z[O++]=G,Z[O++]=F,Z[O++]=D,Z[O++]=K,Z[O++]=w,Z[O++]=N,Z[O++]=z}var A$=kQ(WJ,{counterRight:!0,extendNonceFn:YJ}),_$=EQ({blockSize:64,nonceLength:24,tagLength:16},(V,$)=>{return{encrypt(Q,Z){Z=C$(Q.length+32,Z,!1);let J=Z.subarray(0,32),I=Z.subarray(32);Z.set(Q,32),M0(J),A$(V,$,Z,Z);let W=D$(I,J);return Z.set(W,16),M0(Z.subarray(0,16),W),Z.subarray(16)},decrypt(Q,Z){h(Q),Z=C$(Q.length+32,Z,!1);let J=Z.subarray(0,32),I=Z.subarray(32,48),W=Z.subarray(48);Z.set(Q,32),M0(J);let Y=A$(V,$,J,J),X=D$(W,Y);if(!mQ(I,X))throw Error("invalid tag");return A$(V,$,Z.subarray(16),Z.subarray(16)),M0(J,I,X),W}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function XJ(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function GV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function k0(V,...$){if(!XJ(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function KV(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function gV(V,$){k0(V);let Q=$.outputLen;if(V.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function gQ(V){return new Uint8Array(V.buffer,V.byteOffset,V.byteLength)}function c0(V){return new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4))}function d0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function MV(V,$){return V<<32-$|V>>>$}var iQ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function vQ(V){return V<<24&4278190080|V<<8&16711680|V>>>8&65280|V>>>24&255}var uQ=iQ?(V)=>V:(V)=>vQ(V);function GJ(V){for(let $=0;$<V.length;$++)V[$]=vQ(V[$]);return V}var V0=iQ?(V)=>V:GJ;function KJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function o0(V){if(typeof V==="string")V=KJ(V);return k0(V),V}class j${}function nQ(V){let $=(Z,J)=>V(J).update(o0(Z)).digest(),Q=V({});return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=(Z)=>V(Z),$}var yQ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var iV=BigInt(4294967295),bQ=BigInt(32);function L$(V,$=!1){if($)return{h:Number(V&iV),l:Number(V>>bQ&iV)};return{h:Number(V>>bQ&iV)|0,l:Number(V&iV)|0}}function U0(V,$,Q,Z,J){return V=V+$+J|0,Z=MV(Z^V,16),Q=Q+Z|0,$=MV($^Q,12),{a:V,b:$,c:Q,d:Z}}function O0(V,$,Q,Z,J){return V=V+$+J|0,Z=MV(Z^V,8),Q=Q+Z|0,$=MV($^Q,7),{a:V,b:$,c:Q,d:Z}}class m$ extends j${constructor(V,$){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,GV(V),GV($),this.blockLen=V,this.outputLen=$,this.buffer=new Uint8Array(V),this.buffer32=c0(this.buffer)}update(V){KV(this),V=o0(V),k0(V);let{blockLen:$,buffer:Q,buffer32:Z}=this,J=V.length,I=V.byteOffset,W=V.buffer;for(let Y=0;Y<J;){if(this.pos===$)V0(Z),this.compress(Z,0,!1),V0(Z),this.pos=0;let X=Math.min($-this.pos,J-Y),G=I+Y;if(X===$&&!(G%4)&&Y+X<J){let K=new Uint32Array(W,G,Math.floor((J-Y)/4));V0(K);for(let w=0;Y+$<J;w+=Z.length,Y+=$)this.length+=$,this.compress(K,w,!1);V0(K);continue}Q.set(V.subarray(Y,Y+X),this.pos),this.pos+=X,this.length+=X,Y+=X}return this}digestInto(V){KV(this),gV(V,this);let{pos:$,buffer32:Q}=this;this.finished=!0,d0(this.buffer.subarray($)),V0(Q),this.compress(Q,0,!0),V0(Q);let Z=c0(V);this.get().forEach((J,I)=>Z[I]=uQ(J))}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Q=V.slice(0,$);return this.destroy(),Q}_cloneInto(V){let{buffer:$,length:Q,finished:Z,destroyed:J,outputLen:I,pos:W}=this;return V||(V=new this.constructor({dkLen:I})),V.set(...this.get()),V.buffer.set($),V.destroyed=J,V.finished=Z,V.length=Q,V.pos=W,V.outputLen=I,V}clone(){return this._cloneInto()}}function E$(V,$,Q,Z,J,I,W,Y,X,G,K,w,N,z,F,R,U,H,P,D){let O=0;for(let A=0;A<Z;A++)({a:J,b:X,c:N,d:U}=U0(J,X,N,U,Q[$+V[O++]])),{a:J,b:X,c:N,d:U}=O0(J,X,N,U,Q[$+V[O++]]),{a:I,b:G,c:z,d:H}=U0(I,G,z,H,Q[$+V[O++]]),{a:I,b:G,c:z,d:H}=O0(I,G,z,H,Q[$+V[O++]]),{a:W,b:K,c:F,d:P}=U0(W,K,F,P,Q[$+V[O++]]),{a:W,b:K,c:F,d:P}=O0(W,K,F,P,Q[$+V[O++]]),{a:Y,b:w,c:R,d:D}=U0(Y,w,R,D,Q[$+V[O++]]),{a:Y,b:w,c:R,d:D}=O0(Y,w,R,D,Q[$+V[O++]]),{a:J,b:G,c:F,d:D}=U0(J,G,F,D,Q[$+V[O++]]),{a:J,b:G,c:F,d:D}=O0(J,G,F,D,Q[$+V[O++]]),{a:I,b:K,c:R,d:U}=U0(I,K,R,U,Q[$+V[O++]]),{a:I,b:K,c:R,d:U}=O0(I,K,R,U,Q[$+V[O++]]),{a:W,b:w,c:N,d:H}=U0(W,w,N,H,Q[$+V[O++]]),{a:W,b:w,c:N,d:H}=O0(W,w,N,H,Q[$+V[O++]]),{a:Y,b:X,c:z,d:P}=U0(Y,X,z,P,Q[$+V[O++]]),{a:Y,b:X,c:z,d:P}=O0(Y,X,z,P,Q[$+V[O++]]);return{v0:J,v1:I,v2:W,v3:Y,v4:X,v5:G,v6:K,v7:w,v8:N,v9:z,v10:F,v11:R,v12:U,v13:H,v14:P,v15:D}}var w0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},q0=yQ.slice(),pQ=(()=>{let V=Array.from({length:16},(Z,J)=>J),$=(Z)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((J)=>Z[J]),Q=[];for(let Z=0,J=V;Z<7;Z++,J=$(J))Q.push(...J);return Uint8Array.from(Q)})();class S$ extends m${constructor(V={},$=0){super(64,V.dkLen===void 0?32:V.dkLen);this.chunkPos=0,this.chunksDone=0,this.flags=0,this.stack=[],this.posOut=0,this.bufferOut32=new Uint32Array(16),this.chunkOut=0,this.enableXOF=!0;let{key:Q,context:Z}=V,J=Z!==void 0;if(Q!==void 0){if(J)throw Error('Only "key" or "context" can be specified at same time');let I=o0(Q).slice();k0(I,32),this.IV=c0(I),V0(this.IV),this.flags=$|w0.KEYED_HASH}else if(J){let I=o0(Z),W=new S$({dkLen:32},w0.DERIVE_KEY_CONTEXT).update(I).digest();this.IV=c0(W),V0(this.IV),this.flags=$|w0.DERIVE_KEY_MATERIAL}else this.IV=q0.slice(),this.flags=$;this.state=this.IV.slice(),this.bufferOut=gQ(this.bufferOut32)}get(){return[]}set(){}b2Compress(V,$,Q,Z=0){let{state:J,pos:I}=this,{h:W,l:Y}=L$(BigInt(V),!0),{v0:X,v1:G,v2:K,v3:w,v4:N,v5:z,v6:F,v7:R,v8:U,v9:H,v10:P,v11:D,v12:O,v13:A,v14:m,v15:x}=E$(pQ,Z,Q,7,J[0],J[1],J[2],J[3],J[4],J[5],J[6],J[7],q0[0],q0[1],q0[2],q0[3],W,Y,I,$);J[0]=X^U,J[1]=G^H,J[2]=K^P,J[3]=w^D,J[4]=N^O,J[5]=z^A,J[6]=F^m,J[7]=R^x}compress(V,$=0,Q=!1){let Z=this.flags;if(!this.chunkPos)Z|=w0.CHUNK_START;if(this.chunkPos===15||Q)Z|=w0.CHUNK_END;if(!Q)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,Z,V,$),this.chunkPos+=1,this.chunkPos===16||Q){let J=this.state;this.state=this.IV.slice();for(let I,W=this.chunksDone+1;Q||!(W&1);W>>=1){if(!(I=this.stack.pop()))break;this.buffer32.set(I,0),this.buffer32.set(J,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|w0.PARENT,this.buffer32,0),J=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(J)}this.pos=0}_cloneInto(V){V=super._cloneInto(V);let{IV:$,flags:Q,state:Z,chunkPos:J,posOut:I,chunkOut:W,stack:Y,chunksDone:X}=this;return V.state.set(Z.slice()),V.stack=Y.map((G)=>Uint32Array.from(G)),V.IV.set($),V.flags=Q,V.chunkPos=J,V.chunksDone=X,V.posOut=I,V.chunkOut=W,V.enableXOF=this.enableXOF,V.bufferOut32.set(this.bufferOut32),V}destroy(){this.destroyed=!0,d0(this.state,this.buffer32,this.IV,this.bufferOut32),d0(...this.stack)}b2CompressOut(){let{state:V,pos:$,flags:Q,buffer32:Z,bufferOut32:J}=this,{h:I,l:W}=L$(BigInt(this.chunkOut++));V0(Z);let{v0:Y,v1:X,v2:G,v3:K,v4:w,v5:N,v6:z,v7:F,v8:R,v9:U,v10:H,v11:P,v12:D,v13:O,v14:A,v15:m}=E$(pQ,0,Z,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],q0[0],q0[1],q0[2],q0[3],W,I,$,Q);J[0]=Y^R,J[1]=X^U,J[2]=G^H,J[3]=K^P,J[4]=w^D,J[5]=N^O,J[6]=z^A,J[7]=F^m,J[8]=V[0]^R,J[9]=V[1]^U,J[10]=V[2]^H,J[11]=V[3]^P,J[12]=V[4]^D,J[13]=V[5]^O,J[14]=V[6]^A,J[15]=V[7]^m,V0(Z),V0(J),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,d0(this.buffer.subarray(this.pos));let V=this.flags|w0.ROOT;if(this.stack.length)V|=w0.PARENT,V0(this.buffer32),this.compress(this.buffer32,0,!0),V0(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else V|=(!this.chunkPos?w0.CHUNK_START:0)|w0.CHUNK_END;this.flags=V,this.b2CompressOut()}writeInto(V){KV(this,!1),k0(V),this.finish();let{blockLen:$,bufferOut:Q}=this;for(let Z=0,J=V.length;Z<J;){if(this.posOut>=$)this.b2CompressOut();let I=Math.min($-this.posOut,J-Z);V.set(Q.subarray(this.posOut,this.posOut+I),Z),this.posOut+=I,Z+=I}return V}xofInto(V){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(V)}xof(V){return GV(V),this.xofInto(new Uint8Array(V))}digestInto(V){if(gV(V,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto(V),this.destroy(),V}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var lQ=nQ((V)=>new S$(V));var f$=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function hQ(V){let $=new Uint8Array(f$.length+32);return $.set(f$),$.set(V.subarray(0,32),f$.length),$}function rQ(V){return typeof V==="string"?new TextEncoder().encode(V):V}function a0(V){let $=new ArrayBuffer(V.byteLength);return new Uint8Array($).set(V),$}class x${verifyKeys=new Map;signKeys=new Map;async genRandomBytes(V){return kV(V)}async gen256BitSecureRandomSeed(){return kV(32)}async encryptXSalsa20Poly1305Combined(V,$){let Q=kV(24),J=_$($,Q).encrypt(V);return new Uint8Array([...Q,...J])}async decryptXSalsa20Poly1305Combined(V,$){let Q=V.slice(0,24),Z=V.slice(24);return _$($,Q).decrypt(Z)}async deriveEd25519KeyPair(V){let $=V,Q=hQ($),Z=await globalThis.crypto.subtle.importKey("pkcs8",a0(Q),{name:"Ed25519"},!0,["sign"]),J=await globalThis.crypto.subtle.exportKey("jwk",Z);if(typeof J.x!=="string")throw Error("Ed25519 JWK missing x");let I=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:J.x},{name:"Ed25519"},!0,["verify"]),W=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",I)),Y=new Uint8Array(64);return Y.set($,0),Y.set(W,32),this.signKeys.set(a($),Z),this.verifyKeys.set(a(W),I),{keyType:"ed25519",privateKey:Y,publicKey:W}}async importSignKey(V){let $=V.subarray(0,32),Q=a($),Z=this.signKeys.get(Q);if(Z)return Z;let J=hQ($),I=await globalThis.crypto.subtle.importKey("pkcs8",a0(J),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Q,I),I}async importVerifyKey(V){let $=a(V),Q=this.verifyKeys.get($);if(Q)return Q;let Z=await globalThis.crypto.subtle.importKey("raw",a0(V),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set($,Z),Z}async signEd25519(V,$){let Q=rQ(V),Z=await this.importSignKey($),J=await globalThis.crypto.subtle.sign({name:"Ed25519"},Z,a0(Q));return new Uint8Array(J)}async checkSigEd25519(V,$,Q){let Z=rQ($);try{let J=await this.importVerifyKey(Q);return await globalThis.crypto.subtle.verify({name:"Ed25519"},J,a0(V),a0(Z))}catch{return!1}}async blake3(V){return lQ(V)}}var MJ=new x$,J0=MJ;import{useEffect as bV,useState as n$}from"react";class k${db;constructor(V){this.db=V}async enq(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(I0,"readwrite"),Z=Q.objectStore(I0);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=`${W.host}:${W.seq}`;Z.put(W,Y)}})}async deq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(I0,"readwrite"),J=Z.objectStore(I0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=`${V}:${Y}`;J.delete(X)}})}async list(){let $=this.db.transaction(I0,"readonly").objectStore(I0);return new Promise((Q,Z)=>{let J=$.getAll();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async count(){let $=this.db.transaction(I0,"readonly").objectStore(I0);return new Promise((Q,Z)=>{let J=$.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(I0,"readwrite"),$=V.objectStore(I0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}function cQ(V){return{label:V.label,handle:new URL(V.handle),idx:V.idx,lastSeq:V.lastSeq||0,clockOffset:V.clockOffset,subscription:V.subscription}}class B${db;constructor(V){this.db=V}async add(V){return this.put(V)}async put(V){let $={...V,handle:V.handle.toString(),lastSeq:V.lastSeq??0},Q=this.db.transaction($0,"readwrite"),Z=Q.objectStore($0);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error),Z.put($)})}async touch(V,$){let Q=this.db.transaction($0,"readwrite"),Z=Q.objectStore($0);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);let W=Z.get(V);W.onsuccess=()=>{let Y=W.result;if(!Y)return;let X=Y.lastSeq||0;if($<=X)return;Z.put({...Y,lastSeq:$})}})}async get(V){let Q=this.db.transaction($0,"readonly").objectStore($0);return new Promise((Z,J)=>{let I=Q.get(V);I.onsuccess=()=>{let W=I.result;if(!W)Z(void 0);else Z(cQ(W))},I.onerror=()=>J(I.error)})}async set(V,$){let Q=await this.get(V);if(!Q)return 13;try{return await this.put({...Q,...$}),0}catch{return 18}}async del(V){let $=this.db.transaction($0,"readwrite"),Q=$.objectStore($0);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),Q.delete(V)})}async list(){let $=this.db.transaction($0,"readonly").objectStore($0);return new Promise((Q,Z)=>{let J=$.getAll();J.onsuccess=()=>{let I=J.result;Q(I.map(cQ))},J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction($0,"readwrite"),$=V.objectStore($0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}class g${crypto;db;constructor(V,$){this.crypto=$;this.db=V}async add(V){let $=this.db.transaction(u,"readwrite"),Q=$.objectStore(u);return new Promise((Z)=>{if(V.length===0){Z([]);return}let J=Array(V.length).fill(0);$.oncomplete=()=>Z(J),$.onerror=()=>{for(let I=0;I<J.length;I++)J[I]=18;Z(J)};for(let I=0;I<V.length;I++){let{key:W,data:Y}=V[I],X=L(W),G=Q.put(Y,X);G.onerror=(K)=>{K.preventDefault(),J[I]=18}}})}async del(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=L(W);Z.delete(Y)}})}async get(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let I=L(V),W=Q.get(I);W.onsuccess=async()=>{let Y=W.result;if(Y)Z(await L0(V,Y,this.crypto));else Z(void 0)},W.onerror=()=>J(W.error)})}async has(V){return await this.get(V)!==void 0}async list(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let I=[],W=V===void 0?Q.openCursor():Q.index(vV).openCursor(IDBKeyRange.only(V));W.onsuccess=(Y)=>{let X=Y.target.result;if(X){let G=V===void 0?X.key:X.primaryKey,K=X.value;I.push({hash:X0(G),data:K}),X.continue()}else Promise.all(I.map(({hash:G,data:K})=>L0(G,K,this.crypto))).then(Z).catch(J)},W.onerror=()=>J(W.error)})}async last(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let I,W=Q.openCursor();W.onsuccess=async(Y)=>{let X=Y.target.result;if(X){let{key:G,value:K}=X;if(s(V,K.eid)){if(!I||(K.ctr??0)>(I.data.ctr??0)||(K.ctr??0)===(I.data.ctr??0)&&(K.off??0)>(I.data.off??0))I={key:G,data:K}}X.continue()}else if(I){let G=X0(I.key);Z(await L0(G,I.data,this.crypto))}else Z(void 0)},W.onerror=()=>J(W.error)})}async markApplied(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=L(W),X=Z.get(Y);X.onsuccess=()=>{let G=X.result;if(!G)return;S0(G,j0),Z.put(G,Y)},X.onerror=(G)=>{G.preventDefault()}}})}async markFailed(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let{key:W,err:Y}of $){let X=L(W),G=Z.get(X);G.onsuccess=()=>{let K=G.result;if(!K)return;S0(K,K0,Y),Z.put(K,X)},G.onerror=(K)=>{K.preventDefault()}}})}async wipe(){let V=this.db.transaction(u,"readwrite"),$=V.objectStore(u);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}class s0{seed;crypto;constructor(V,$){this.seed=V,this.crypto=$}async deriveFromKDM(V){let $=$V(this.seed,V);return await this.crypto.blake3($)}async derive(V,$=0){let Q=new TextEncoder().encode(V),Z=new Uint8Array(8);new DataView(Z.buffer).setBigUint64(0,BigInt($),!1);let J=$V(Q,Z);return await this.deriveFromKDM(J)}}class i${enclave;db;constructor(V){this.db=V}async save(V){let $=a(V),Q=this.db.transaction(H0,"readwrite"),Z=Q.objectStore(H0);return new Promise((J,I)=>{Q.oncomplete=()=>{this.enclave=new s0(V,J0),J(this.enclave)},Q.onerror=()=>I(Q.error),Z.put($,"seed")})}async load(){if(this.enclave)return this.enclave;let $=this.db.transaction(H0,"readonly").objectStore(H0);return new Promise((Q,Z)=>{let J=$.get("seed");J.onsuccess=()=>{let I=J.result;if(!I)Q(void 0);else{let W=_0(I);this.enclave=new s0(W,J0),Q(this.enclave)}},J.onerror=()=>Z(J.error)})}async wipe(){this.enclave=void 0;let V=this.db.transaction(H0,"readwrite"),$=V.objectStore(H0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.delete("seed")})}}class v${db;constructor(V){this.db=V}async enq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=a(Y);J.put({host:V,hash:X})}})}async deq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=a(Y);J.delete([V,X])}})}async list(V){let Q=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Z,J)=>{let I=Q.getAll();I.onsuccess=()=>{let Y=I.result.filter((X)=>X.host===V).map((X)=>X.hash);Z(Y.map((X)=>_0(X)))},I.onerror=()=>J(I.error)})}async count(){let $=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Q,Z)=>{let J=$.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(W0,"readwrite"),$=V.objectStore(W0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}var H0="seedMeta",$0="hosts",W0="uploadQueue",I0="downloadQueue",u="messages",vV="apld",wJ=3;class u${seed;hosts;uploads;downloads;messages;db;constructor(V,$){this.db=V,this.seed=new i$(V),this.hosts=new B$(V),this.uploads=new v$(V),this.downloads=new k$(V),this.messages=new g$(V,$)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function NJ(){return new Promise((V,$)=>{let Q=indexedDB.open("diplomatic-store-db",wJ);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!Z.objectStoreNames.contains(H0))Z.createObjectStore(H0);if(!Z.objectStoreNames.contains($0))Z.createObjectStore($0,{keyPath:"label"});if(!Z.objectStoreNames.contains(W0))Z.createObjectStore(W0,{keyPath:["host","hash"]});if(!Z.objectStoreNames.contains(I0))Z.createObjectStore(I0);let I;if(!Z.objectStoreNames.contains(u))I=Z.createObjectStore(u);else{if(!J)throw Error("missing upgrade transaction for messages store");I=J.objectStore(u)}if(!I.indexNames.contains(vV))I.createIndex(vV,"apld",{unique:!1})},Q.onsuccess=()=>V(Q.result),Q.onerror=()=>$(Q.error)})}async function uV(V){let $=await NJ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new u$($,V)}function dQ(V){if(!V||typeof V!=="object")return!1;if(!("kind"in V))return!1;return typeof V.kind==="string"}function oQ(V){if(typeof V!=="number")return;return V}function aQ(V){if(!V||typeof V!=="object")return;if(!("hasSeed"in V)||!("hasHost"in V)||!("connected"in V))return;if(typeof V.hasSeed!=="boolean"||typeof V.hasHost!=="boolean"||typeof V.connected!=="boolean")return;return{hasSeed:V.hasSeed,hasHost:V.hasHost,connected:V.connected}}function RJ(V){if(!V||typeof V!=="object")return;if(!("phase"in V))return;let $=zJ(V.phase);if($===void 0)return;let Q={phase:$};if("host"in V&&typeof V.host==="string")Q.host=V.host;if("done"in V&&typeof V.done==="number")Q.done=V.done;if("total"in V&&typeof V.total==="number")Q.total=V.total;if("bytesDone"in V&&typeof V.bytesDone==="number")Q.bytesDone=V.bytesDone;if("bytesTotal"in V&&typeof V.bytesTotal==="number")Q.bytesTotal=V.bytesTotal;return Q}function zJ(V){if(V==="peek"||V==="pull"||V==="open"||V==="exec"||V==="push"||V==="import"||V==="idle"||V==="apply")return V==="apply"?"exec":V;return}function sQ(V){if(!V||typeof V!=="object")return;if(!("numUploads"in V)||!("numDownloads"in V))return;if(typeof V.numUploads!=="number"||typeof V.numDownloads!=="number")return;let $={phase:"idle"};if("progress"in V){let Q=RJ(V.progress);if(Q===void 0)return;$=Q}return{numUploads:V.numUploads,numDownloads:V.numDownloads,progress:$}}var P0="[DIPLOMATIC]";class wV{worker;state;local;nextId=1;pending=new Map;ready;resolveReady;rejectReady;scheduledSync;cachedClientState={hasSeed:!1,hasHost:!1,connected:!1};cachedXferState={numUploads:0,numDownloads:0,progress:E0};clientState;xferState;constructor(V,$,Q,Z,J){this.worker=V,this.state=$,this.clientState=new G0(async()=>this.cachedClientState),this.xferState=new G0(async()=>this.cachedXferState),this.scheduledSync=new IV(J,async()=>{try{await this.request({id:this.allocId(),op:"sync"})}catch(I){console.error(`${P0} worker sync after local write failed`,I)}}),this.local=new f0(Z,$,Q,()=>{throw Error(`${P0} local writer has no transport (use worker for network)`)},J0,!0,void 0,void 0,()=>{this.scheduledSync.schedule()}),this.ready=new Promise((I,W)=>{this.resolveReady=I,this.rejectReady=W}),this.worker.onmessage=(I)=>{this.onMessage(I.data)},this.worker.onerror=(I)=>{console.error(`${P0} worker error`,I),this.failReady(Error(`${P0} worker failed to load`))},this.worker.onmessageerror=()=>{this.failReady(Error(`${P0} worker message error`))}}failReady(V){let $=this.rejectReady;if(this.rejectReady=void 0,this.resolveReady=void 0,$)$(V)}async flushScheduledSync(){await this.scheduledSync.flush()}static async connect(V,$,Q){let Z=Q.clock??new R0,J=Q.syncDebounceMs??mV,I=new wV(Q.worker,V,$,Z,J),W=Q.readyTimeoutMs??15000,Y;try{let X=I.probeReady();if(await Promise.race([I.ready,X,new Promise((G,K)=>{Y=setTimeout(()=>{K(Error(`${P0} worker ready timeout after ${W}ms`))},W)})]),Y!==void 0)clearTimeout(Y),Y=void 0;X.catch(()=>{}),await I.hydrateStateFromStore($),await I.pullRemoteState()}catch(X){throw I.terminate(),X}finally{if(Y!==void 0)clearTimeout(Y)}return I}async hydrateStateFromStore(V){let $=await V.seed.load(),Q=await V.hosts.list();this.cachedClientState={hasSeed:$!==void 0,hasHost:Array.from(Q).length>0,connected:!1};let Z=await V.uploads.count(),J=await V.downloads.count();this.cachedXferState={numUploads:Z,numDownloads:J,progress:E0}}async pullRemoteState(){let V=await this.request({id:this.allocId(),op:"getClientState"}),$=aQ(V);if($!==void 0)this.cachedClientState=$;let Q=await this.request({id:this.allocId(),op:"getXferState"}),Z=sQ(Q);if(Z!==void 0)this.cachedXferState=Z}markReady(){let V=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V()}probeReady(){return new Promise((V,$)=>{let Q=this.allocId();this.pending.set(Q,{resolve:(Z)=>{if(Z==="pong"){this.markReady(),V();return}$(Error(`${P0} worker probe ping failed`))},reject:$}),this.worker.postMessage({id:Q,op:"ping"})})}async ping(){if(await this.ready,await this.request({id:this.allocId(),op:"ping"})!=="pong")throw Error(`${P0} worker ping failed`)}terminate(){this.scheduledSync.cancel(),this.worker.terminate();for(let[,V]of this.pending)V.reject(Error(`${P0} worker terminated`));this.pending.clear()}onMessage(V){if(!dQ(V))return;let $=V;switch($.kind){case"ready":{this.markReady();return}case"clientState":{this.cachedClientState=$.state,this.clientState.emit();return}case"xferState":{this.cachedXferState=$.state,this.xferState.emit();return}case"dirty":{this.state.refresh($.eids.map(FJ));return}case"wiped":{this.state.clear();return}case"reply":{let Q=this.pending.get($.id);if(!Q)return;if(this.pending.delete($.id),$.ok)Q.resolve($.result);else Q.reject(new nV($.status));return}default:return}}allocId(){let V=this.nextId;return this.nextId+=1,V}request(V,$){return new Promise((Q,Z)=>{if(this.pending.set(V.id,{resolve:Q,reject:Z}),$&&$.length>0)this.worker.postMessage(V,$);else this.worker.postMessage(V)})}async requestStatus(V,$){try{let Q=await this.request(V,$),Z=oQ(Q);if(Z!==void 0)return Z;return 0}catch(Q){if(Q instanceof nV)return Q.status;return 12}}serializeHost(V){return{handle:V.handle.href,label:V.label,idx:V.idx??0}}async setSeed(V){await this.ready,await this.local.setSeed(V);let $=V.slice();await this.request({id:this.allocId(),op:"setSeed",seed:$},[$.buffer])}async link(V,$=!0){await this.ready,await this.local.link(V,!1),await this.request({id:this.allocId(),op:"link",host:this.serializeHost(V),connect:$})}async unlink(V){await this.ready,await this.local.unlink(V),await this.request({id:this.allocId(),op:"unlink",label:V})}async hosts(){return await this.ready,this.local.hosts()}async connect(V=!0,$=!0){await this.ready,await this.request({id:this.allocId(),op:"connect",listen:V,sync:$})}async disconnect(){await this.ready,await this.request({id:this.allocId(),op:"disconnect"})}async insertRaw(V){return await this.ready,this.local.insertRaw(V)}async updateRaw(V,$,Q){return await this.ready,this.local.updateRaw(V,$,Q)}async insert(V){return await this.ready,this.local.insert(V)}async update(V){return await this.ready,this.local.update(V)}async delete(V){return await this.ready,this.local.delete(V)}async genEID(V){return await this.ready,this.local.genEID(V)}async sync(){return await this.ready,this.requestStatus({id:this.allocId(),op:"sync"})}async wipe(){await this.ready,await this.request({id:this.allocId(),op:"wipe"})}async import(V){await this.ready;let $=new Uint8Array(await V.arrayBuffer());return this.requestStatus({id:this.allocId(),op:"import",bytes:$},[$.buffer])}async export(V,$){await this.ready;try{let Q=await this.request({id:this.allocId(),op:"export"});if(!(Q instanceof Uint8Array))return 12;let Z=new Blob([Q.slice()]);return EV(Z,V),0}catch(Q){if(Q instanceof nV)return Q.status;return 12}}}class nV extends Error{status;constructor(V){super(`WorkerReplyError: ${_[V]}`);this.status=V;this.name="WorkerReplyError"}}function FJ(V){return V}var B0="[DIPLOMATIC]";async function yV(V){let $=V.clock??new R0;if(V.worker!==void 0&&UJ(V)!==void 0)throw Error(`${B0} worker path requires IndexedDB on both sides; do not pass store (got a custom store)`);if(V.worker===void 0){console.info(`${B0} sync on main thread `+"(no worker — app did not request a worker)");let J=await tQ(V.store);return OJ($,V.state,J)}if(typeof Worker>"u")throw Error(`${B0} worker was provided but Worker API is unavailable`);let Q=await tQ(void 0);console.info(`${B0} attaching app-provided sync worker…`);let Z=await wV.connect(V.state,Q,{worker:V.worker,readyTimeoutMs:V.readyTimeoutMs,clock:$,syncDebounceMs:V.syncDebounceMs});return await Z.ping(),console.info(`${B0} sync worker active (network + EntDB writes off main; local mutates on main; dirty signals only)`),{client:Z,mode:"worker",dispose:()=>{console.info(`${B0} terminating sync worker`),Z.terminate()}}}function UJ(V){if("store"in V)return V.store;return}async function OJ(V,$,Q){let Z=new f0(V,$,Q,CV,J0);return{client:Z,mode:"main",dispose:()=>{Z.disconnect()}}}async function tQ(V){if(V!==void 0)return V;if(typeof indexedDB>"u")throw Error(`${B0} IndexedDB is unavailable; pass store explicitly (e.g. new MemoryStore(crypto))`);return uV(J0)}function qJ(V){let[$,Q]=n$();return bV(()=>{async function Z(){let I=await V.clientState.get();Q(I)}let J=V.clientState.listen(Z);return Z(),()=>{J()}},[V]),$}function HJ(V){let[$,Q]=n$();return bV(()=>{async function Z(){let I=await V.xferState.get();Q(I)}let J=V.xferState.listen(Z);return Z(),()=>{J()}},[V]),$}function PJ(V){bV(()=>{async function $(){try{await V.connect(),await V.sync()}catch(I){console.error("reconnectAndSync failed",I)}}function Q(){$()}function Z(){if(typeof document<"u"&&document.visibilityState==="visible")$()}function J(){$()}if(globalThis.addEventListener("online",Q),typeof document<"u")document.addEventListener("visibilitychange",Z);return globalThis.addEventListener("focus",J),globalThis.addEventListener("pageshow",J),()=>{if(globalThis.removeEventListener("online",Q),typeof document<"u")document.removeEventListener("visibilitychange",Z);globalThis.removeEventListener("focus",J),globalThis.removeEventListener("pageshow",J)}},[V])}function CJ(V={}){let $=V.clock??new R0,{seed:Q,host:Z,readyTimeoutMs:J}=V,I=V.worker,W="store"in V?V.store:void 0,[Y,X]=n$({stateMgr:Y$});return bV(()=>{let G=!1,K;return(async()=>{let w=await w$();if(G)return;let N=jV(w),z=I!==void 0?await yV({state:N,clock:$,worker:I,readyTimeoutMs:J}):await yV({state:N,clock:$,store:W,readyTimeoutMs:J});if(G){z.dispose();return}K=z.dispose;let{client:F,mode:R}=z;if(Q)await F.setSeed(Q);if(Z)await F.link(Z);if(G){K();return}X({client:F,entDB:w,stateMgr:N,mode:R,error:void 0})})().catch((w)=>{let N=w instanceof Error?w:Error(String(w));if(console.error("[DIPLOMATIC] useClient init failed",N),!G)X((z)=>({...z,client:void 0,error:N}))}),()=>{G=!0,K?.()}},[$,Q,Z,I,W,J]),Y}import{use as TJ,useEffect as eQ,useRef as DJ,useState as AJ}from"react";function VZ(V,$,Q){let[Z,J]=AJ();return eQ(()=>{async function I(){let W=await Q();J(W)}return I(),V.on($,I),()=>{V.off($,I)}},[V,$,Q]),Z}function _J(V,$,Q){let Z=DJ(Q());return eQ(()=>{async function J(){Z.current=Q()}return V.on($,J),()=>{V.off($,J)}},[V,$,Q]),TJ(Z.current)}function $Z(V,$){return`${V}:${$}`}class y${queue=new Map;async enq(V){for(let $ of V){let Q=$Z($.host,$.seq);this.queue.set(Q,$)}}async deq(V,$){for(let Q of $){let Z=$Z(V,Q);this.queue.delete(Z)}}async list(){let V=[];for(let $ of this.queue.values())V.push($);return V}async count(){return this.queue.size}async wipe(){this.queue.clear()}}class b${hosts=new Map;async add(V){let $={...V,lastSeq:0};this.hosts.set(V.label,$)}async touch(V,$){let Q=this.hosts.get(V);if(!Q||$<=Q.lastSeq)return;this.hosts.set(V,{...Q,lastSeq:$})}async get(V){return this.hosts.get(V)}async set(V,$){let Q=this.hosts.get(V);if(!Q)return 13;return this.hosts.set(V,{...Q,...$}),0}async del(V){this.hosts.delete(V)}async list(){return this.hosts.values()}async wipe(){this.hosts.clear()}}class p${crypto;messages=new Map;constructor(V){this.crypto=V}async add(V){let $=[];for(let{key:Q,data:Z}of V)this.messages.set(L(Q),Z),$.push(0);return $}async del(V){for(let $ of V)this.messages.delete(L($))}async get(V){let $=this.messages.get(L(V));if($)return await L0(V,$,this.crypto);return}async has(V){return this.messages.has(L(V))}async list(V){let $=[];for(let[Q,Z]of this.messages){if(V!==void 0&&XV(Z.apld)!==V)continue;let J=X0(Q);$.push(await L0(J,Z,this.crypto))}return $}async last(V){let $;for(let[Q,Z]of this.messages){if(s(V,Z.eid)===!1)continue;let J=X0(Q);if($===void 0)$={hash:J,data:Z};else if((Z.ctr??0)>($.data.ctr??0)||(Z.ctr??0)===($.data.ctr??0)&&(Z.off??0)>($.data.off??0))$={hash:J,data:Z}}if($)return await L0($.hash,$.data,this.crypto);return}async markApplied(V){for(let $ of V){let Q=this.messages.get(L($));if(!Q)continue;S0(Q,j0)}}async markFailed(V){for(let{key:$,err:Q}of V){let Z=this.messages.get(L($));if(!Z)continue;S0(Z,K0,Q)}}async wipe(){this.messages.clear()}}class l${enclave;async save(V){return this.enclave=new s0(V,J0),this.enclave}async load(){return this.enclave}async wipe(){this.enclave=void 0}}class h${queue=new Map;async enq(V,$){let Q=this.queue.get(V)||new Set;this.queue.set(V,Q);for(let Z of $)Q.add(a(Z))}async deq(V,$){let Q=this.queue.get(V);if(Q)for(let Z of $)Q.delete(a(Z))}async list(V){let $=this.queue.get(V);if(!$)return[];let Q=[];for(let Z of $)Q.push(_0(Z));return Q}async count(){let V=0;for(let $ of this.queue.values())V+=$.size;return V}async wipe(){this.queue.clear()}}class QZ{seed=new l$;hosts=new b$;uploads=new h$;downloads=new y$;messages;constructor(V){this.messages=new p$(V)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}class ZZ{singletonType;latest;latestOff=-1;emitter=new C0;constructor(V){this.singletonType=V}async apply(V){for(let $ of V){let Q=new f($.eid),[Z,J]=Q.readStruct(r);if(J!==0)continue;let I=new k;I.writeVarString(this.singletonType);let W=I.result();if(Z.id.length===W.length&&Z.id.every((Y,X)=>Y===W[X])){if(this.latest===void 0||$.off>this.latestOff)this.latestOff=$.off,this.latest=$.bod,this.emitter.emit(this.singletonType,null)}}return V.map(()=>0)}clear=async()=>{return this.latest=void 0,this.latestOff=-1,this.emitter.emit(this.singletonType,null),0};notify=(V)=>{for(let $ of V)if($===this.singletonType)this.emitter.emit(this.singletonType,null)};refresh=async(V)=>{this.notify([this.singletonType])};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}async function JN(V,$){let Q=await uV(J0),Z=new f0(new R0,V,Q,CV,J0);return{client:Z,setSeed:async(I)=>{let W=_0(I);await Q.seed.save(W),await Q.hosts.add({handle:$,label:"host",idx:0}),await Z.connect()}}}export{PJ as useSyncOnResume,_J as useStateWatcherSuspense,VZ as useStateWatcher,HJ as useClientXferState,qJ as useClientState,CJ as useClient,R$ as shouldEmitItemProgress,S0 as setApld,N$ as revFromHead,yZ as revFromEntity,uV as openIDBStore,w$ as openEntDB,yV as openDiplomaticClient,Y$ as nullStateManager,bZ as nullEntDB,F$ as isTerminalApplyFailure,hZ as isPendingApply,lZ as isApldState,E0 as idleProgress,_0 as htob,CV as hostHTTPTransport,JN as genWebClient,EZ as genSingletonEID,jV as entStateManager,r as eidCodec,YV as defaultPeekProgressEvery,J0 as crypto,a as btoh,XV as apldFromStored,wV as WorkerClient,C0 as TypedEventEmitter,f0 as SyncClient,_ as Status,ZV as StateManager,ZZ as SingletonStateManager,QZ as MemoryStore,u$ as IDBStore,Z$ as HTTPTransport,M$ as EntIDB,_V as EntDBMemory,k as Encoder,f as Decoder,R0 as Clock,JV as CachedEntDB,z0 as APLD_PENDING,K0 as APLD_ERROR,j0 as APLD_APPLIED};
1
+ function r$(V){let $=V.length,Q=0,Z=0;while(Z<$){let J=V.charCodeAt(Z++);if((J&4294967168)===0){Q++;continue}else if((J&4294965248)===0)Q+=2;else{if(J>=55296&&J<=56319){if(Z<$){let I=V.charCodeAt(Z);if((I&64512)===56320)++Z,J=((J&1023)<<10)+(I&1023)+65536}}if((J&4294901760)===0)Q+=3;else Q+=4}}return Q}function JZ(V,$,Q){let Z=V.length,J=Q,I=0;while(I<Z){let W=V.charCodeAt(I++);if((W&4294967168)===0){$[J++]=W;continue}else if((W&4294965248)===0)$[J++]=W>>6&31|192;else{if(W>=55296&&W<=56319){if(I<Z){let Y=V.charCodeAt(I);if((Y&64512)===56320)++I,W=((W&1023)<<10)+(Y&1023)+65536}}if((W&4294901760)===0)$[J++]=W>>12&15|224,$[J++]=W>>6&63|128;else $[J++]=W>>18&7|240,$[J++]=W>>12&63|128,$[J++]=W>>6&63|128}$[J++]=W&63|128}}var IZ=new TextEncoder,WZ=50;function YZ(V,$,Q){IZ.encodeInto(V,$.subarray(Q))}function c$(V,$,Q){if(V.length>WZ)YZ(V,$,Q);else JZ(V,$,Q)}var XZ=4096;function pV(V,$,Q){let Z=$,J=Z+Q,I=[],W="";while(Z<J){let Y=V[Z++];if((Y&128)===0)I.push(Y);else if((Y&224)===192){let X=V[Z++]&63;I.push((Y&31)<<6|X)}else if((Y&240)===224){let X=V[Z++]&63,G=V[Z++]&63;I.push((Y&31)<<12|X<<6|G)}else if((Y&248)===240){let X=V[Z++]&63,G=V[Z++]&63,K=V[Z++]&63,w=(Y&7)<<18|X<<12|G<<6|K;if(w>65535)w-=65536,I.push(w>>>10&1023|55296),w=56320|w&1023;I.push(w)}else I.push(Y);if(I.length>=XZ)W+=String.fromCharCode(...I),I.length=0}if(I.length>0)W+=String.fromCharCode(...I);return W}var GZ=new TextDecoder,KZ=200;function MZ(V,$,Q){let Z=V.subarray($,$+Q);return GZ.decode(Z)}function d$(V,$,Q){if(Q>KZ)return MZ(V,$,Q);else return pV(V,$,Q)}class y0{type;data;constructor(V,$){this.type=V,this.data=$}}class e extends Error{constructor(V){super(V);let $=Object.create(e.prototype);Object.setPrototypeOf(this,$),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}}var b0=4294967295;function o$(V,$,Q){let Z=Q/4294967296,J=Q;V.setUint32($,Z),V.setUint32($+4,J)}function NV(V,$,Q){let Z=Math.floor(Q/4294967296),J=Q;V.setUint32($,Z),V.setUint32($+4,J)}function RV(V,$){let Q=V.getInt32($),Z=V.getUint32($+4);return Q*4294967296+Z}function a$(V,$){let Q=V.getUint32($),Z=V.getUint32($+4);return Q*4294967296+Z}var wZ=-1,NZ=4294967295,RZ=17179869183;function zZ({sec:V,nsec:$}){if(V>=0&&$>=0&&V<=RZ)if($===0&&V<=NZ){let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,V),Q}else{let Q=V/4294967296,Z=V&4294967295,J=new Uint8Array(8),I=new DataView(J.buffer);return I.setUint32(0,$<<2|Q&3),I.setUint32(4,Z),J}else{let Q=new Uint8Array(12),Z=new DataView(Q.buffer);return Z.setUint32(0,$),NV(Z,4,V),Q}}function FZ(V){let $=V.getTime(),Q=Math.floor($/1000),Z=($-Q*1000)*1e6,J=Math.floor(Z/1e9);return{sec:Q+J,nsec:Z-J*1e9}}function UZ(V){if(V instanceof Date){let $=FZ(V);return zZ($)}else return null}function OZ(V){let $=new DataView(V.buffer,V.byteOffset,V.byteLength);switch(V.byteLength){case 4:{let Q=$.getUint32(0),Z=0;return{sec:Q,nsec:0}}case 8:{let Q=$.getUint32(0),Z=$.getUint32(4),J=(Q&3)*4294967296+Z,I=Q>>>2;return{sec:J,nsec:I}}case 12:{let Q=RV($,4),Z=$.getUint32(0);return{sec:Q,nsec:Z}}default:throw new e(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${V.length}`)}}function qZ(V){let $=OZ(V);return new Date($.sec*1000+$.nsec/1e6)}var s$={type:wZ,encode:UZ,decode:qZ};class p0{static defaultCodec=new p0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(s$)}register({type:V,encode:$,decode:Q}){if(V>=0)this.encoders[V]=$,this.decoders[V]=Q;else{let Z=-1-V;this.builtInEncoders[Z]=$,this.builtInDecoders[Z]=Q}}tryToEncode(V,$){for(let Q=0;Q<this.builtInEncoders.length;Q++){let Z=this.builtInEncoders[Q];if(Z!=null){let J=Z(V,$);if(J!=null){let I=-1-Q;return new y0(I,J)}}}for(let Q=0;Q<this.encoders.length;Q++){let Z=this.encoders[Q];if(Z!=null){let J=Z(V,$);if(J!=null)return new y0(Q,J)}}if(V instanceof y0)return V;return null}decode(V,$,Q){let Z=$<0?this.builtInDecoders[-1-$]:this.decoders[$];if(Z)return Z(V,$,Q);else return new y0($,V)}}function HZ(V){return V instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&V instanceof SharedArrayBuffer}function t0(V){if(V instanceof Uint8Array)return V;else if(ArrayBuffer.isView(V))return new Uint8Array(V.buffer,V.byteOffset,V.byteLength);else if(HZ(V))return new Uint8Array(V);else return Uint8Array.from(V)}var PZ=100,CZ=2048;class zV{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??p0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.maxDepth=V?.maxDepth??PZ,this.initialBufferSize=V?.initialBufferSize??CZ,this.sortKeys=V?.sortKeys??!1,this.forceFloat32=V?.forceFloat32??!1,this.ignoreUndefined=V?.ignoreUndefined??!1,this.forceIntegerToFloat=V?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new zV({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(V){if(this.entered)return this.clone().encodeSharedRef(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(V){if(this.entered)return this.clone().encode(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(V,$){if($>this.maxDepth)throw Error(`Too deep objects in depth ${$}`);if(V==null)this.encodeNil();else if(typeof V==="boolean")this.encodeBoolean(V);else if(typeof V==="number")if(!this.forceIntegerToFloat)this.encodeNumber(V);else this.encodeNumberAsFloat(V);else if(typeof V==="string")this.encodeString(V);else if(this.useBigInt64&&typeof V==="bigint")this.encodeBigInt64(V);else this.encodeObject(V,$)}ensureBufferSizeToWrite(V){let $=this.pos+V;if(this.view.byteLength<$)this.resizeBuffer($*2)}resizeBuffer(V){let $=new ArrayBuffer(V),Q=new Uint8Array($),Z=new DataView($);Q.set(this.bytes),this.view=Z,this.bytes=Q}encodeNil(){this.writeU8(192)}encodeBoolean(V){if(V===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber(V){if(!this.forceIntegerToFloat&&Number.isSafeInteger(V))if(V>=0)if(V<128)this.writeU8(V);else if(V<256)this.writeU8(204),this.writeU8(V);else if(V<65536)this.writeU8(205),this.writeU16(V);else if(V<4294967296)this.writeU8(206),this.writeU32(V);else if(!this.useBigInt64)this.writeU8(207),this.writeU64(V);else this.encodeNumberAsFloat(V);else if(V>=-32)this.writeU8(224|V+32);else if(V>=-128)this.writeU8(208),this.writeI8(V);else if(V>=-32768)this.writeU8(209),this.writeI16(V);else if(V>=-2147483648)this.writeU8(210),this.writeI32(V);else if(!this.useBigInt64)this.writeU8(211),this.writeI64(V);else this.encodeNumberAsFloat(V);else this.encodeNumberAsFloat(V)}encodeNumberAsFloat(V){if(this.forceFloat32)this.writeU8(202),this.writeF32(V);else this.writeU8(203),this.writeF64(V)}encodeBigInt64(V){if(V>=BigInt(0))this.writeU8(207),this.writeBigUint64(V);else this.writeU8(211),this.writeBigInt64(V)}writeStringHeader(V){if(V<32)this.writeU8(160+V);else if(V<256)this.writeU8(217),this.writeU8(V);else if(V<65536)this.writeU8(218),this.writeU16(V);else if(V<4294967296)this.writeU8(219),this.writeU32(V);else throw Error(`Too long string: ${V} bytes in UTF-8`)}encodeString(V){let Q=r$(V);this.ensureBufferSizeToWrite(5+Q),this.writeStringHeader(Q),c$(V,this.bytes,this.pos),this.pos+=Q}encodeObject(V,$){let Q=this.extensionCodec.tryToEncode(V,this.context);if(Q!=null)this.encodeExtension(Q);else if(Array.isArray(V))this.encodeArray(V,$);else if(ArrayBuffer.isView(V))this.encodeBinary(V);else if(typeof V==="object")this.encodeMap(V,$);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply(V)}`)}encodeBinary(V){let $=V.byteLength;if($<256)this.writeU8(196),this.writeU8($);else if($<65536)this.writeU8(197),this.writeU16($);else if($<4294967296)this.writeU8(198),this.writeU32($);else throw Error(`Too large binary: ${$}`);let Q=t0(V);this.writeU8a(Q)}encodeArray(V,$){let Q=V.length;if(Q<16)this.writeU8(144+Q);else if(Q<65536)this.writeU8(220),this.writeU16(Q);else if(Q<4294967296)this.writeU8(221),this.writeU32(Q);else throw Error(`Too large array: ${Q}`);for(let Z of V)this.doEncode(Z,$+1)}countWithoutUndefined(V,$){let Q=0;for(let Z of $)if(V[Z]!==void 0)Q++;return Q}encodeMap(V,$){let Q=Object.keys(V);if(this.sortKeys)Q.sort();let Z=this.ignoreUndefined?this.countWithoutUndefined(V,Q):Q.length;if(Z<16)this.writeU8(128+Z);else if(Z<65536)this.writeU8(222),this.writeU16(Z);else if(Z<4294967296)this.writeU8(223),this.writeU32(Z);else throw Error(`Too large map object: ${Z}`);for(let J of Q){let I=V[J];if(!(this.ignoreUndefined&&I===void 0))this.encodeString(J),this.doEncode(I,$+1)}}encodeExtension(V){if(typeof V.data==="function"){let Q=V.data(this.pos+6),Z=Q.length;if(Z>=4294967296)throw Error(`Too large extension object: ${Z}`);this.writeU8(201),this.writeU32(Z),this.writeI8(V.type),this.writeU8a(Q);return}let $=V.data.length;if($===1)this.writeU8(212);else if($===2)this.writeU8(213);else if($===4)this.writeU8(214);else if($===8)this.writeU8(215);else if($===16)this.writeU8(216);else if($<256)this.writeU8(199),this.writeU8($);else if($<65536)this.writeU8(200),this.writeU16($);else if($<4294967296)this.writeU8(201),this.writeU32($);else throw Error(`Too large extension object: ${$}`);this.writeI8(V.type),this.writeU8a(V.data)}writeU8(V){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,V),this.pos++}writeU8a(V){let $=V.length;this.ensureBufferSizeToWrite($),this.bytes.set(V,this.pos),this.pos+=$}writeI8(V){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,V),this.pos++}writeU16(V){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,V),this.pos+=2}writeI16(V){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,V),this.pos+=2}writeU32(V){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,V),this.pos+=4}writeI32(V){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,V),this.pos+=4}writeF32(V){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,V),this.pos+=4}writeF64(V){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,V),this.pos+=8}writeU64(V){this.ensureBufferSizeToWrite(8),o$(this.view,this.pos,V),this.pos+=8}writeI64(V){this.ensureBufferSizeToWrite(8),NV(this.view,this.pos,V),this.pos+=8}writeBigUint64(V){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,V),this.pos+=8}writeBigInt64(V){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,V),this.pos+=8}}function m0(V,$){return new zV($).encodeSharedRef(V)}function FV(V){return`${V<0?"-":""}0x${Math.abs(V).toString(16).padStart(2,"0")}`}var TZ=16,DZ=16;class lV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(V=TZ,$=DZ){this.maxKeyLength=V,this.maxLengthPerKey=$,this.caches=[];for(let Q=0;Q<this.maxKeyLength;Q++)this.caches.push([])}canBeCached(V){return V>0&&V<=this.maxKeyLength}find(V,$,Q){let Z=this.caches[Q-1];V:for(let J of Z){let I=J.bytes;for(let W=0;W<Q;W++)if(I[W]!==V[$+W])continue V;return J.str}return null}store(V,$){let Q=this.caches[V.length-1],Z={bytes:V,str:$};if(Q.length>=this.maxLengthPerKey)Q[Math.random()*Q.length|0]=Z;else Q.push(Z)}decode(V,$,Q){let Z=this.find(V,$,Q);if(Z!=null)return this.hit++,Z;this.miss++;let J=pV(V,$,Q),I=Uint8Array.prototype.slice.call(V,$,$+Q);return this.store(I,J),J}}var hV="array",VV="map_key",e$="map_value",AZ=(V)=>{if(typeof V==="string"||typeof V==="number")return V;throw new e("The type of key must be string or number but "+typeof V)};class VQ{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(V){let $=this.getUninitializedStateFromPool();$.type=hV,$.position=0,$.size=V,$.array=Array(V)}pushMapState(V){let $=this.getUninitializedStateFromPool();$.type=VV,$.readCount=0,$.size=V,$.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let V={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(V)}return this.stack[this.stackHeadPosition]}release(V){if(this.stack[this.stackHeadPosition]!==V)throw Error("Invalid stack state. Released state is not on top of the stack.");if(V.type===hV){let Q=V;Q.size=0,Q.array=void 0,Q.position=0,Q.type=void 0}if(V.type===VV||V.type===e$){let Q=V;Q.size=0,Q.map=void 0,Q.readCount=0,Q.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var e0=-1,rV=new DataView(new ArrayBuffer(0)),_Z=new Uint8Array(rV.buffer);try{rV.getInt8(0)}catch(V){if(!(V instanceof RangeError))throw Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var t$=RangeError("Insufficient data"),jZ=new lV;class UV{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=rV;bytes=_Z;headByte=e0;stack=new VQ;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??p0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.rawStrings=V?.rawStrings??!1,this.maxStrLength=V?.maxStrLength??b0,this.maxBinLength=V?.maxBinLength??b0,this.maxArrayLength=V?.maxArrayLength??b0,this.maxMapLength=V?.maxMapLength??b0,this.maxExtLength=V?.maxExtLength??b0,this.keyDecoder=V?.keyDecoder!==void 0?V.keyDecoder:jZ,this.mapKeyConverter=V?.mapKeyConverter??AZ}clone(){return new UV({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=e0,this.stack.reset()}setBuffer(V){let $=t0(V);this.bytes=$,this.view=new DataView($.buffer,$.byteOffset,$.byteLength),this.pos=0}appendBuffer(V){if(this.headByte===e0&&!this.hasRemaining(1))this.setBuffer(V);else{let $=this.bytes.subarray(this.pos),Q=t0(V),Z=new Uint8Array($.length+Q.length);Z.set($),Z.set(Q,$.length),this.setBuffer(Z)}}hasRemaining(V){return this.view.byteLength-this.pos>=V}createExtraByteError(V){let{view:$,pos:Q}=this;return RangeError(`Extra ${$.byteLength-Q} of ${$.byteLength} byte(s) found at buffer[${V}]`)}decode(V){if(this.entered)return this.clone().decode(V);try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);let $=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return $}finally{this.entered=!1}}*decodeMulti(V){if(this.entered){yield*this.clone().decodeMulti(V);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(V){if(this.entered)return this.clone().decodeAsync(V);try{this.entered=!0;let $=!1,Q;for await(let W of V){if($)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(W);try{Q=this.doDecodeSync(),$=!0}catch(Y){if(!(Y instanceof RangeError))throw Y}this.totalPos+=this.pos}if($){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Q}let{headByte:Z,pos:J,totalPos:I}=this;throw RangeError(`Insufficient data in parsing ${FV(Z)} at ${I} (${J} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(V){return this.decodeMultiAsync(V,!0)}decodeStream(V){return this.decodeMultiAsync(V,!1)}async*decodeMultiAsync(V,$){if(this.entered){yield*this.clone().decodeMultiAsync(V,$);return}try{this.entered=!0;let Q=$,Z=-1;for await(let J of V){if($&&Z===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(J),Q)Z=this.readArraySize(),Q=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--Z===0)break}catch(I){if(!(I instanceof RangeError))throw I}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){V:while(!0){let V=this.readHeadByte(),$;if(V>=224)$=V-256;else if(V<192)if(V<128)$=V;else if(V<144){let Z=V-128;if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V<160){let Z=V-144;if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else{let Z=V-160;$=this.decodeString(Z,0)}else if(V===192)$=null;else if(V===194)$=!1;else if(V===195)$=!0;else if(V===202)$=this.readF32();else if(V===203)$=this.readF64();else if(V===204)$=this.readU8();else if(V===205)$=this.readU16();else if(V===206)$=this.readU32();else if(V===207)if(this.useBigInt64)$=this.readU64AsBigInt();else $=this.readU64();else if(V===208)$=this.readI8();else if(V===209)$=this.readI16();else if(V===210)$=this.readI32();else if(V===211)if(this.useBigInt64)$=this.readI64AsBigInt();else $=this.readI64();else if(V===217){let Z=this.lookU8();$=this.decodeString(Z,1)}else if(V===218){let Z=this.lookU16();$=this.decodeString(Z,2)}else if(V===219){let Z=this.lookU32();$=this.decodeString(Z,4)}else if(V===220){let Z=this.readU16();if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else if(V===221){let Z=this.readU32();if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else if(V===222){let Z=this.readU16();if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V===223){let Z=this.readU32();if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V===196){let Z=this.lookU8();$=this.decodeBinary(Z,1)}else if(V===197){let Z=this.lookU16();$=this.decodeBinary(Z,2)}else if(V===198){let Z=this.lookU32();$=this.decodeBinary(Z,4)}else if(V===212)$=this.decodeExtension(1,0);else if(V===213)$=this.decodeExtension(2,0);else if(V===214)$=this.decodeExtension(4,0);else if(V===215)$=this.decodeExtension(8,0);else if(V===216)$=this.decodeExtension(16,0);else if(V===199){let Z=this.lookU8();$=this.decodeExtension(Z,1)}else if(V===200){let Z=this.lookU16();$=this.decodeExtension(Z,2)}else if(V===201){let Z=this.lookU32();$=this.decodeExtension(Z,4)}else throw new e(`Unrecognized type byte: ${FV(V)}`);this.complete();let Q=this.stack;while(Q.length>0){let Z=Q.top();if(Z.type===hV)if(Z.array[Z.position]=$,Z.position++,Z.position===Z.size)$=Z.array,Q.release(Z);else continue V;else if(Z.type===VV){if($==="__proto__")throw new e("The key __proto__ is not allowed");Z.key=this.mapKeyConverter($),Z.type=e$;continue V}else if(Z.map[Z.key]=$,Z.readCount++,Z.readCount===Z.size)$=Z.map,Q.release(Z);else{Z.key=null,Z.type=VV;continue V}}return $}}readHeadByte(){if(this.headByte===e0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=e0}readArraySize(){let V=this.readHeadByte();switch(V){case 220:return this.readU16();case 221:return this.readU32();default:if(V<160)return V-144;else throw new e(`Unrecognized array type byte: ${FV(V)}`)}}pushMapState(V){if(V>this.maxMapLength)throw new e(`Max length exceeded: map length (${V}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(V)}pushArrayState(V){if(V>this.maxArrayLength)throw new e(`Max length exceeded: array length (${V}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(V)}decodeString(V,$){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String(V,$);return this.decodeBinary(V,$)}decodeUtf8String(V,$){if(V>this.maxStrLength)throw new e(`Max length exceeded: UTF-8 byte length (${V}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+$+V)throw t$;let Q=this.pos+$,Z;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached(V))Z=this.keyDecoder.decode(this.bytes,Q,V);else Z=d$(this.bytes,Q,V);return this.pos+=$+V,Z}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===VV;return!1}decodeBinary(V,$){if(V>this.maxBinLength)throw new e(`Max length exceeded: bin length (${V}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(V+$))throw t$;let Q=this.pos+$,Z=this.bytes.subarray(Q,Q+V);return this.pos+=$+V,Z}decodeExtension(V,$){if(V>this.maxExtLength)throw new e(`Max length exceeded: ext length (${V}) > maxExtLength (${this.maxExtLength})`);let Q=this.view.getInt8(this.pos+$),Z=this.decodeBinary(V,$+1);return this.extensionCodec.decode(Z,Q,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let V=this.view.getUint8(this.pos);return this.pos++,V}readI8(){let V=this.view.getInt8(this.pos);return this.pos++,V}readU16(){let V=this.view.getUint16(this.pos);return this.pos+=2,V}readI16(){let V=this.view.getInt16(this.pos);return this.pos+=2,V}readU32(){let V=this.view.getUint32(this.pos);return this.pos+=4,V}readI32(){let V=this.view.getInt32(this.pos);return this.pos+=4,V}readU64(){let V=a$(this.view,this.pos);return this.pos+=8,V}readI64(){let V=RV(this.view,this.pos);return this.pos+=8,V}readU64AsBigInt(){let V=this.view.getBigUint64(this.pos);return this.pos+=8,V}readI64AsBigInt(){let V=this.view.getBigInt64(this.pos);return this.pos+=8,V}readF32(){let V=this.view.getFloat32(this.pos);return this.pos+=4,V}readF64(){let V=this.view.getFloat64(this.pos);return this.pos+=8,V}}function cV(V,$){return new UV($).decode(V)}class C0{listeners=new Map;addEventListener(V,$){let Q=this.listeners.get(V);if(!Q)Q=new Set,this.listeners.set(V,Q);return Q.add($),()=>{this.removeEventListener(V,$)}}removeEventListener(V,$){let Q=this.listeners.get(V);if(Q){if(Q.delete($),Q.size===0)this.listeners.delete(V)}}emit(V,$){let Q=this.listeners.get(V);if(Q){let Z=Array.from(Q);for(let J of Z)J($)}}emitAll(V){let $=Array.from(this.listeners.keys());for(let Q of $)this.emit(Q,V)}}class G0{getter;static eventName="update";emitter;constructor(V){this.getter=V;this.emitter=new C0}get=()=>this.getter();async emit(){let V=await this.getter();queueMicrotask(()=>this.emitter.emit(G0.eventName,V))}listen(V){return this.emitter.addEventListener(G0.eventName,V),()=>{this.emitter.removeEventListener(G0.eventName,V)}}}var T0=64;var $Q=32,D0=8;var OV=32;var QQ=30000,ZQ=512,_;((C)=>{C[C.Success=0]="Success";C[C.InvalidSignature=3]="InvalidSignature";C[C.ClockOutOfSync=4]="ClockOutOfSync";C[C.UserNotRegistered=5]="UserNotRegistered";C[C.ServerMisconfigured=6]="ServerMisconfigured";C[C.MissingBody=7]="MissingBody";C[C.ExtraBodyContent=8]="ExtraBodyContent";C[C.MissingParam=9]="MissingParam";C[C.InvalidParam=10]="InvalidParam";C[C.InvalidRequest=11]="InvalidRequest";C[C.InternalError=12]="InternalError";C[C.NotFound=13]="NotFound";C[C.InvalidMessage=14]="InvalidMessage";C[C.NoChange=15]="NoChange";C[C.DatabaseClosed=16]="DatabaseClosed";C[C.StorageError=17]="StorageError";C[C.DatabaseError=18]="DatabaseError";C[C.HashMismatch=19]="HashMismatch";C[C.DecryptionError=20]="DecryptionError";C[C.NotImplemented=21]="NotImplemented";C[C.MissingSeed=22]="MissingSeed";C[C.OutOfBounds=23]="OutOfBounds";C[C.HostError=24]="HostError";C[C.CommunicationError=25]="CommunicationError";C[C.VarLimitExceeded=26]="VarLimitExceeded";C[C.InvalidResponse=27]="InvalidResponse";C[C.ConnectionClosed=28]="ConnectionClosed"})(_||={});function q(V){return[V,0]}function M(V){return[void 0,V]}function LZ(V){if(V<0)console.info("N",V),console.trace();if(typeof V!=="bigint")V=BigInt(V);if(V<0n)return M(10);let $=[];while(V>0n){let Q=Number(V&0x7fn);if(V>>=7n,V>0n)$.push(Q|128);else $.push(Q)}if($.length===0)return q(new Uint8Array([0]));if($.length>8)return M(26);return q(new Uint8Array($))}function mZ(V,$=0){let Q=0n,Z=0,J=$;while(!0){if(J>=V.length)return M(14);let I=V[J++];if(I===void 0)return M(14);if(Q|=BigInt(I&127)<<BigInt(Z),(I&128)===0){if(J-$>8)return M(26);return q({value:Q>0x1fffffffffffffn?Q:Number(Q),bytesRead:J-$})}if(Z+=7,Z>=56)return M(26)}}class f{data;pos=0;constructor(V){this.data=V}static async fromResponse(V){let $=await V.arrayBuffer(),Q=new Uint8Array($);return new f(Q)}readBigInt(){if(this.pos+8>this.data.length)return M(7);let V=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,q(V)}readDate(){let[V,$]=this.readVarInt();if($!==0)return M($);return q(new Date(V))}readVarInt(){let[V,$]=mZ(this.data,this.pos);if($!==0)return M($);this.pos+=V.bytesRead;let Q=V.value;return q(typeof Q==="bigint"?Number(Q):Q)}readVarString(){let[V,$]=this.readVarInt();if($!==0)return M($);let[Q,Z]=this.readBytes(V);if(Z!==0)return M(Z);let J=new TextDecoder().decode(Q);return q(J)}readBytes(V){if(V<0)return M(10);if(this.pos+V>this.data.length)return M(23);let $=this.data.slice(this.pos,this.pos+V);return this.pos+=V,q($)}readVarBytes(){let[V,$]=this.readVarInt();if($!==0)return M($);return this.readBytes(V)}readStruct(V){return V.decode(this)}readStructs(V){let $=[];while(!this.done()){let[Q,Z]=this.readStruct(V);if(Z!==0)return M(Z);$.push(Q)}return q($)}readBytesSeq(V){let $=[];while(!this.done()){let[Q,Z]=this.readBytes(V);if(Z!==0)return M(Z);$.push(Q)}return q($)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class k{parts=[];writeBigInt(V){let $=new Uint8Array(8);new DataView($.buffer).setBigUint64(0,V,!1),this.parts.push($)}writeDate(V){let $=V.getTime();return this.writeVarInt($)}writeVarInt(V){let[$,Q]=LZ(V);if(Q!==0)return Q;return this.parts.push($),0}writeVarString(V){let $=new TextEncoder().encode(V),Q=this.writeVarInt($.length);if(Q!==0)return Q;return this.writeBytes($),0}prependBytes(V){this.parts.unshift(V)}writeBytes(V){this.parts.push(V)}writeVarBytes(V){let $=this.writeVarInt(V.length);if($!==0)return $;return this.writeBytes(V),0}writeStruct(V,$){return V.encode(this,$)}writeStructs(V,$){for(let Q of $){let Z=this.writeStruct(V,Q);if(Z!==0)return Z}return 0}writeBytesSeq(V){for(let $ of V)this.writeBytes($)}result(){let V=this.parts.reduce((Z,J)=>Z+J.length,0),$=new Uint8Array(V),Q=0;for(let Z of this.parts)$.set(Z,Q),Q+=Z.length;return $}*scan(){for(let V of this.parts)yield V}}async function dV(V,$,Q){let Z=new k,J=Z.writeDate($);if(J!==0)return M(J);let I=Z.result(),W=await Q.signEd25519(I,V.privateKey);return q({pubKey:V.publicKey,sig:W,timestamp:$})}async function A0(V,$,Q){let Z=Q.now().getTime(),J=V.timestamp.getTime();if(Math.abs(Z-J)>QQ)return 4;let W=new k;W.writeDate(V.timestamp);let Y=W.result();if(!await $.checkSigEd25519(V.sig,Y,V.pubKey))return 3;return 0}var r={encode(V,$){let Q=V.writeVarBytes($.id);if(Q!==0)return Q;let Z=V.writeDate($.ts);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return M(Q);let[Z,J]=V.readDate();if(J!==0)return M(J);return q({id:$,ts:Z})}};function l0(V){let $=new k,Q=$.writeStruct(r,V);if(Q!==0)return M(Q);let Z=$.result();return q(Z)}async function EZ(V){return l0({id:V,ts:new Date(0)})}var Y0={encode(V,$){let Q=V.writeVarBytes($.eid);if(Q!==0)return Q;let Z=V.writeVarInt($.off);if(Z!==0)return Z;let J=V.writeVarInt($.ctr);if(J!==0)return J;let I=V.writeVarInt($.len);if(I!==0)return I;if($.hsh)V.writeBytes($.hsh);return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return M(Q);let Z=new f($),[,J]=r.decode(Z);if(J!==0)return M(J);let[I,W]=V.readVarInt();if(W!==0)return M(W);let[Y,X]=V.readVarInt();if(X!==0)return M(X);let[G,K]=V.readVarInt();if(K!==0)return M(K);let w;if(G>0){let[N,z]=V.readBytes(OV);if(z!==0)return M(z);w=N}return q({eid:$,off:I,ctr:Y,len:G,hsh:w})}};function a(V){return Array.from(V).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}function _0(V){if(V.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(V.length/2);for(let Q=0;Q<V.length;Q+=2)$[Q/2]=Number.parseInt(V.substr(Q,2),16);return $}function s(V,$){if(V===$)return!0;if(V.byteLength!==$.byteLength)return!1;return V.every((Q,Z)=>Q===$[Z])}var L;if(typeof Uint8Array.prototype.toBase64==="function")L=(V)=>V.toBase64();else L=(V)=>btoa(String.fromCharCode(...V));var X0;if(typeof Uint8Array.fromBase64==="function")X0=(V)=>Uint8Array.fromBase64(V);else X0=(V)=>Uint8Array.from(atob(V),($)=>$.charCodeAt(0));function $V(V,$){let Q=new Uint8Array(V.length+$.length);return Q.set(V,0),Q.set($,V.length),Q}function JQ(V,$,Q){return Q.checkSigEd25519(V.sig,V.headCph,$)}async function oV(V,$,Q){let Z=$V($.privateKey,V);return(await Q.blake3(Z)).slice(0,D0)}async function IQ(V,$,Q,Z){let J;if(V.bod&&V.len>0)J=await Q.blake3(V.bod);let I=new k,W=Y0.encode(I,{...V,hsh:J});if(W!==0)return M(W);let Y=I.result(),X=await oV(Y,$,Q),G=await Z.deriveFromKDM(X),K=await Q.encryptXSalsa20Poly1305Combined(Y,G),w=V.bod?await Q.encryptXSalsa20Poly1305Combined(V.bod,G):new Uint8Array(0),N=await Q.signEd25519(K,$.privateKey);return q({sig:N,kdm:X,headCph:K,bodyCph:w})}async function aV(V,$,Q,Z,J){let I=new f(V),[W,Y]=Y0.decode(I);if(Y!==0)return M(14);let X;try{X=$&&$.length>0?await Z.decryptXSalsa20Poly1305Combined($,Q):void 0}catch{return M(20)}let G=W.hsh&&X===void 0,K=W.hsh===void 0&&X!==void 0;if(G||K)return M(19);if(W.hsh&&X){let N=await Z.blake3(X);if(!s(N,W.hsh))return M(19)}let w=J??await Z.blake3(V);return q({msgHead:W,bod:X,headHash:w})}class R0{now(){return new Date}}function WQ(V,$,Q,Z){let J=$.getTime()-V.getTime(),I=Q.getTime()-Z.getTime();return(J+I)/2}var QV={encode(V,$){if(V.writeVarInt($.quota),$.quota>0){if($.usage===void 0)return 9;V.writeVarInt($.usage)}return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return M(Q);let Z;if($>0){let[J,I]=V.readVarInt();if(I!==0)return M(I);Z=J}return q({quota:$,usage:Z})}};var sV={encode(V,$){V.writeBytes(new Uint8Array([$.status]));let Q=V.writeDate($.timeRcvd);if(Q!==0)return Q;let Z=V.writeDate($.timeSent);if(Z!==0)return Z;let J=V.writeVarInt($.subscription.term);if(J!==0)return J;let I=V.writeVarInt($.subscription.elapsed);if(I!==0)return I;let W=V.writeStruct(QV,$.subscription.stat);if(W!==0)return W;let Y=V.writeStruct(QV,$.subscription.dyn);if(Y!==0)return Y;return 0},decode(V){let[$,Q]=V.readBytes(1);if(Q!==0)return M(Q);let Z=$[0],[J,I]=V.readDate();if(I!==0)return M(I);let[W,Y]=V.readDate();if(Y!==0)return M(Y);let[X,G]=V.readVarInt();if(G!==0)return M(G);let[K,w]=V.readVarInt();if(w!==0)return M(w);let[N,z]=V.readStruct(QV);if(z!==0)return M(z);let[F,R]=V.readStruct(QV);if(R!==0)return M(R);return q({status:Z,timeRcvd:J,timeSent:W,subscription:{term:X,elapsed:K,stat:N,dyn:F}})}};async function tV(V,$,Q){let{crypto:Z,enclave:J}=V,I=await J.derive($,Q);return await Z.deriveEd25519KeyPair(I)}var eV={encode(V,$){let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarInt($.seq);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return M(Q);let[Z,J]=V.readVarInt();if(J!==0)return M(J);return q({headCph:$,seq:Z})}};var Z0={encode(V,$){V.writeBytes($.pubKey),V.writeBytes($.sig);let Q=V.writeDate($.timestamp);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readBytes($Q);if(Q!==0)return M(Q);let[Z,J]=V.readBytes(T0);if(J!==0)return M(J);let[I,W]=V.readDate();if(W!==0)return M(W);return q({pubKey:$,sig:Z,timestamp:I})}};var YQ={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct(Z0,Q);if(I!==0)return I;for(let W of Z)J.writeVarInt(W);return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct(Z0);if(Y!==0)return Y;let X=await A0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W,[K,w]=await I.hasUser(G);if(w!==0)return w;if(!K)return 5;let[N,z]=$.readVarInt();if(z!==0)return z;if(!$.done())return 8;let[F,R]=await I.listHeads(G,N);if(R!==0)return R;return Q.writeStructs(eV,F)},decodeResp(V){return V.readStructs(eV)}};var V$={encode(V,$){V.writeVarInt($.seq);let Q=V.writeVarBytes($.bodyCph);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return M(Q);let[Z,J]=V.readVarBytes();if(J!==0)return M(J);return q({seq:$,bodyCph:Z})}};var XQ={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct(Z0,Q);if(I!==0)return I;for(let W of Z){let Y=J.writeVarInt(W);if(Y!==0)return Y}return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct(Z0);if(Y!==0)return Y;let X=await A0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W,[K,w]=await I.hasUser(G);if(w!==0)return w;if(!K)return 5;let N=[];while(!$.done()){let[R,U]=$.readVarInt();if(U!==0)return U;N.push(R)}console.info(`PULL: ${N.length} bags`);let[z,F]=await I.getBodies(G,N);if(F!==0)return F;if(!z)return 17;for(let{seq:R,bodyCph:U}of z){let H={seq:R,bodyCph:U},P=Q.writeStruct(V$,H);if(P!==0)return P}return 0},decodeResp(V){return V.readStructs(V$)}};var $$={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarBytes($.bodyCph);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readBytes(T0);if(Q!==0)return M(Q);let[Z,J]=V.readBytes(D0);if(J!==0)return M(J);let[I,W]=V.readVarBytes();if(W!==0)return M(W);let[Y,X]=V.readVarBytes();if(X!==0)return M(X);return q({sig:$,kdm:Z,headCph:I,bodyCph:Y})}};var qV={encode(V,$){let Q=V.writeVarInt($.seq);if(Q!==0)return Q;let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=$.bodyCph?$.bodyCph.length:0,I=V.writeVarInt(J);if(I!==0)return I;if(J>0){if(!$.bodyCph)return 10;V.writeBytes($.bodyCph)}return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return M(Q);let[Z,J]=V.readVarBytes();if(J!==0)return M(J);let[I,W]=V.readVarInt();if(W!==0)return M(W);let Y;if(I>0){let[X,G]=V.readBytes(I);if(G!==0)return M(G);Y=X}return q({seq:$,headCph:Z,bodyCph:Y})}};var HV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readBytes(T0);if(Q!==0)return M(Q);let[Z,J]=V.readBytes(D0);if(J!==0)return M(J);let[I,W]=V.readVarBytes();if(W!==0)return M(W);return q({sig:$,kdm:Z,headCph:I})}};var PV={encode(V,$){if(V.writeVarInt($.idx),V.writeBytes(new Uint8Array([$.status])),$.status===0)V.writeVarInt($.seq);return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return M(Q);let[Z,J]=V.readBytes(1);if(J!==0)return M(J);let I=Z[0];if(I!==0)return q({idx:$,status:I});let[W,Y]=V.readVarInt();if(Y!==0)return M(Y);return q({idx:$,status:I,seq:W})}};var GQ={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct(Z0,Q);if(I!==0)return I;let W=J.writeStructs($$,Z);if(W!==0)return W;return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I,notifier:W}=V,[Y,X]=$.readStruct(Z0);if(X!==0)return X;let G=await A0(Y,J,Z);if(G!==0)return G;let{pubKey:K}=Y,[w,N]=await I.hasUser(K);if(N!==0)return N;if(!w)return 5;let[z,F]=$.readStructs($$);if(F!==0)return F;console.info(`PUSH: ${z.length} bags`);let R=[],U=[];for(let O=0;O<z.length;O++){let A=z[O];if(!await JQ(A,K,J)){let x={idx:O,status:3},S=Q.writeStruct(PV,x);if(S!==0)return S;continue}R.push(O),U.push(A)}let[H,P]=await I.setBags(K,U);if(P!==0)return P;if(!H||H.length!==U.length)return 17;let D=[];for(let O=0;O<U.length;O++){let A=U[O],m=R[O],x=H[O],S=new k,E=S.writeStruct(HV,A);if(E!==0)return E;let B=S.result(),C={seq:x,headCph:B};if(z.length===1&&A.bodyCph.length<=ZQ)C.bodyCph=A.bodyCph;D.push(C);let g={idx:m,status:0,seq:x},v=Q.writeStruct(PV,g);if(v!==0)return v}if(D.length>0){let O=new k,A=O.writeStructs(qV,D);if(A!==0)return A;let m=O.result();await Promise.resolve(W.push(K,m))}return 0},decodeResp(V){return V.readStructs(PV)}};var KQ={async encodeReq(V,$,Q,Z,J){return J.writeStruct(Z0,Q)},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct(Z0);if(Y!==0)return Y;let X=await A0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W;if(!$.done())return 8;let[K,w]=await I.addUser(G);if(w!==0)return w;return 0},decodeResp(V){return q(void 0)}};class Q${url;websocket;constructor(V){this.url=V}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(V,$,Q=()=>{},Z=()=>{}){let{url:J}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let I=new k;I.writeStruct(Z0,V);let W=I.result(),Y=a(W);return J.searchParams.set("t",Y),this.websocket=new WebSocket(J),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),Z()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Q()},this.websocket.onmessage=(X)=>{let G=new Uint8Array(X.data);$(G)},this.websocket.onerror=(X)=>{console.log(`ERROR: ${JSON.stringify(X)}`),this.websocket=void 0,Q()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var c={user:{path:"/user",endpoint:KQ,name:0},push:{path:"/push",endpoint:GQ,name:2},peek:{path:"/peek",endpoint:YQ,name:1},pull:{path:"/pull",endpoint:XQ,name:3}},SZ={0:c.user,2:c.push,1:c.peek,3:c.pull},fY={[c.user.path]:c.user,[c.push.path]:c.push,[c.peek.path]:c.peek,[c.pull.path]:c.pull};class Z${url;listener;constructor(V){this.url=V;this.listener=new Q$(V)}async call(V,$){let{path:Q}=SZ[V],Z=new URL(Q,this.url);try{return await fZ(Z,$)}catch{return M(25)}}}var CV=(V)=>{return new Z$(V.handle)};async function fZ(V,$){let Q=await fetch(V,{method:"POST",body:$.result().slice()});if(!Q.ok)return M(24);let Z=await f.fromResponse(Q);return q(Z)}class TV{enclave;crypto;host;clock;transport;updateHostMeta;constructor(V,$,Q,Z,J,I){this.enclave=V;this.crypto=$;this.host=Q;this.clock=Z;this.transport=J;this.updateHostMeta=I}async call(V,$){let{clock:Q,crypto:Z,transport:J}=this,{endpoint:I,name:W}=V,Y=await this.keys(),X=Q.now(),[G,K]=await dV(Y,X,Z);if(K!==0)return M(K);let w=new k,N=await I.encodeReq(this,Y,G,$,w);if(N!==0)return M(N);let z=Q.now(),[F,R]=await J.call(W,w),U=Q.now();if(R!==0)return M(R);let[H,P]=F.readStruct(sV);if(P!==0)return M(P);if(H.status!==0)return M(H.status);let O={clockOffset:WQ(z,H.timeRcvd,H.timeSent,U),subscription:H.subscription},A=await this.updateHostMeta(O);if(A!==0)return M(A);return I.decodeResp(F)}keys=()=>{let{host:V}=this;return tV(this,V.label,V.idx)};seal=async(V)=>{let{crypto:$,enclave:Q}=this,Z=await this.keys();return IQ(V,Z,$,Q)};register=()=>this.call(c.user,[]);peek=(V)=>this.call(c.peek,[V]);push=(V)=>this.call(c.push,V);pull=(V)=>this.call(c.pull,V);listen=async(V,$,Q)=>{let{clock:Z,crypto:J,host:I,transport:W}=this,{listener:Y}=W,X=await tV(this,I.label,I.idx),G=Z.now(),[K,w]=await dV(X,G,J);if(w!==0)return w;return await Y.connect(K,V,$,Q)};isConnected(){let V=this.transport?.listener;if(V&&typeof V.connected==="function")return V.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var J$={encode(V,$){let Q=V.writeVarString($.lbl);if(Q!==0)return Q;let Z=V.writeVarInt($.idx);if(Z!==0)return Z;let J=V.writeVarInt($.num);if(J!==0)return J;return V.writeBytes($.hsh),V.writeBytes($.sig),0},decode(V){let[$,Q]=V.readVarString();if(Q!==0)return M(Q);let[Z,J]=V.readVarInt();if(J!==0)return M(J);let[I,W]=V.readVarInt();if(W!==0)return M(W);let[Y,X]=V.readBytes(OV);if(X!==0)return M(X);let[G,K]=V.readBytes(T0);if(K!==0)return M(K);return q({lbl:$,idx:Z,num:I,hsh:Y,sig:G})}};var I$={encode(V,$){let Q=V.writeStruct(J$,$.head);if(Q!==0)return Q;let Z=V.writeVarBytes($.indexEnc);if(Z!==0)return Z;let J=V.writeVarBytes($.bodyEnc);if(J!==0)return J;return 0},decode(V){let[$,Q]=V.readStruct(J$);if(Q!==0)return M(Q);let[Z,J]=V.readVarBytes();if(J!==0)return M(J);let[I,W]=V.readVarBytes();if(W!==0)return M(W);return q({head:$,indexEnc:Z,bodyEnc:I})}};var W$={encode(V,$){V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarInt($.lenBody);if(Z!==0)return Z;if($.lenBody>0&&$.offBody!==void 0){let J=V.writeVarInt($.offBody);if(J!==0)return J}return 0},decode(V){let[$,Q]=V.readBytes(D0);if(Q!==0)return M(Q);let[Z,J]=V.readVarBytes();if(J!==0)return M(J);let[I,W]=V.readVarInt();if(W!==0)return M(W);let Y;if(I>0){let[X,G]=V.readVarInt();if(G!==0)return M(G);Y=X}return q({kdm:$,headCph:Z,lenBody:I,offBody:Y})}};async function MQ(V,$,Q,Z,J){let I=await J.derive(V,$),W=await Z.deriveEd25519KeyPair(I),Y=new k,X=new k,G=0,K=0;for(let P of Q){let D=new k,O=D.writeStruct(Y0,P.head);if(O!==0)return M(O);let A=D.result(),m=await oV(A,W,Z),x=await J.deriveFromKDM(m),S=await Z.encryptXSalsa20Poly1305Combined(A,x),E=P.body?await Z.encryptXSalsa20Poly1305Combined(P.body,x):new Uint8Array(0),B=P.head.len>0&&P.head.hsh!==void 0?E.length:0,C={kdm:m,headCph:S,lenBody:B,offBody:B>0?K:void 0},g=Y.writeStruct(W$,C);if(g!==0)return M(g);if(P.body)X.writeBytes(E),K+=E.length;G++}let w=X.result(),N=Y.result(),z=await Z.blake3(N),F=await Z.signEd25519(z,W.privateKey),R={lbl:V,idx:$,num:G,hsh:z,sig:F},U=new k;U.writeStruct(I$,{head:R,indexEnc:N,bodyEnc:w});let H=U.result();return q(H)}async function wQ(V,$,Q){let[Z,J]=I$.decode(new f(V));if(J!==0)return M(J);let{head:I,indexEnc:W,bodyEnc:Y}=Z,X=await Q.derive(I.lbl,I.idx),G=await $.deriveEd25519KeyPair(X);if(!await $.checkSigEd25519(I.sig,I.hsh,G.publicKey))return M(3);let w=await $.blake3(W);if(!s(w,I.hsh))return M(19);let N=new f(W),z=[];for(let R=0;R<I.num;R++){let[U,H]=N.readStruct(W$);if(H!==0)return M(H);z.push(U)}if(z.length!==I.num)return M(14);let F=[];for(let R of z){let U=await Q.deriveFromKDM(R.kdm),H=await $.decryptXSalsa20Poly1305Combined(R.headCph,U),[P,D]=Y0.decode(new f(H));if(D!==0)return M(D);let O;if(R.lenBody>0&&R.offBody!==void 0){if(P.hsh===void 0)return M(14);let A=Y.slice(R.offBody,R.offBody+R.lenBody);O=await $.decryptXSalsa20Poly1305Combined(A,U);let m=await $.blake3(O);if(!s(m,P.hsh))return M(19)}F.push({head:P,body:O})}return q(F)}async function NQ({now:V,bod:$,crypto:Q}){let Z=await Q.genRandomBytes(8),J=new k,I=J.writeStruct(r,{id:Z,ts:V});if(I!==0)return M(I);let W=J.result();return DV({now:V,eid:W,ctr:0,bod:$,crypto:Q})}async function DV({now:V,eid:$,ctr:Q,bod:Z,crypto:J}){let I=new f($),[W,Y]=r.decode(I);if(Y!==0)return M(Y);let X=V.getTime()-W.ts.getTime(),G,K=Z?.length??0;if(Z&&K>0)G=await J.blake3(Z);return q({eid:$,off:X,ctr:Q,len:K,hsh:G})}var CX=Symbol("EntityID");function RQ(V){return"type"in V}var TX=Symbol("MasterSeed"),DX=Symbol("DerivationSeed"),AX=Symbol("PublicKey"),_X=Symbol("PrivateKey"),jX=Symbol("HostSpecificKeyPair"),LX=Symbol("Hash");function xZ(V){if(!V)return!1;if(typeof V!=="object")return!1;if("body"in V===!1)return!1;if("type"in V===!1)return!1;return!0}function kZ(V){if(!V.bod||V.bod.length===0){let Z={off:V.off,ctr:V.ctr,eid:V.eid};return q(Z)}let $=cV(V.bod);if(xZ($)===!1)return console.warn("msg body invalid",$),M(14);let Q={off:V.off,ctr:V.ctr,eid:V.eid,gid:$.gid,pid:$.pid,type:$.type,body:$.body};return q(Q)}class ZV{applier;emitter=new C0;clearer;onDirtyEids;cacheDriven;peerIngest;constructor(V,$,Q,Z){this.applier=V;this.clearer=$,this.onDirtyEids=Q,this.cacheDriven=Z?.cacheDriven??!1,this.peerIngest=Z?.peerIngest}apply=async(V)=>{let $=[],Q=[];for(let Y of V){let[X,G]=kZ(Y);if(Q.push(G),G!==0)continue;$.push(X)}let{stats:Z,types:J,eids:I}=await this.applier($),W=[];for(let Y=0;Y<V.length;Y++){let X=Q[Y],G=Z[Y];if(X!==0){W.push(X);continue}if(G!==0){W.push(G);continue}W.push(0)}if(!this.cacheDriven)for(let Y of J)this.emitter.emit(Y,null);if(I.length>0)this.onDirtyEids?.(I);return W};clear=async()=>{let V=await this.clearer();if(V!==0)return V;return this.emitter.emitAll(null),V};notify=(V)=>{for(let $ of V)this.emitter.emit($,null)};refresh=async(V)=>{if(this.peerIngest){await this.peerIngest(V);return}};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}var Y$={apply:async function(V){return V.map(()=>0)},clear:async function(){return 0},notify:function(V){},refresh:async function(V){},on:function(V,$){},off:function(V,$){}};var n="entities",AV="entity_type_created_at",X$="entity_type_updated_at",G$="entity_type_group_id",K$="entity_type_parent_id";function BZ(V){let $={bod:V.body,crd:V.createdAt,...V.ctr!==0?{ctr:V.ctr}:{},eid:L(V.eid),gid:V.gid,pid:V.pid?L(V.pid):void 0,typ:V.type,upd:V.updatedAt};if($.gid===void 0)delete $.gid;if($.pid===void 0)delete $.pid;if($.ctr===void 0)delete $.ctr;return $}function h0(V){return{body:V.bod,createdAt:V.crd,updatedAt:V.upd,ctr:V.ctr??0,type:V.typ,eid:X0(V.eid),gid:V.gid,pid:V.pid?X0(V.pid):void 0}}class M${db;async init(){this.db=await new Promise((V,$)=>{let Q=indexedDB.open("db",11);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!J)throw Error("Transaction is null during upgrade");if(!Z.objectStoreNames.contains(n))Z.createObjectStore(n,{keyPath:"eid",autoIncrement:!1});let I=J.objectStore(n);if(!I.indexNames.contains(AV))I.createIndex(AV,["typ","crd"],{unique:!1});if(!I.indexNames.contains(X$))I.createIndex(X$,["typ","upd"],{unique:!1});if(!I.indexNames.contains(G$))I.createIndex(G$,["typ","gid"],{unique:!1});if(!I.indexNames.contains(K$))I.createIndex(K$,["typ","pid"],{unique:!1})},Q.onsuccess=()=>V(Q.result),Q.onerror=()=>$(Q.error)})}apply=async(V)=>{let $=new Set,Q=[];if(!this.db)return{stats:V.map(()=>16),types:$,eids:Q};let Z=this.db.transaction(n,"readwrite"),J=Z.objectStore(n);return new Promise((I)=>{let W=Array(V.length).fill(0);if(V.length<1){I({stats:[],types:$,eids:Q});return}Z.oncomplete=()=>{I({stats:W,types:$,eids:Q})},Z.onerror=()=>{for(let X=0;X<W.length;X++)if(W[X]===void 0)W[X]=18;I({stats:W,types:$,eids:Q})};let Y=new Map;for(let X=0;X<V.length;X++){let G=V[X],K=L(G.eid),w={op:G,index:X},N=Y.get(K);if(N)N.push(w);else Y.set(K,[w])}for(let[X,G]of Y){if(G.length<1)continue;let K=J.get(X);K.onsuccess=()=>{let w=K.result,N=w?h0(w):void 0,z=!1;for(let{op:F,index:R}of G){let[U,H]=r0(N,F);if(H!==0){W[R]=H;continue}if(z=!0,U)$.add(U.type);else if(N)$.add(N.type);N=U}if(z)Q.push(G[0].op.eid);if(N){let F=BZ(N),R=J.put(F);R.onerror=(U)=>{U.preventDefault();for(let{index:H}of G)W[H]=18}}else{let F=J.delete(X);F.onerror=()=>{for(let{index:R}of G)W[R]=18}}},K.onerror=()=>{for(let{index:w}of G)W[w]=18}}})};async clear(){if(!this.db)return 16;let V=this.db.transaction(n,"readwrite"),$=V.objectStore(n);return new Promise((Q)=>{V.oncomplete=()=>Q(0),V.onerror=()=>Q(18),$.clear()})}async getEnt(V){if(!this.db)return M(16);let $=L(V),Z=this.db.transaction(n,"readonly").objectStore(n);return new Promise((J)=>{let I=Z.get($);I.onsuccess=()=>{let W=I.result;if(!W)J(q(void 0));else{let Y=h0(W);J(q(Y))}},I.onerror=()=>J(M(18))})}async getAllOfTypeUpdatedBetween(V,$,Q){if(!this.db)return M(16);let J=this.db.transaction(n,"readonly").objectStore(n).index(X$);return new Promise((I)=>{let W=J.getAll(IDBKeyRange.bound([V,$],[V,Q]));W.onsuccess=()=>{let Y=W.result;I(q(Y.map(h0)))},W.onerror=()=>I(M(18))})}async getGroupMembers(V,$){if(!this.db)return M(16);let Z=this.db.transaction(n,"readonly").objectStore(n).index(G$);return new Promise((J)=>{let I=Z.getAll(IDBKeyRange.only([V,$]));I.onsuccess=()=>{let W=I.result;J(q(W.map(h0)))},I.onerror=()=>J(M(18))})}async getAllOfType(V){if(!this.db)return M(16);let Q=this.db.transaction(n,"readonly").objectStore(n).index(AV);return new Promise((Z)=>{let J=Q.getAll(IDBKeyRange.bound([V],[V,[]]));J.onsuccess=()=>{let I=J.result;Z(q(I.map(h0)))},J.onerror=()=>Z(M(18))})}async getAllEntities(V){if(!this.db)return M(16);if("pid"in V){let $=L(V.pid),Z=this.db.transaction(n,"readonly").objectStore(n).index(K$);return new Promise((J)=>{let I=Z.getAll(IDBKeyRange.only([V.type,$]));I.onsuccess=()=>{let Y=I.result.map(h0);J(q(Y))},I.onerror=()=>J(M(18))})}else if("gid"in V)return await this.getGroupMembers(V.type,V.gid);else if("updatedBetween"in V)return await this.getAllOfTypeUpdatedBetween(V.type,V.updatedBetween.start,V.updatedBetween.end);return await this.getAllOfType(V.type)}async getEntities(V){let[$,Q]=await this.getAllEntities(V);if(Q!==0)return M(Q);return q($)}async countEntities({type:V}){if(!this.db)return M(16);let Q=this.db.transaction(n,"readonly").objectStore(n).index(AV);return new Promise((Z)=>{let J=IDBKeyRange.bound([V],[V,[]]),I=Q.count(J);I.onsuccess=()=>Z(q(I.result)),I.onerror=()=>Z(M(18))})}}async function zQ(){let V=new M$;return await V.init(),V}class _V{ents=new Map;constructor(V=[]){for(let $ of V){let Q=L($.eid);this.ents.set(Q,$)}}async apply(V){let $=new Set,Q=[],Z=[];for(let J of V){let I=L(J.eid),W=this.ents.get(I),[Y,X]=r0(W,J);if(X!==0){Z.push(X);continue}if(Y)$.add(Y.type);else if(W)$.add(W.type);if(Y)this.ents.set(I,Y);else this.ents.delete(I);Q.push(J.eid),Z.push(0)}return{stats:Z,types:$,eids:Q}}async clear(){return this.ents.clear(),0}async getEnt(V){let $=L(V),Q=this.ents.get($);return q(Q)}async getAllEntities({type:V,gid:$,pid:Q,updatedBetween:Z}){let J=[];if(Q!==void 0){for(let I of this.ents.values())if(I.type===V&&I.pid&&s(I.pid,Q))J.push(I)}else if($!==void 0){for(let I of this.ents.values())if(I.type===V&&(typeof I.gid==="string"&&I.gid===$))J.push(I)}else if(Z!==void 0){for(let I of this.ents.values())if(I.type===V&&I.updatedAt>=Z.start&&I.updatedAt<=Z.end)J.push(I)}else for(let I of this.ents.values())if(I.type===V)J.push(I);return q(J)}async getEntities(V){let[$,Q]=await this.getAllEntities(V);if(Q!==0)return M(Q);return q($)}async countEntities({type:V}){let $=0;for(let Q of this.ents.values())if(Q.type===V)$+=1;return q($)}}async function w$(V){let $=await zQ();if(V?.cache===!1)return $;return new JV($)}class JV{mem;durable;warmed=new Set;listeners=new Set;chain=Promise.resolve();constructor(V,$){if(this.durable=V,this.mem=new _V($??[]),$)for(let Q of $)this.warmed.add(Q.type)}subscribe(V){return this.listeners.add(V),()=>{this.listeners.delete(V)}}emit(V){if(V.size<1)return;for(let $ of this.listeners)$(V)}run(V){let $=this.chain.then(V,V);return this.chain=$.then(()=>{return},()=>{return}),$}apply(V){return this.run(async()=>{let $=nZ(this.mem.ents,V);this.emit($.types);let Q=await this.durable.apply(V),{changed:Z,status:J}=await this.pullEids(V.map((I)=>I.eid));this.emit(Z);for(let I of Q.types)this.warmed.add(I);if(J!==0)return{stats:V.map(()=>J),types:Q.types,eids:Q.eids};return Q})}clear(){return this.run(async()=>{let V=await this.durable.clear();if(V!==0)return V;let $=this.mem.ents.size>0;return await this.mem.clear(),this.warmed.clear(),0})}ingestFromDurable(V){return this.run(async()=>{let{changed:$,status:Q}=await this.pullEids(V);return this.emit($),Q})}async pullEids(V){let $=new Set,Q=new Set;for(let Z of V){let J=L(Z);if(Q.has(J))continue;Q.add(J);let I=this.mem.ents.get(J),[W,Y]=await this.durable.getEnt(Z);if(Y!==0)return{changed:$,status:Y};if(W){if(this.mem.ents.set(J,W),this.warmed.add(W.type),!I||!gZ(I,W)){if($.add(W.type),I&&I.type!==W.type)$.add(I.type)}}else if(I)this.mem.ents.delete(J),$.add(I.type)}return{changed:$,status:0}}async warmType(V){if(this.warmed.has(V))return 0;let[$,Q]=await this.durable.getEntities({type:V});if(Q!==0)return Q;if($)for(let Z of $){let J=L(Z.eid),I=this.mem.ents.get(J);if(!I||uZ(Z,I))this.mem.ents.set(J,Z)}return this.warmed.add(V),0}async getEnt(V){let $=L(V);if(this.mem.ents.has($))return this.mem.getEnt(V);return this.run(async()=>{if(this.mem.ents.has($))return this.mem.getEnt(V);let[Q,Z]=await this.durable.getEnt(V);if(Z!==0)return M(Z);if(Q)this.mem.ents.set($,Q),this.warmed.add(Q.type);return q(Q)})}async getEntities(V){let $=await this.run(()=>this.warmType(V.type));if($!==0)return M($);return this.mem.getEntities(V)}async countEntities({type:V}){let $=await this.run(()=>this.warmType(V));if($!==0)return M($);return this.mem.countEntities({type:V})}}function gZ(V,$){if(V.ctr!==$.ctr)return!1;if(V.updatedAt.getTime()!==$.updatedAt.getTime())return!1;if(V.createdAt.getTime()!==$.createdAt.getTime())return!1;if(V.type!==$.type)return!1;if(V.gid!==$.gid)return!1;if(!s(V.eid,$.eid))return!1;if(!iZ(V.pid,$.pid))return!1;return vZ(V.body,$.body)}function iZ(V,$){if(V===void 0&&$===void 0)return!0;if(V===void 0||$===void 0)return!1;return s(V,$)}function vZ(V,$){if(Object.is(V,$))return!0;if(V instanceof Uint8Array&&$ instanceof Uint8Array)return s(V,$);if(V instanceof Date&&$ instanceof Date)return V.getTime()===$.getTime();try{return s(m0(V),m0($))}catch{return!1}}function uZ(V,$){let Q=V.updatedAt.getTime(),Z=$.updatedAt.getTime();if(Q!==Z)return Q>Z;return V.ctr>$.ctr}function nZ(V,$){let Q=new Set,Z=[];for(let J of $){let I=L(J.eid),W=V.get(I),[Y,X]=r0(W,J);if(X!==0){Z.push(X);continue}if(Y)Q.add(Y.type);else if(W)Q.add(W.type);if(Y)V.set(I,Y);else V.delete(I);Z.push(0)}return{stats:Z,types:Q}}function jV(V){if(V instanceof JV){let $=new ZV((Q)=>V.apply(Q),()=>V.clear(),void 0,{cacheDriven:!0,peerIngest:async(Q)=>{await V.ingestFromDurable(Q)}});return V.subscribe((Q)=>$.notify(Q)),$}return new ZV(($)=>V.apply($),()=>V.clear())}function yZ(V){return{eid:V.eid,ctr:V.ctr,updatedAt:V.updatedAt}}function N$(V){let $=new f(V.eid),[Q,Z]=$.readStruct(r);if(Z!==0)return M(Z);return q({eid:V.eid,ctr:V.ctr,updatedAt:new Date(Q.ts.getTime()+V.off)})}function r0(V,$){let Q=new f($.eid),[Z,J]=Q.readStruct(r);if(J!==0)return M(J);let I=new Date(Z.ts.getTime()+$.off);if(V!==void 0&&I<=V.updatedAt)return M(15);if(RQ($))return q({eid:$.eid,gid:$.gid,pid:$.pid,type:$.type,createdAt:Z.ts,updatedAt:I,ctr:$.ctr,body:$.body});else return q(void 0)}var bZ={getEnt:async()=>M(21),getEntities:async(V)=>M(21),countEntities:async()=>M(21),apply:async(V)=>({stats:V.map(()=>21),types:new Set,eids:[]}),clear:async()=>21};class LV{inflight=null;again=!1;run(V){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain(V),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain(V){try{this.again=!1;let $=await V();while(this.again)this.again=!1,$=await V();return $}finally{this.inflight=null}}}var mV=100;class IV{timer=null;delayMs;work;tail=new LV;constructor(V,$){this.delayMs=V<0?0:V,this.work=$}schedule(){if(this.delayMs<=0){this.fire();return}if(this.timer!==null)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=null,this.fire()},this.delayMs)}async flush(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null,this.fire();await this.tail.flush()}cancel(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null}fire(){return this.tail.run(this.work)}}function FQ(V){let $=new f(V.eid),[Q,Z]=r.decode($);if(Z!==0)return;return Q.ts.getTime()+V.off}function pZ(V,$){let Q=FQ(V),Z=FQ($);if(Q===void 0&&Z===void 0)return 0;if(Q===void 0)return 1;if(Z===void 0)return-1;if(Z!==Q)return Z-Q;return $.ctr-V.ctr}function WV(V,$){return V.slice().sort((Q,Z)=>pZ($(Q),$(Z)))}var E0={phase:"idle"},YV=50;function R$(V,$,Q){if(V<=0||$<=0)return!1;if(V===1||V===$)return!0;return V%Q===0}function EV(V,$){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(V,$);return}let Q=URL.createObjectURL(V),Z=document.createElement("a");Z.href=Q,Z.download=$,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(Q)}function UQ(V,$,Q){let Z=[],J=[],I=0;for(let W of V){let Y=$(W);if(J.length>0&&I+Y>Q)Z.push(J),J=[],I=0;if(J.push(W),I+=Y,I>=Q)Z.push(J),J=[],I=0}if(J.length>0)Z.push(J);return Z}async function OQ(V,$,Q){let Z=V.length;if(Z<1)return[];let J=Array(Z),I=0,W=Math.min(Math.max(1,$),Z),Y=async()=>{while(!0){let G=I;if(I+=1,G>=Z)return;J[G]=await Q(V[G],G)}},X=[];for(let G=0;G<W;G++)X.push(Y());return await Promise.all(X),J}async function z$(V,$,Q,Z){let J=new f(V.headCph),[I,W]=J.readStruct(HV);if(W!==0)return M(W);let{sig:Y,kdm:X,headCph:G}=I;if(!await Z.checkSigEd25519(Y,G,$.publicKey))return M(3);let w=await Q.deriveFromKDM(X),N;try{N=await Z.decryptXSalsa20Poly1305Combined(G,w)}catch{return M(20)}return q({kdm:X,headEnc:N})}var z0="f",j0="t",K0="e";function lZ(V){return V===z0||V===j0||V===K0}function XV(V){if(V===!0||V===j0)return j0;if(V===K0)return K0;return z0}function hZ(V){return XV(V.apld)===z0}function F$(V){return V!==0&&V!==15&&V!==18&&V!==17}function S0(V,$,Q){if(V.apld=$,$===K0&&Q!==void 0)V.err=Q;else delete V.err}async function L0(V,$,Q){let Z=XV($.apld),J=$.body,I=J?.length??0,W;if(J&&I>0)W=await Q.blake3(J);let Y={eid:$.eid,off:$.off??0,ctr:$.ctr??0,len:I,hsh:W},X={hash:V,head:Y,apld:Z};if(J!==void 0)X.body=J;if(Z===K0&&$.err!==void 0)X.err=$.err;return X}var U$=1048576,O$=1048576,rZ=64;function cZ(V){return V.sig.length+V.kdm.length+V.headCph.length+V.bodyCph.length}async function dZ(V,$,Q,Z,J){if(Z.length<1)return 0;let[I,W]=await V.push(Z);if(W!==0)return W;if(!I)return 27;for(let X of I){if(X.status!==0){console.error("push err",X);continue}let G=J[X.idx];if(!G){console.error("no hash",X);continue}await $.uploads.deq(Q,[G])}let Y=await $.hosts.get(Q);if(Y){let X=Y.lastSeq,G=X,K=[];for(let w of I)if(w.status===0)K.push(w.seq);K.sort((w,N)=>w-N);for(let w of K)if(w===X+1)X=w;if(X>G)await $.hosts.touch(Q,X)}return 0}async function qQ(V,$){if($.length<1)return q([]);let Q=new Map,Z=[];for(let Y of $)Q.set(Y.seq,Y),Z.push(Y.seq);let[J,I]=await V.pull(Z);if(I!==0)return M(I);if(!J)return M(27);let W=[];for(let{seq:Y,bodyCph:X}of J){let G=Q.get(Y);if(!G)continue;W.push({dl:G,bodyCph:X})}return q(W)}async function oZ(V,$,Q,Z){if(Z.length<1)return q({parts:[],hashes:[]});let J=[],I=[],W=[],Y=new Map;for(let{dl:G,bodyCph:K}of Z){let{head:w,kdm:N,seq:z,host:F}=G,[R,U]=await HQ(G,Q);if(U!==0||!R){let E=Y.get(F)??[];E.push(z),Y.set(F,E);continue}let{headEnc:H,headEncHash:P}=R,D=await $.deriveFromKDM(N),[O,A]=await aV(H,K,D,Q,P);if(A!==0||!O){let E=Y.get(F)??[];E.push(z),Y.set(F,E);continue}let m={head:w,body:O.bod},x=O.headHash;W.push({key:x,data:AQ(m)}),J.push(m),I.push(x);let S=Y.get(F)??[];S.push(z),Y.set(F,S)}let X=await V.messages.add(W);for(let[G,K]of Y)await V.downloads.deq(G,K);for(let G=0;G<X.length;G++){let K=X[G];if(K!==0&&K!==15)console.error("ERR storing",_[K],"for message",G)}return q({parts:J,hashes:I})}async function HQ(V,$){let Q=V.headEnc;if(!Q){let J=new k,I=J.writeStruct(Y0,V.head);if(I!==0)return M(I);Q=J.result()}if(V.headEncHash)return q({headEnc:Q,headEncHash:V.headEncHash});let Z=await $.blake3(Q);return q({headEnc:Q,headEncHash:Z})}async function PQ(V,$,Q){let Z=new Set;for(let W of $)Z.add(L(W));if(Z.size<1)return;let J=Array.from(await V.downloads.list());if(J.length<1)return;let I=new Map;for(let W of J){let Y;if(W.headEncHash)Y=L(W.headEncHash);else{let[G,K]=await HQ(W,Q);if(K!==0||!G)continue;Y=L(G.headEncHash)}if(!Z.has(Y))continue;let X=I.get(W.host)??[];X.push(W.seq),I.set(W.host,X)}for(let[W,Y]of I)await V.downloads.deq(W,Y)}async function CQ({conn:V,store:$,enclave:Q,host:Z,crypto:J,onProgress:I,peekProgressEvery:W,peekConcurrency:Y}){let X=await V.keys(),G=[],[K,w]=await V.peek(Z.lastSeq);if(w!==0)return w;let N=K.length,z=W??YV,F=Y??rZ;if(I&&N>0)I({phase:"peek",host:Z.label,done:0,total:N});let R=0,U=await OQ(K,F,async(H)=>{let[P,D]=await z$(H,X,Q,J),O;if(D!==0||!P)O={ok:!1,seq:H.seq,stat:D};else{let A=await J.blake3(P.headEnc);O={ok:!0,seq:H.seq,kdm:P.kdm,headEnc:P.headEnc,headEncHash:A}}if(R+=1,I&&R$(R,N,z))I({phase:"peek",host:Z.label,done:R,total:N});return O});for(let H of U){if(!H.ok){console.error("peek: decrypting item head",H.stat);continue}if(await $.messages.has(H.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await $.uploads.deq(Z.label,[H.headEncHash]),await $.downloads.deq(Z.label,[H.seq]);continue}let D=new f(H.headEnc),[O,A]=D.readStruct(Y0);if(A!==0){console.error("peek: reading item head",A);continue}G.push({kdm:H.kdm,head:O,seq:H.seq,host:Z.label,headEnc:H.headEnc,headEncHash:H.headEncHash})}if(await $.downloads.enq(G),K.length>0){let H=Math.max(...K.map((P)=>P.seq));await $.hosts.touch(Z.label,H)}if(I)I({phase:"peek",host:Z.label,done:N,total:N});return 0}async function TQ({conn:V,store:$,host:Q,maxPushBytes:Z,onProgress:J}){let I=Z??U$,W=await $.uploads.list(Q.label),Y=W.length,X=0;if(J&&Y>0)J({phase:"push",host:Q.label,done:0,total:Y});let G=[],K=[],w=0,N=async()=>{if(G.length<1)return 0;let z=G.length,F=await dZ(V,$,Q.label,G,K);if(G=[],K=[],w=0,F===0){if(X+=z,J)J({phase:"push",host:Q.label,done:X,total:Y})}return F};for(let z of W){let F=await $.messages.get(z);if(!F){X+=1;continue}let R={...F.head,bod:F.body},[U,H]=await V.seal(R);if(H!==0)return H;if(!U)return 12;let P=cZ(U);if(G.length>0&&w+P>I){let D=await N();if(D!==0)return D}if(G.push(U),K.push(z),w+=P,w>=I){let D=await N();if(D!==0)return D}}return N()}async function DQ({conn:V,store:$,enclave:Q,host:Z,crypto:J,maxPullBytes:I,onProgress:W},Y){let X=I??O$,G=await $.downloads.list(),K=Array.from(G).filter((U)=>U.host===Z.label);if(K.length<1)return 15;let w=WV(K,(U)=>U.head),N=UQ(w,(U)=>U.head.len,X),z=w.length,F=0;if(W)W({phase:"pull",host:Z.label,done:0,total:z});let R=qQ(V,N[0]);for(let U=0;U<N.length;U++){let[H,P]=await R;if(P!==0||!H)return P;if(F+=N[U].length,W)W({phase:"pull",host:Z.label,done:F,total:z});let D=N[U+1];if(D)R=qQ(V,D);if(W)W({phase:"open",host:Z.label,done:F,total:z});let O=WV(H,(m)=>m.dl.head),[,A]=await oZ($,Q,J,O);if(A!==0)return A;if(Y){if(W)W({phase:"exec",host:Z.label,done:F,total:z});await Y()}}return 0}function AQ({head:V,body:$}){let Q={eid:V.eid,body:$,apld:z0};if(V.off!==0)Q.off=V.off;if(V.ctr!==0)Q.ctr=V.ctr;return Q}async function _Q(V,{conn:$,store:Q,enclave:Z,host:J,crypto:I,onProgress:W},Y){let X=J.label,G=await $.keys(),K=new f(V),[w,N]=K.readStructs(qV);if(N!==0){console.error("Failed decoding notif",_[N]);return}let z=!1,R=(await Q.hosts.get(X))?.lastSeq,U=[],H=!1;for(let O of w){let[A,m]=await z$({seq:O.seq,headCph:O.headCph},G,Z,I);if(m!==0){console.error("Failed decrypting notif",_[m]);continue}let x=await I.blake3(A.headEnc);if(await Q.messages.has(x))continue;let S=new f(A.headEnc),[E,B]=S.readStruct(Y0);if(B!==0){console.error("Failed to parse head",_[B]);continue}if(!O.bodyCph&&E.len>0)H=!0,await Q.downloads.enq([{seq:O.seq,host:X,kdm:A.kdm,head:E,headEnc:A.headEnc,headEncHash:x}]);else U.push({...A,head:E,bodyCph:O.bodyCph,headEncHash:x});if(R===void 0||O.seq!==R+1)console.log("out of seq",O.seq,R),z=!0;else R=O.seq}if(R!==void 0)await Q.hosts.touch(J.label,R);let P=[];for(let O of U){let A=await Z.deriveFromKDM(O.kdm),[m,x]=await aV(O.headEnc,O.bodyCph,A,I);if(x!==0){console.error("Failed to open body",_[x]);continue}P.push({key:O.headEncHash,data:AQ({head:O.head,body:m.bod})})}let D=await Q.messages.add(P);for(let O=0;O<D.length;O++){let A=D[O];if(A!==0&&A!==15)console.error("ERR storing",_[A],"for message",O)}if(W&&P.length>0)W({phase:"open",host:J.label,done:P.length,total:P.length});if(z||H||P.length>0)Y()}class f0{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new LV;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=YV;lastProgress=E0;scheduledSync;constructor(V,$,Q,Z,J,I=!0,W=U$,Y=O$,X){this.clock=V;this.state=$;this.store=Q;this.transport=Z;this.crypto=J;this.forceSkewHandlingByDefault=I;this.onScheduleSync=X;this.maxPushBytes=W,this.maxPullBytes=Y,this.clientState=new G0(()=>this.getClientState()),this.xferState=new G0(()=>this.getXferState()),this.scheduledSync=new IV(mV,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(G){console.error("Debounced sync failed:",G)}})}emitProgress=(V)=>{this.lastProgress=V,this.xferState.emit()};async setSeed(V){await this.store.seed.save(V),this.clientState.emit()}async getClientState(){let{store:V,connections:$}=this,Q=await V.seed.load(),Z=await V.hosts.list(),J=!1;for(let I of $.values())if(I.isConnected()){J=!0;break}return{hasSeed:Q!==void 0,hasHost:Array.from(Z).length>0,connected:J}}async getXferState(){let{uploads:V,downloads:$}=this.store,Q=await V.count();return{numDownloads:await $.count(),numUploads:Q,progress:this.lastProgress}}apply=(V,$)=>{return this.enqueueApplyJob(()=>this.doApply(V,$))};async doApply(V,$={enqueueUpload:!0,triggerUpload:!0}){let Q=[],Z=[];for(let{head:I,body:W}of V){let Y=new k;Y.writeStruct(Y0,I);let X=Y.result(),G=await this.crypto.blake3(X),K={eid:I.eid,body:W,apld:z0};if(I.off!==0)K.off=I.off;if(I.ctr!==0)K.ctr=I.ctr;Q.push(G),Z.push({key:G,data:K})}await this.store.messages.add(Z),await PQ(this.store,Q,this.crypto);let J=await this.doApplyHashes(Q);if($.enqueueUpload){let I=[];for(let W=0;W<Q.length;W++){let Y=J[W];if(Y===0||Y===15)I.push(Q[W])}if(I.length>0){let W=await this.store.hosts.list();for(let Y of W)await this.store.uploads.enq(Y.label,I);this.xferState.emit()}}if($.triggerUpload)this.scheduleSync();return J}enqueueApplyJob(V){let $=this.applyChain.then(V,V);return this.applyChain=$.then(()=>{return},()=>{return}),$}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let V=await this.store.messages.list(z0);if(V.length<1)return[];let $=WV(V,(Q)=>Q.head);return this.applyStored($)}applyHashes=(V)=>{return this.enqueueApplyJob(()=>this.doApplyHashes(V))};async doApplyHashes(V){let $=[];for(let J of V){let I=await this.store.messages.get(J);if(I)$.push(I)}let Q=await this.applyStored($),Z=new Map;for(let J=0;J<$.length;J++)Z.set(L($[J].hash),Q[J]??12);return V.map((J)=>Z.get(L(J))??13)}async applyStored(V){if(V.length<1)return[];let $=V.map((I)=>({...I.head,bod:I.body})),Q=await this.state.apply($),Z=[],J=[];for(let I=0;I<V.length;I++){let W=Q[I];if(W===0||W===15)Z.push(V[I].hash);else if(W!==void 0&&F$(W))J.push({key:V[I].hash,err:W})}if(Z.length>0)await this.store.messages.markApplied(Z);if(J.length>0)await this.store.messages.markFailed(J);return Q}async insertRaw(V){let{clock:$,crypto:Q}=this,[Z,J]=await NQ({now:$.now(),bod:V,crypto:Q});if(J!==0)return M(J);let W=(await this.apply([{head:Z,body:V}]))[0];if(W!==0&&W!==15)return M(W??12);return q(Z)}async makeUpdate(V,$){let{clock:Q,crypto:Z}=this,J=Q.now();if(V.updatedAt.getTime()>J.getTime())return M(4);let I=V.ctr+1,[W,Y]=await DV({now:J,eid:V.eid,ctr:I,bod:$,crypto:Z});if(Y!==0)return M(Y);return q({head:W,body:$})}async updateWithSkew(V,$,Q){if(Q===!1)return M(4);let{clock:Z,crypto:J}=this,I=Z.now(),W=new f(V.eid),[Y,X]=W.readStruct(r);if(X!==0)return M(X);let G=V.updatedAt.getTime()-Y.ts.getTime(),K={eid:V.eid,off:G+1,ctr:V.ctr+1,len:0},N=(await this.apply([{head:K,body:void 0}]))[0];if(N!==0&&N!==15)return M(N??12);if($===void 0)return q(K);let[z,F]=l0({id:Y.id,ts:I});if(F!==0)return M(F);let[R,U]=await DV({now:I,eid:z,ctr:0,bod:$,crypto:J});if(U!==0)return M(U);let P=(await this.apply([{head:R,body:$}]))[0];if(P!==0&&P!==15)return M(P??12);return q(R)}async updateRaw(V,$,Q=this.forceSkewHandlingByDefault){if(V.updatedAt.getTime()>this.clock.now().getTime())return this.updateWithSkew(V,$,Q);return this.enqueueApplyJob(async()=>{let[Z,J]=await this.makeUpdate(V,$);if(J!==0)return M(J);let W=(await this.doApply([Z]))[0];if(W!==0&&W!==15)return M(W??12);return q(Z.head)})}async insert(V){let{body:$,type:Q,gid:Z,pid:J}=V,W=m0({body:$,type:Q,gid:Z,pid:J});return this.insertRaw(W)}async update(V){let{prior:$,body:Q,type:Z,gid:J,pid:I,force:W}=V,X=m0({body:Q,type:Z,gid:J,pid:I});return this.updateRaw($,X,W??this.forceSkewHandlingByDefault)}async delete(V){let $=V.force??!0;if("prior"in V)return this.updateRaw(V.prior,void 0,$);let[Q,Z]=await this.revFromArchive(V.eid);if(Z!==0)return M(Z);return this.updateRaw(Q,void 0,$)}async revFromArchive(V){let $=await this.store.messages.last(V);if($)return N$($.head);let Q=new f(V),[Z,J]=Q.readStruct(r);if(J!==0)return M(J);return q({eid:V,ctr:-1,updatedAt:Z.ts})}async genEID(V){let{clock:$,crypto:Q}=this,Z=$.now();if(V!==void 0)return l0({id:V,ts:Z});let J=await Q.genRandomBytes(8);return l0({id:J,ts:Z})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:V,crypto:$,store:Q}=this,Z=await Q.seed.load();if(!Z)return 22;await this.drainApplyQueue();for(let[J,I]of V){let W=await Q.hosts.get(J);if(!W)continue;let Y={conn:I,store:Q,enclave:Z,host:W,crypto:$,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},X=await CQ(Y);if(X!==0)return console.error(`Failed to peek: ${X}`),X;this.xferState.emit();let G=await TQ(Y);if(G!==0)return console.error(`Failed to push: ${G}`),G;this.xferState.emit();let K=await DQ(Y,async()=>{await this.drainApplyQueue()});if(K!==0&&K!==15)return console.error(`Failed to pull: ${K}`),K;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async wipe(){this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush(),await this.store.wipe(),await this.state.clear(),this.lastProgress=E0,this.clientState.emit(),this.xferState.emit()}import=async(V,$)=>{let{crypto:Q,store:Z}=this,J=$?.onProgress,I=await Z.seed.load();if(!I)return 22;console.time("import: decoding file...");let W=await V.bytes(),[Y,X]=await wQ(W,Q,I);if(X!==0)return X;console.timeEnd("import: decoding file...");let G=0;while(G<Y.length){let K=0,w=0,N=G;for(let R=G;R<Y.length&&w<100&&K<102400;R++)K+=Y[R].head.len,w++,N=R+1;let z=Y.slice(G,N);console.time(`import: applying [${G}, ${N}]`);let F=await this.apply(z,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${G}, ${N}]`);for(let R=0;R<z.length;R++){let U=F[R];if(U!==0&&U!==15)console.warn(`failed to import msg ${G+R}: ${_[U]}`)}if(J)queueMicrotask(()=>J(N,Y.length,0));this.emitProgress({phase:"import",done:N,total:Y.length}),G=N}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:V,store:$}=this,Q=await $.seed.load();if(!Q)return M(22);let Z=await $.messages.list();return MQ("export",0,Z,V,Q)}async export(V){let[$,Q]=await this.exportBytes();if(Q!==0)return Q;if(!$)return 12;let Z=new Blob([$.slice()]);return EV(Z,V),0}async link(V,$=!0){if(await this.store.hosts.add(V),this.clientState.emit(),$){let Q=await this.store.hosts.get(V.label);if(Q)await this.connectToHost(Q)}}async unlink(V){await this.store.hosts.del(V),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async(V,$=!0,Q=!0)=>{let{clock:Z,connections:J,crypto:I,store:W,transport:Y}=this,X=J.get(V.label);if(X){if(X.isConnected())return;try{X.closeListener()}catch{}J.delete(V.label)}let G=await W.seed.load();if(!G)return;console.info(`Connecting to ${V.handle} (${V.label})`);let K=new TV(G,I,V,Z,Y(V),(w)=>W.hosts.set(V.label,w));if(await K.register(),$)await K.listen(async(w)=>{let N={conn:K,store:W,enclave:G,host:V,crypto:I,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return _Q(w,N,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(J.set(V.label,K),this.clientState.emit(),Q)this.scheduleSync()};async connect(V=!0,$=!0){let{connectToHost:Q,scheduleSync:Z,store:J}=this;if(!await J.seed.load())return;await this.drainApplyQueue();let W=await J.hosts.list();for(let Y of W)await Q(Y,V,!1);if($)Z()}disconnect=async()=>{for(let V of this.connections.values())try{V.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var x0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function SV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function q$(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function h(V,...$){if(!q$(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function H$(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function jQ(V,$){h(V);let Q=$.outputLen;if(V.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function P$(V){if(typeof V!=="boolean")throw Error(`boolean expected, not ${V}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var F0=(V)=>new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4));var aZ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!aZ)throw Error("Non little-endian hardware is not supported");function sZ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function fV(V){if(typeof V==="string")V=sZ(V);else if(q$(V))V=xV(V);else throw Error("Uint8Array expected, got "+typeof V);return V}function LQ(V,$){if($==null||typeof $!=="object")throw Error("options must be defined");return Object.assign(V,$)}function mQ(V,$){if(V.length!==$.length)return!1;let Q=0;for(let Z=0;Z<V.length;Z++)Q|=V[Z]^$[Z];return Q===0}var EQ=(V,$)=>{function Q(Z,...J){if(h(Z),V.nonceLength!==void 0){let K=J[0];if(!K)throw Error("nonce / iv required");if(V.varSizeNonce)h(K);else h(K,V.nonceLength)}let I=V.tagLength;if(I&&J[1]!==void 0)h(J[1]);let W=$(Z,...J),Y=(K,w)=>{if(w!==void 0){if(K!==2)throw Error("cipher output not supported");h(w)}},X=!1;return{encrypt(K,w){if(X)throw Error("cannot encrypt() twice with same key + nonce");return X=!0,h(K),Y(W.encrypt.length,w),W.encrypt(K,w)},decrypt(K,w){if(h(K),I&&K.length<I)throw Error("invalid ciphertext length: smaller than tagLength="+I);return Y(W.decrypt.length,w),W.decrypt(K,w)}}}return Object.assign(Q,V),Q};function C$(V,$,Q=!0){if($===void 0)return new Uint8Array(V);if($.length!==V)throw Error("invalid output length, expected "+V+", got: "+$.length);if(Q&&!tZ($))throw Error("invalid output, must be aligned");return $}function tZ(V){return V.byteOffset%4===0}function xV(V){return Uint8Array.from(V)}function M0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function kV(V=32){if(x0&&typeof x0.getRandomValues==="function")return x0.getRandomValues(new Uint8Array(V));if(x0&&typeof x0.randomBytes==="function")return x0.randomBytes(V);throw Error("crypto.getRandomValues must be defined")}var fQ=(V)=>Uint8Array.from(V.split("").map(($)=>$.charCodeAt(0))),eZ=fQ("expand 16-byte k"),VJ=fQ("expand 32-byte k"),$J=F0(eZ),QJ=F0(VJ);function T(V,$){return V<<$|V>>>32-$}function T$(V){return V.byteOffset%4===0}var BV=64,ZJ=16,xQ=4294967295,SQ=new Uint32Array;function JJ(V,$,Q,Z,J,I,W,Y){let X=J.length,G=new Uint8Array(BV),K=F0(G),w=T$(J)&&T$(I),N=w?F0(J):SQ,z=w?F0(I):SQ;for(let F=0;F<X;W++){if(V($,Q,Z,K,W,Y),W>=xQ)throw Error("arx: counter overflow");let R=Math.min(BV,X-F);if(w&&R===BV){let U=F/4;if(F%4!==0)throw Error("arx: invalid block position");for(let H=0,P;H<ZJ;H++)P=U+H,z[P]=N[P]^K[H];F+=BV;continue}for(let U=0,H;U<R;U++)H=F+U,I[H]=J[H]^G[U];F+=R}}function kQ(V,$){let{allowShortKeys:Q,extendNonceFn:Z,counterLength:J,counterRight:I,rounds:W}=LQ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},$);if(typeof V!=="function")throw Error("core must be a function");return SV(J),SV(W),P$(I),P$(Q),(Y,X,G,K,w=0)=>{h(Y),h(X),h(G);let N=G.length;if(K===void 0)K=new Uint8Array(N);if(h(K),SV(w),w<0||w>=xQ)throw Error("arx: counter overflow");if(K.length<N)throw Error(`arx: output (${K.length}) is shorter than data (${N})`);let z=[],F=Y.length,R,U;if(F===32)z.push(R=xV(Y)),U=QJ;else if(F===16&&Q)R=new Uint8Array(32),R.set(Y),R.set(Y,16),U=$J,z.push(R);else throw Error(`arx: invalid 32-byte key, got length=${F}`);if(!T$(X))z.push(X=xV(X));let H=F0(R);if(Z){if(X.length!==24)throw Error("arx: extended nonce must be 24 bytes");Z(U,H,F0(X.subarray(0,16)),H),X=X.subarray(16)}let P=16-J;if(P!==X.length)throw Error(`arx: nonce must be ${P} or 16 bytes`);if(P!==12){let O=new Uint8Array(12);O.set(X,I?0:12-X.length),X=O,z.push(X)}let D=F0(X);return JJ(V,U,H,D,G,K,w,W),M0(...z),K}}var d=(V,$)=>V[$++]&255|(V[$++]&255)<<8;class BQ{constructor(V){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,V=fV(V),h(V,32);let $=d(V,0),Q=d(V,2),Z=d(V,4),J=d(V,6),I=d(V,8),W=d(V,10),Y=d(V,12),X=d(V,14);this.r[0]=$&8191,this.r[1]=($>>>13|Q<<3)&8191,this.r[2]=(Q>>>10|Z<<6)&7939,this.r[3]=(Z>>>7|J<<9)&8191,this.r[4]=(J>>>4|I<<12)&255,this.r[5]=I>>>1&8190,this.r[6]=(I>>>14|W<<2)&8191,this.r[7]=(W>>>11|Y<<5)&8065,this.r[8]=(Y>>>8|X<<8)&8191,this.r[9]=X>>>5&127;for(let G=0;G<8;G++)this.pad[G]=d(V,16+2*G)}process(V,$,Q=!1){let Z=Q?0:2048,{h:J,r:I}=this,W=I[0],Y=I[1],X=I[2],G=I[3],K=I[4],w=I[5],N=I[6],z=I[7],F=I[8],R=I[9],U=d(V,$+0),H=d(V,$+2),P=d(V,$+4),D=d(V,$+6),O=d(V,$+8),A=d(V,$+10),m=d(V,$+12),x=d(V,$+14),S=J[0]+(U&8191),E=J[1]+((U>>>13|H<<3)&8191),B=J[2]+((H>>>10|P<<6)&8191),C=J[3]+((P>>>7|D<<9)&8191),g=J[4]+((D>>>4|O<<12)&8191),v=J[5]+(O>>>1&8191),y=J[6]+((O>>>14|A<<2)&8191),b=J[7]+((A>>>11|m<<5)&8191),p=J[8]+((m>>>8|x<<8)&8191),l=J[9]+(x>>>5|Z),j=0,o=j+S*W+E*(5*R)+B*(5*F)+C*(5*z)+g*(5*N);j=o>>>13,o&=8191,o+=v*(5*w)+y*(5*K)+b*(5*G)+p*(5*X)+l*(5*Y),j+=o>>>13,o&=8191;let t=j+S*Y+E*W+B*(5*R)+C*(5*F)+g*(5*z);j=t>>>13,t&=8191,t+=v*(5*N)+y*(5*w)+b*(5*K)+p*(5*G)+l*(5*X),j+=t>>>13,t&=8191;let Q0=j+S*X+E*Y+B*W+C*(5*R)+g*(5*F);j=Q0>>>13,Q0&=8191,Q0+=v*(5*z)+y*(5*N)+b*(5*w)+p*(5*K)+l*(5*G),j+=Q0>>>13,Q0&=8191;let i=j+S*G+E*X+B*Y+C*W+g*(5*R);j=i>>>13,i&=8191,i+=v*(5*F)+y*(5*z)+b*(5*N)+p*(5*w)+l*(5*K),j+=i>>>13,i&=8191;let N0=j+S*K+E*G+B*X+C*Y+g*W;j=N0>>>13,N0&=8191,N0+=v*(5*R)+y*(5*F)+b*(5*z)+p*(5*N)+l*(5*w),j+=N0>>>13,N0&=8191;let g0=j+S*w+E*K+B*G+C*X+g*Y;j=g0>>>13,g0&=8191,g0+=v*W+y*(5*R)+b*(5*F)+p*(5*z)+l*(5*N),j+=g0>>>13,g0&=8191;let i0=j+S*N+E*w+B*K+C*G+g*X;j=i0>>>13,i0&=8191,i0+=v*Y+y*W+b*(5*R)+p*(5*F)+l*(5*z),j+=i0>>>13,i0&=8191;let v0=j+S*z+E*N+B*w+C*K+g*G;j=v0>>>13,v0&=8191,v0+=v*X+y*Y+b*W+p*(5*R)+l*(5*F),j+=v0>>>13,v0&=8191;let u0=j+S*F+E*z+B*N+C*w+g*K;j=u0>>>13,u0&=8191,u0+=v*G+y*X+b*Y+p*W+l*(5*R),j+=u0>>>13,u0&=8191;let n0=j+S*R+E*F+B*z+C*N+g*w;j=n0>>>13,n0&=8191,n0+=v*K+y*G+b*X+p*Y+l*W,j+=n0>>>13,n0&=8191,j=(j<<2)+j|0,j=j+o|0,o=j&8191,j=j>>>13,t+=j,J[0]=o,J[1]=t,J[2]=Q0,J[3]=i,J[4]=N0,J[5]=g0,J[6]=i0,J[7]=v0,J[8]=u0,J[9]=n0}finalize(){let{h:V,pad:$}=this,Q=new Uint16Array(10),Z=V[1]>>>13;V[1]&=8191;for(let W=2;W<10;W++)V[W]+=Z,Z=V[W]>>>13,V[W]&=8191;V[0]+=Z*5,Z=V[0]>>>13,V[0]&=8191,V[1]+=Z,Z=V[1]>>>13,V[1]&=8191,V[2]+=Z,Q[0]=V[0]+5,Z=Q[0]>>>13,Q[0]&=8191;for(let W=1;W<10;W++)Q[W]=V[W]+Z,Z=Q[W]>>>13,Q[W]&=8191;Q[9]-=8192;let J=(Z^1)-1;for(let W=0;W<10;W++)Q[W]&=J;J=~J;for(let W=0;W<10;W++)V[W]=V[W]&J|Q[W];V[0]=(V[0]|V[1]<<13)&65535,V[1]=(V[1]>>>3|V[2]<<10)&65535,V[2]=(V[2]>>>6|V[3]<<7)&65535,V[3]=(V[3]>>>9|V[4]<<4)&65535,V[4]=(V[4]>>>12|V[5]<<1|V[6]<<14)&65535,V[5]=(V[6]>>>2|V[7]<<11)&65535,V[6]=(V[7]>>>5|V[8]<<8)&65535,V[7]=(V[8]>>>8|V[9]<<5)&65535;let I=V[0]+$[0];V[0]=I&65535;for(let W=1;W<8;W++)I=(V[W]+$[W]|0)+(I>>>16)|0,V[W]=I&65535;M0(Q)}update(V){H$(this);let{buffer:$,blockLen:Q}=this;V=fV(V);let Z=V.length;for(let J=0;J<Z;){let I=Math.min(Q-this.pos,Z-J);if(I===Q){for(;Q<=Z-J;J+=Q)this.process(V,J);continue}if($.set(V.subarray(J,J+I),this.pos),this.pos+=I,J+=I,this.pos===Q)this.process($,0,!1),this.pos=0}return this}destroy(){M0(this.h,this.r,this.buffer,this.pad)}digestInto(V){H$(this),jQ(V,this),this.finished=!0;let{buffer:$,h:Q}=this,{pos:Z}=this;if(Z){$[Z++]=1;for(;Z<16;Z++)$[Z]=0;this.process($,0,!0)}this.finalize();let J=0;for(let I=0;I<8;I++)V[J++]=Q[I]>>>0,V[J++]=Q[I]>>>8;return V}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Q=V.slice(0,$);return this.destroy(),Q}}function IJ(V){let $=(Z,J)=>V(J).update(fV(Z)).digest(),Q=V(new Uint8Array(32));return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=(Z)=>V(Z),$}var D$=IJ((V)=>new BQ(V));function WJ(V,$,Q,Z,J,I=20){let W=V[0],Y=$[0],X=$[1],G=$[2],K=$[3],w=V[1],N=Q[0],z=Q[1],F=J,R=0,U=V[2],H=$[4],P=$[5],D=$[6],O=$[7],A=V[3],m=W,x=Y,S=X,E=G,B=K,C=w,g=N,v=z,y=F,b=R,p=U,l=H,j=P,o=D,t=O,Q0=A;for(let N0=0;N0<I;N0+=2)B^=T(m+j|0,7),y^=T(B+m|0,9),j^=T(y+B|0,13),m^=T(j+y|0,18),b^=T(C+x|0,7),o^=T(b+C|0,9),x^=T(o+b|0,13),C^=T(x+o|0,18),t^=T(p+g|0,7),S^=T(t+p|0,9),g^=T(S+t|0,13),p^=T(g+S|0,18),E^=T(Q0+l|0,7),v^=T(E+Q0|0,9),l^=T(v+E|0,13),Q0^=T(l+v|0,18),x^=T(m+E|0,7),S^=T(x+m|0,9),E^=T(S+x|0,13),m^=T(E+S|0,18),g^=T(C+B|0,7),v^=T(g+C|0,9),B^=T(v+g|0,13),C^=T(B+v|0,18),l^=T(p+b|0,7),y^=T(l+p|0,9),b^=T(y+l|0,13),p^=T(b+y|0,18),j^=T(Q0+t|0,7),o^=T(j+Q0|0,9),t^=T(o+j|0,13),Q0^=T(t+o|0,18);let i=0;Z[i++]=W+m|0,Z[i++]=Y+x|0,Z[i++]=X+S|0,Z[i++]=G+E|0,Z[i++]=K+B|0,Z[i++]=w+C|0,Z[i++]=N+g|0,Z[i++]=z+v|0,Z[i++]=F+y|0,Z[i++]=R+b|0,Z[i++]=U+p|0,Z[i++]=H+l|0,Z[i++]=P+j|0,Z[i++]=D+o|0,Z[i++]=O+t|0,Z[i++]=A+Q0|0}function YJ(V,$,Q,Z){let J=V[0],I=$[0],W=$[1],Y=$[2],X=$[3],G=V[1],K=Q[0],w=Q[1],N=Q[2],z=Q[3],F=V[2],R=$[4],U=$[5],H=$[6],P=$[7],D=V[3];for(let A=0;A<20;A+=2)X^=T(J+U|0,7),N^=T(X+J|0,9),U^=T(N+X|0,13),J^=T(U+N|0,18),z^=T(G+I|0,7),H^=T(z+G|0,9),I^=T(H+z|0,13),G^=T(I+H|0,18),P^=T(F+K|0,7),W^=T(P+F|0,9),K^=T(W+P|0,13),F^=T(K+W|0,18),Y^=T(D+R|0,7),w^=T(Y+D|0,9),R^=T(w+Y|0,13),D^=T(R+w|0,18),I^=T(J+Y|0,7),W^=T(I+J|0,9),Y^=T(W+I|0,13),J^=T(Y+W|0,18),K^=T(G+X|0,7),w^=T(K+G|0,9),X^=T(w+K|0,13),G^=T(X+w|0,18),R^=T(F+z|0,7),N^=T(R+F|0,9),z^=T(N+R|0,13),F^=T(z+N|0,18),U^=T(D+P|0,7),H^=T(U+D|0,9),P^=T(H+U|0,13),D^=T(P+H|0,18);let O=0;Z[O++]=J,Z[O++]=G,Z[O++]=F,Z[O++]=D,Z[O++]=K,Z[O++]=w,Z[O++]=N,Z[O++]=z}var A$=kQ(WJ,{counterRight:!0,extendNonceFn:YJ}),_$=EQ({blockSize:64,nonceLength:24,tagLength:16},(V,$)=>{return{encrypt(Q,Z){Z=C$(Q.length+32,Z,!1);let J=Z.subarray(0,32),I=Z.subarray(32);Z.set(Q,32),M0(J),A$(V,$,Z,Z);let W=D$(I,J);return Z.set(W,16),M0(Z.subarray(0,16),W),Z.subarray(16)},decrypt(Q,Z){h(Q),Z=C$(Q.length+32,Z,!1);let J=Z.subarray(0,32),I=Z.subarray(32,48),W=Z.subarray(48);Z.set(Q,32),M0(J);let Y=A$(V,$,J,J),X=D$(W,Y);if(!mQ(I,X))throw Error("invalid tag");return A$(V,$,Z.subarray(16),Z.subarray(16)),M0(J,I,X),W}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function XJ(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function GV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function k0(V,...$){if(!XJ(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function KV(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function gV(V,$){k0(V);let Q=$.outputLen;if(V.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function gQ(V){return new Uint8Array(V.buffer,V.byteOffset,V.byteLength)}function c0(V){return new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4))}function d0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function MV(V,$){return V<<32-$|V>>>$}var iQ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function vQ(V){return V<<24&4278190080|V<<8&16711680|V>>>8&65280|V>>>24&255}var uQ=iQ?(V)=>V:(V)=>vQ(V);function GJ(V){for(let $=0;$<V.length;$++)V[$]=vQ(V[$]);return V}var V0=iQ?(V)=>V:GJ;function KJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function o0(V){if(typeof V==="string")V=KJ(V);return k0(V),V}class j${}function nQ(V){let $=(Z,J)=>V(J).update(o0(Z)).digest(),Q=V({});return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=(Z)=>V(Z),$}var yQ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var iV=BigInt(4294967295),bQ=BigInt(32);function L$(V,$=!1){if($)return{h:Number(V&iV),l:Number(V>>bQ&iV)};return{h:Number(V>>bQ&iV)|0,l:Number(V&iV)|0}}function U0(V,$,Q,Z,J){return V=V+$+J|0,Z=MV(Z^V,16),Q=Q+Z|0,$=MV($^Q,12),{a:V,b:$,c:Q,d:Z}}function O0(V,$,Q,Z,J){return V=V+$+J|0,Z=MV(Z^V,8),Q=Q+Z|0,$=MV($^Q,7),{a:V,b:$,c:Q,d:Z}}class m$ extends j${constructor(V,$){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,GV(V),GV($),this.blockLen=V,this.outputLen=$,this.buffer=new Uint8Array(V),this.buffer32=c0(this.buffer)}update(V){KV(this),V=o0(V),k0(V);let{blockLen:$,buffer:Q,buffer32:Z}=this,J=V.length,I=V.byteOffset,W=V.buffer;for(let Y=0;Y<J;){if(this.pos===$)V0(Z),this.compress(Z,0,!1),V0(Z),this.pos=0;let X=Math.min($-this.pos,J-Y),G=I+Y;if(X===$&&!(G%4)&&Y+X<J){let K=new Uint32Array(W,G,Math.floor((J-Y)/4));V0(K);for(let w=0;Y+$<J;w+=Z.length,Y+=$)this.length+=$,this.compress(K,w,!1);V0(K);continue}Q.set(V.subarray(Y,Y+X),this.pos),this.pos+=X,this.length+=X,Y+=X}return this}digestInto(V){KV(this),gV(V,this);let{pos:$,buffer32:Q}=this;this.finished=!0,d0(this.buffer.subarray($)),V0(Q),this.compress(Q,0,!0),V0(Q);let Z=c0(V);this.get().forEach((J,I)=>Z[I]=uQ(J))}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Q=V.slice(0,$);return this.destroy(),Q}_cloneInto(V){let{buffer:$,length:Q,finished:Z,destroyed:J,outputLen:I,pos:W}=this;return V||(V=new this.constructor({dkLen:I})),V.set(...this.get()),V.buffer.set($),V.destroyed=J,V.finished=Z,V.length=Q,V.pos=W,V.outputLen=I,V}clone(){return this._cloneInto()}}function E$(V,$,Q,Z,J,I,W,Y,X,G,K,w,N,z,F,R,U,H,P,D){let O=0;for(let A=0;A<Z;A++)({a:J,b:X,c:N,d:U}=U0(J,X,N,U,Q[$+V[O++]])),{a:J,b:X,c:N,d:U}=O0(J,X,N,U,Q[$+V[O++]]),{a:I,b:G,c:z,d:H}=U0(I,G,z,H,Q[$+V[O++]]),{a:I,b:G,c:z,d:H}=O0(I,G,z,H,Q[$+V[O++]]),{a:W,b:K,c:F,d:P}=U0(W,K,F,P,Q[$+V[O++]]),{a:W,b:K,c:F,d:P}=O0(W,K,F,P,Q[$+V[O++]]),{a:Y,b:w,c:R,d:D}=U0(Y,w,R,D,Q[$+V[O++]]),{a:Y,b:w,c:R,d:D}=O0(Y,w,R,D,Q[$+V[O++]]),{a:J,b:G,c:F,d:D}=U0(J,G,F,D,Q[$+V[O++]]),{a:J,b:G,c:F,d:D}=O0(J,G,F,D,Q[$+V[O++]]),{a:I,b:K,c:R,d:U}=U0(I,K,R,U,Q[$+V[O++]]),{a:I,b:K,c:R,d:U}=O0(I,K,R,U,Q[$+V[O++]]),{a:W,b:w,c:N,d:H}=U0(W,w,N,H,Q[$+V[O++]]),{a:W,b:w,c:N,d:H}=O0(W,w,N,H,Q[$+V[O++]]),{a:Y,b:X,c:z,d:P}=U0(Y,X,z,P,Q[$+V[O++]]),{a:Y,b:X,c:z,d:P}=O0(Y,X,z,P,Q[$+V[O++]]);return{v0:J,v1:I,v2:W,v3:Y,v4:X,v5:G,v6:K,v7:w,v8:N,v9:z,v10:F,v11:R,v12:U,v13:H,v14:P,v15:D}}var w0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},q0=yQ.slice(),pQ=(()=>{let V=Array.from({length:16},(Z,J)=>J),$=(Z)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((J)=>Z[J]),Q=[];for(let Z=0,J=V;Z<7;Z++,J=$(J))Q.push(...J);return Uint8Array.from(Q)})();class S$ extends m${constructor(V={},$=0){super(64,V.dkLen===void 0?32:V.dkLen);this.chunkPos=0,this.chunksDone=0,this.flags=0,this.stack=[],this.posOut=0,this.bufferOut32=new Uint32Array(16),this.chunkOut=0,this.enableXOF=!0;let{key:Q,context:Z}=V,J=Z!==void 0;if(Q!==void 0){if(J)throw Error('Only "key" or "context" can be specified at same time');let I=o0(Q).slice();k0(I,32),this.IV=c0(I),V0(this.IV),this.flags=$|w0.KEYED_HASH}else if(J){let I=o0(Z),W=new S$({dkLen:32},w0.DERIVE_KEY_CONTEXT).update(I).digest();this.IV=c0(W),V0(this.IV),this.flags=$|w0.DERIVE_KEY_MATERIAL}else this.IV=q0.slice(),this.flags=$;this.state=this.IV.slice(),this.bufferOut=gQ(this.bufferOut32)}get(){return[]}set(){}b2Compress(V,$,Q,Z=0){let{state:J,pos:I}=this,{h:W,l:Y}=L$(BigInt(V),!0),{v0:X,v1:G,v2:K,v3:w,v4:N,v5:z,v6:F,v7:R,v8:U,v9:H,v10:P,v11:D,v12:O,v13:A,v14:m,v15:x}=E$(pQ,Z,Q,7,J[0],J[1],J[2],J[3],J[4],J[5],J[6],J[7],q0[0],q0[1],q0[2],q0[3],W,Y,I,$);J[0]=X^U,J[1]=G^H,J[2]=K^P,J[3]=w^D,J[4]=N^O,J[5]=z^A,J[6]=F^m,J[7]=R^x}compress(V,$=0,Q=!1){let Z=this.flags;if(!this.chunkPos)Z|=w0.CHUNK_START;if(this.chunkPos===15||Q)Z|=w0.CHUNK_END;if(!Q)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,Z,V,$),this.chunkPos+=1,this.chunkPos===16||Q){let J=this.state;this.state=this.IV.slice();for(let I,W=this.chunksDone+1;Q||!(W&1);W>>=1){if(!(I=this.stack.pop()))break;this.buffer32.set(I,0),this.buffer32.set(J,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|w0.PARENT,this.buffer32,0),J=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(J)}this.pos=0}_cloneInto(V){V=super._cloneInto(V);let{IV:$,flags:Q,state:Z,chunkPos:J,posOut:I,chunkOut:W,stack:Y,chunksDone:X}=this;return V.state.set(Z.slice()),V.stack=Y.map((G)=>Uint32Array.from(G)),V.IV.set($),V.flags=Q,V.chunkPos=J,V.chunksDone=X,V.posOut=I,V.chunkOut=W,V.enableXOF=this.enableXOF,V.bufferOut32.set(this.bufferOut32),V}destroy(){this.destroyed=!0,d0(this.state,this.buffer32,this.IV,this.bufferOut32),d0(...this.stack)}b2CompressOut(){let{state:V,pos:$,flags:Q,buffer32:Z,bufferOut32:J}=this,{h:I,l:W}=L$(BigInt(this.chunkOut++));V0(Z);let{v0:Y,v1:X,v2:G,v3:K,v4:w,v5:N,v6:z,v7:F,v8:R,v9:U,v10:H,v11:P,v12:D,v13:O,v14:A,v15:m}=E$(pQ,0,Z,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],q0[0],q0[1],q0[2],q0[3],W,I,$,Q);J[0]=Y^R,J[1]=X^U,J[2]=G^H,J[3]=K^P,J[4]=w^D,J[5]=N^O,J[6]=z^A,J[7]=F^m,J[8]=V[0]^R,J[9]=V[1]^U,J[10]=V[2]^H,J[11]=V[3]^P,J[12]=V[4]^D,J[13]=V[5]^O,J[14]=V[6]^A,J[15]=V[7]^m,V0(Z),V0(J),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,d0(this.buffer.subarray(this.pos));let V=this.flags|w0.ROOT;if(this.stack.length)V|=w0.PARENT,V0(this.buffer32),this.compress(this.buffer32,0,!0),V0(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else V|=(!this.chunkPos?w0.CHUNK_START:0)|w0.CHUNK_END;this.flags=V,this.b2CompressOut()}writeInto(V){KV(this,!1),k0(V),this.finish();let{blockLen:$,bufferOut:Q}=this;for(let Z=0,J=V.length;Z<J;){if(this.posOut>=$)this.b2CompressOut();let I=Math.min($-this.posOut,J-Z);V.set(Q.subarray(this.posOut,this.posOut+I),Z),this.posOut+=I,Z+=I}return V}xofInto(V){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(V)}xof(V){return GV(V),this.xofInto(new Uint8Array(V))}digestInto(V){if(gV(V,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto(V),this.destroy(),V}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var lQ=nQ((V)=>new S$(V));var f$=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function hQ(V){let $=new Uint8Array(f$.length+32);return $.set(f$),$.set(V.subarray(0,32),f$.length),$}function rQ(V){return typeof V==="string"?new TextEncoder().encode(V):V}function a0(V){let $=new ArrayBuffer(V.byteLength);return new Uint8Array($).set(V),$}class x${verifyKeys=new Map;signKeys=new Map;async genRandomBytes(V){return kV(V)}async gen256BitSecureRandomSeed(){return kV(32)}async encryptXSalsa20Poly1305Combined(V,$){let Q=kV(24),J=_$($,Q).encrypt(V);return new Uint8Array([...Q,...J])}async decryptXSalsa20Poly1305Combined(V,$){let Q=V.slice(0,24),Z=V.slice(24);return _$($,Q).decrypt(Z)}async deriveEd25519KeyPair(V){let $=V,Q=hQ($),Z=await globalThis.crypto.subtle.importKey("pkcs8",a0(Q),{name:"Ed25519"},!0,["sign"]),J=await globalThis.crypto.subtle.exportKey("jwk",Z);if(typeof J.x!=="string")throw Error("Ed25519 JWK missing x");let I=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:J.x},{name:"Ed25519"},!0,["verify"]),W=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",I)),Y=new Uint8Array(64);return Y.set($,0),Y.set(W,32),this.signKeys.set(a($),Z),this.verifyKeys.set(a(W),I),{keyType:"ed25519",privateKey:Y,publicKey:W}}async importSignKey(V){let $=V.subarray(0,32),Q=a($),Z=this.signKeys.get(Q);if(Z)return Z;let J=hQ($),I=await globalThis.crypto.subtle.importKey("pkcs8",a0(J),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Q,I),I}async importVerifyKey(V){let $=a(V),Q=this.verifyKeys.get($);if(Q)return Q;let Z=await globalThis.crypto.subtle.importKey("raw",a0(V),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set($,Z),Z}async signEd25519(V,$){let Q=rQ(V),Z=await this.importSignKey($),J=await globalThis.crypto.subtle.sign({name:"Ed25519"},Z,a0(Q));return new Uint8Array(J)}async checkSigEd25519(V,$,Q){let Z=rQ($);try{let J=await this.importVerifyKey(Q);return await globalThis.crypto.subtle.verify({name:"Ed25519"},J,a0(V),a0(Z))}catch{return!1}}async blake3(V){return lQ(V)}}var MJ=new x$,J0=MJ;import{useEffect as bV,useState as n$}from"react";class k${db;constructor(V){this.db=V}async enq(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(I0,"readwrite"),Z=Q.objectStore(I0);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=`${W.host}:${W.seq}`;Z.put(W,Y)}})}async deq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(I0,"readwrite"),J=Z.objectStore(I0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=`${V}:${Y}`;J.delete(X)}})}async list(){let $=this.db.transaction(I0,"readonly").objectStore(I0);return new Promise((Q,Z)=>{let J=$.getAll();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async count(){let $=this.db.transaction(I0,"readonly").objectStore(I0);return new Promise((Q,Z)=>{let J=$.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(I0,"readwrite"),$=V.objectStore(I0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}function cQ(V){return{label:V.label,handle:new URL(V.handle),idx:V.idx,lastSeq:V.lastSeq||0,clockOffset:V.clockOffset,subscription:V.subscription}}class B${db;constructor(V){this.db=V}async add(V){return this.put(V)}async put(V){let $={...V,handle:V.handle.toString(),lastSeq:V.lastSeq??0},Q=this.db.transaction($0,"readwrite"),Z=Q.objectStore($0);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error),Z.put($)})}async touch(V,$){let Q=this.db.transaction($0,"readwrite"),Z=Q.objectStore($0);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);let W=Z.get(V);W.onsuccess=()=>{let Y=W.result;if(!Y)return;let X=Y.lastSeq||0;if($<=X)return;Z.put({...Y,lastSeq:$})}})}async get(V){let Q=this.db.transaction($0,"readonly").objectStore($0);return new Promise((Z,J)=>{let I=Q.get(V);I.onsuccess=()=>{let W=I.result;if(!W)Z(void 0);else Z(cQ(W))},I.onerror=()=>J(I.error)})}async set(V,$){let Q=await this.get(V);if(!Q)return 13;try{return await this.put({...Q,...$}),0}catch{return 18}}async del(V){let $=this.db.transaction($0,"readwrite"),Q=$.objectStore($0);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),Q.delete(V)})}async list(){let $=this.db.transaction($0,"readonly").objectStore($0);return new Promise((Q,Z)=>{let J=$.getAll();J.onsuccess=()=>{let I=J.result;Q(I.map(cQ))},J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction($0,"readwrite"),$=V.objectStore($0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}class g${crypto;db;constructor(V,$){this.crypto=$;this.db=V}async add(V){let $=this.db.transaction(u,"readwrite"),Q=$.objectStore(u);return new Promise((Z)=>{if(V.length===0){Z([]);return}let J=Array(V.length).fill(0);$.oncomplete=()=>Z(J),$.onerror=()=>{for(let I=0;I<J.length;I++)J[I]=18;Z(J)};for(let I=0;I<V.length;I++){let{key:W,data:Y}=V[I],X=L(W),G=Q.put(Y,X);G.onerror=(K)=>{K.preventDefault(),J[I]=18}}})}async del(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=L(W);Z.delete(Y)}})}async get(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let I=L(V),W=Q.get(I);W.onsuccess=async()=>{let Y=W.result;if(Y)Z(await L0(V,Y,this.crypto));else Z(void 0)},W.onerror=()=>J(W.error)})}async has(V){return await this.get(V)!==void 0}async list(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let I=[],W=V===void 0?Q.openCursor():Q.index(vV).openCursor(IDBKeyRange.only(V));W.onsuccess=(Y)=>{let X=Y.target.result;if(X){let G=V===void 0?X.key:X.primaryKey,K=X.value;I.push({hash:X0(G),data:K}),X.continue()}else Promise.all(I.map(({hash:G,data:K})=>L0(G,K,this.crypto))).then(Z).catch(J)},W.onerror=()=>J(W.error)})}async last(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let I,W=Q.openCursor();W.onsuccess=async(Y)=>{let X=Y.target.result;if(X){let{key:G,value:K}=X;if(s(V,K.eid)){if(!I||(K.ctr??0)>(I.data.ctr??0)||(K.ctr??0)===(I.data.ctr??0)&&(K.off??0)>(I.data.off??0))I={key:G,data:K}}X.continue()}else if(I){let G=X0(I.key);Z(await L0(G,I.data,this.crypto))}else Z(void 0)},W.onerror=()=>J(W.error)})}async markApplied(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=L(W),X=Z.get(Y);X.onsuccess=()=>{let G=X.result;if(!G)return;S0(G,j0),Z.put(G,Y)},X.onerror=(G)=>{G.preventDefault()}}})}async markFailed(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let{key:W,err:Y}of $){let X=L(W),G=Z.get(X);G.onsuccess=()=>{let K=G.result;if(!K)return;S0(K,K0,Y),Z.put(K,X)},G.onerror=(K)=>{K.preventDefault()}}})}async wipe(){let V=this.db.transaction(u,"readwrite"),$=V.objectStore(u);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}class s0{seed;crypto;constructor(V,$){this.seed=V,this.crypto=$}async deriveFromKDM(V){let $=$V(this.seed,V);return await this.crypto.blake3($)}async derive(V,$=0){let Q=new TextEncoder().encode(V),Z=new Uint8Array(8);new DataView(Z.buffer).setBigUint64(0,BigInt($),!1);let J=$V(Q,Z);return await this.deriveFromKDM(J)}}class i${enclave;db;constructor(V){this.db=V}async save(V){let $=a(V),Q=this.db.transaction(H0,"readwrite"),Z=Q.objectStore(H0);return new Promise((J,I)=>{Q.oncomplete=()=>{this.enclave=new s0(V,J0),J(this.enclave)},Q.onerror=()=>I(Q.error),Z.put($,"seed")})}async load(){if(this.enclave)return this.enclave;let $=this.db.transaction(H0,"readonly").objectStore(H0);return new Promise((Q,Z)=>{let J=$.get("seed");J.onsuccess=()=>{let I=J.result;if(!I)Q(void 0);else{let W=_0(I);this.enclave=new s0(W,J0),Q(this.enclave)}},J.onerror=()=>Z(J.error)})}async wipe(){this.enclave=void 0;let V=this.db.transaction(H0,"readwrite"),$=V.objectStore(H0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.delete("seed")})}}class v${db;constructor(V){this.db=V}async enq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=a(Y);J.put({host:V,hash:X})}})}async deq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=a(Y);J.delete([V,X])}})}async list(V){let Q=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Z,J)=>{let I=Q.getAll();I.onsuccess=()=>{let Y=I.result.filter((X)=>X.host===V).map((X)=>X.hash);Z(Y.map((X)=>_0(X)))},I.onerror=()=>J(I.error)})}async count(){let $=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Q,Z)=>{let J=$.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(W0,"readwrite"),$=V.objectStore(W0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}var H0="seedMeta",$0="hosts",W0="uploadQueue",I0="downloadQueue",u="messages",vV="apld",wJ=3;class u${seed;hosts;uploads;downloads;messages;db;constructor(V,$){this.db=V,this.seed=new i$(V),this.hosts=new B$(V),this.uploads=new v$(V),this.downloads=new k$(V),this.messages=new g$(V,$)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function NJ(){return new Promise((V,$)=>{let Q=indexedDB.open("diplomatic-store-db",wJ);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!Z.objectStoreNames.contains(H0))Z.createObjectStore(H0);if(!Z.objectStoreNames.contains($0))Z.createObjectStore($0,{keyPath:"label"});if(!Z.objectStoreNames.contains(W0))Z.createObjectStore(W0,{keyPath:["host","hash"]});if(!Z.objectStoreNames.contains(I0))Z.createObjectStore(I0);let I;if(!Z.objectStoreNames.contains(u))I=Z.createObjectStore(u);else{if(!J)throw Error("missing upgrade transaction for messages store");I=J.objectStore(u)}if(!I.indexNames.contains(vV))I.createIndex(vV,"apld",{unique:!1})},Q.onsuccess=()=>V(Q.result),Q.onerror=()=>$(Q.error)})}async function uV(V){let $=await NJ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new u$($,V)}function dQ(V){if(!V||typeof V!=="object")return!1;if(!("kind"in V))return!1;return typeof V.kind==="string"}function oQ(V){if(typeof V!=="number")return;return V}function aQ(V){if(!V||typeof V!=="object")return;if(!("hasSeed"in V)||!("hasHost"in V)||!("connected"in V))return;if(typeof V.hasSeed!=="boolean"||typeof V.hasHost!=="boolean"||typeof V.connected!=="boolean")return;return{hasSeed:V.hasSeed,hasHost:V.hasHost,connected:V.connected}}function RJ(V){if(!V||typeof V!=="object")return;if(!("phase"in V))return;let $=zJ(V.phase);if($===void 0)return;let Q={phase:$};if("host"in V&&typeof V.host==="string")Q.host=V.host;if("done"in V&&typeof V.done==="number")Q.done=V.done;if("total"in V&&typeof V.total==="number")Q.total=V.total;if("bytesDone"in V&&typeof V.bytesDone==="number")Q.bytesDone=V.bytesDone;if("bytesTotal"in V&&typeof V.bytesTotal==="number")Q.bytesTotal=V.bytesTotal;return Q}function zJ(V){if(V==="peek"||V==="pull"||V==="open"||V==="exec"||V==="push"||V==="import"||V==="idle"||V==="apply")return V==="apply"?"exec":V;return}function sQ(V){if(!V||typeof V!=="object")return;if(!("numUploads"in V)||!("numDownloads"in V))return;if(typeof V.numUploads!=="number"||typeof V.numDownloads!=="number")return;let $={phase:"idle"};if("progress"in V){let Q=RJ(V.progress);if(Q===void 0)return;$=Q}return{numUploads:V.numUploads,numDownloads:V.numDownloads,progress:$}}var P0="[DIPLOMATIC]";class wV{worker;state;local;nextId=1;pending=new Map;ready;resolveReady;rejectReady;scheduledSync;cachedClientState={hasSeed:!1,hasHost:!1,connected:!1};cachedXferState={numUploads:0,numDownloads:0,progress:E0};clientState;xferState;constructor(V,$,Q,Z,J){this.worker=V,this.state=$,this.clientState=new G0(async()=>this.cachedClientState),this.xferState=new G0(async()=>this.cachedXferState),this.scheduledSync=new IV(J,async()=>{try{await this.request({id:this.allocId(),op:"sync"})}catch(I){console.error(`${P0} worker sync after local write failed`,I)}}),this.local=new f0(Z,$,Q,()=>{throw Error(`${P0} local writer has no transport (use worker for network)`)},J0,!0,void 0,void 0,()=>{this.scheduledSync.schedule()}),this.ready=new Promise((I,W)=>{this.resolveReady=I,this.rejectReady=W}),this.worker.onmessage=(I)=>{this.onMessage(I.data)},this.worker.onerror=(I)=>{console.error(`${P0} worker error`,I),this.failReady(Error(`${P0} worker failed to load`))},this.worker.onmessageerror=()=>{this.failReady(Error(`${P0} worker message error`))}}failReady(V){let $=this.rejectReady;if(this.rejectReady=void 0,this.resolveReady=void 0,$)$(V)}async flushScheduledSync(){await this.scheduledSync.flush()}static async connect(V,$,Q){let Z=Q.clock??new R0,J=Q.syncDebounceMs??mV,I=new wV(Q.worker,V,$,Z,J),W=Q.readyTimeoutMs??15000,Y;try{let X=I.probeReady();if(await Promise.race([I.ready,X,new Promise((G,K)=>{Y=setTimeout(()=>{K(Error(`${P0} worker ready timeout after ${W}ms`))},W)})]),Y!==void 0)clearTimeout(Y),Y=void 0;X.catch(()=>{}),await I.hydrateStateFromStore($),await I.pullRemoteState()}catch(X){throw I.terminate(),X}finally{if(Y!==void 0)clearTimeout(Y)}return I}async hydrateStateFromStore(V){let $=await V.seed.load(),Q=await V.hosts.list();this.cachedClientState={hasSeed:$!==void 0,hasHost:Array.from(Q).length>0,connected:!1};let Z=await V.uploads.count(),J=await V.downloads.count();this.cachedXferState={numUploads:Z,numDownloads:J,progress:E0}}async pullRemoteState(){let V=await this.request({id:this.allocId(),op:"getClientState"}),$=aQ(V);if($!==void 0)this.cachedClientState=$;let Q=await this.request({id:this.allocId(),op:"getXferState"}),Z=sQ(Q);if(Z!==void 0)this.cachedXferState=Z}markReady(){let V=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V()}probeReady(){return new Promise((V,$)=>{let Q=this.allocId();this.pending.set(Q,{resolve:(Z)=>{if(Z==="pong"){this.markReady(),V();return}$(Error(`${P0} worker probe ping failed`))},reject:$}),this.worker.postMessage({id:Q,op:"ping"})})}async ping(){if(await this.ready,await this.request({id:this.allocId(),op:"ping"})!=="pong")throw Error(`${P0} worker ping failed`)}terminate(){this.scheduledSync.cancel(),this.worker.terminate();for(let[,V]of this.pending)V.reject(Error(`${P0} worker terminated`));this.pending.clear()}onMessage(V){if(!dQ(V))return;let $=V;switch($.kind){case"ready":{this.markReady();return}case"clientState":{this.cachedClientState=$.state,this.clientState.emit();return}case"xferState":{this.cachedXferState=$.state,this.xferState.emit();return}case"dirty":{this.state.refresh($.eids.map(FJ));return}case"wiped":{this.state.clear();return}case"reply":{let Q=this.pending.get($.id);if(!Q)return;if(this.pending.delete($.id),$.ok)Q.resolve($.result);else Q.reject(new nV($.status));return}default:return}}allocId(){let V=this.nextId;return this.nextId+=1,V}request(V,$){return new Promise((Q,Z)=>{if(this.pending.set(V.id,{resolve:Q,reject:Z}),$&&$.length>0)this.worker.postMessage(V,$);else this.worker.postMessage(V)})}async requestStatus(V,$){try{let Q=await this.request(V,$),Z=oQ(Q);if(Z!==void 0)return Z;return 0}catch(Q){if(Q instanceof nV)return Q.status;return 12}}serializeHost(V){return{handle:V.handle.href,label:V.label,idx:V.idx??0}}async setSeed(V){await this.ready,await this.local.setSeed(V);let $=V.slice();await this.request({id:this.allocId(),op:"setSeed",seed:$},[$.buffer])}async link(V,$=!0){await this.ready,await this.local.link(V,!1),await this.request({id:this.allocId(),op:"link",host:this.serializeHost(V),connect:$})}async unlink(V){await this.ready,await this.local.unlink(V),await this.request({id:this.allocId(),op:"unlink",label:V})}async hosts(){return await this.ready,this.local.hosts()}async connect(V=!0,$=!0){await this.ready,await this.request({id:this.allocId(),op:"connect",listen:V,sync:$})}async disconnect(){await this.ready,await this.request({id:this.allocId(),op:"disconnect"})}async insertRaw(V){return await this.ready,this.local.insertRaw(V)}async updateRaw(V,$,Q){return await this.ready,this.local.updateRaw(V,$,Q)}async insert(V){return await this.ready,this.local.insert(V)}async update(V){return await this.ready,this.local.update(V)}async delete(V){return await this.ready,this.local.delete(V)}async genEID(V){return await this.ready,this.local.genEID(V)}async sync(){return await this.ready,this.requestStatus({id:this.allocId(),op:"sync"})}async wipe(){await this.ready,await this.request({id:this.allocId(),op:"wipe"})}async import(V){await this.ready;let $=new Uint8Array(await V.arrayBuffer());return this.requestStatus({id:this.allocId(),op:"import",bytes:$},[$.buffer])}async export(V,$){await this.ready;try{let Q=await this.request({id:this.allocId(),op:"export"});if(!(Q instanceof Uint8Array))return 12;let Z=new Blob([Q.slice()]);return EV(Z,V),0}catch(Q){if(Q instanceof nV)return Q.status;return 12}}}class nV extends Error{status;constructor(V){super(`WorkerReplyError: ${_[V]}`);this.status=V;this.name="WorkerReplyError"}}function FJ(V){return V}var B0="[DIPLOMATIC]";async function yV(V){let $=V.clock??new R0;if(V.worker!==void 0&&UJ(V)!==void 0)throw Error(`${B0} worker path requires IndexedDB on both sides; do not pass store (got a custom store)`);if(V.worker===void 0){console.info(`${B0} sync on main thread `+"(no worker — app did not request a worker)");let J=await tQ(V.store);return OJ($,V.state,J)}if(typeof Worker>"u")throw Error(`${B0} worker was provided but Worker API is unavailable`);let Q=await tQ(void 0);console.info(`${B0} attaching app-provided sync worker…`);let Z=await wV.connect(V.state,Q,{worker:V.worker,readyTimeoutMs:V.readyTimeoutMs,clock:$,syncDebounceMs:V.syncDebounceMs});return await Z.ping(),console.info(`${B0} sync worker active (network + EntDB writes off main; local mutates on main; dirty signals only)`),{client:Z,mode:"worker",dispose:()=>{console.info(`${B0} terminating sync worker`),Z.terminate()}}}function UJ(V){if("store"in V)return V.store;return}async function OJ(V,$,Q){let Z=new f0(V,$,Q,CV,J0);return{client:Z,mode:"main",dispose:()=>{Z.disconnect()}}}async function tQ(V){if(V!==void 0)return V;if(typeof indexedDB>"u")throw Error(`${B0} IndexedDB is unavailable; pass store explicitly (e.g. new MemoryStore(crypto))`);return uV(J0)}function qJ(V){let[$,Q]=n$();return bV(()=>{async function Z(){let I=await V.clientState.get();Q(I)}let J=V.clientState.listen(Z);return Z(),()=>{J()}},[V]),$}function HJ(V){let[$,Q]=n$();return bV(()=>{async function Z(){let I=await V.xferState.get();Q(I)}let J=V.xferState.listen(Z);return Z(),()=>{J()}},[V]),$}function PJ(V){bV(()=>{async function $(){try{await V.connect(),await V.sync()}catch(I){console.error("reconnectAndSync failed",I)}}function Q(){$()}function Z(){if(typeof document<"u"&&document.visibilityState==="visible")$()}function J(){$()}if(globalThis.addEventListener("online",Q),typeof document<"u")document.addEventListener("visibilitychange",Z);return globalThis.addEventListener("focus",J),globalThis.addEventListener("pageshow",J),()=>{if(globalThis.removeEventListener("online",Q),typeof document<"u")document.removeEventListener("visibilitychange",Z);globalThis.removeEventListener("focus",J),globalThis.removeEventListener("pageshow",J)}},[V])}function CJ(V={}){let $=V.clock??new R0,{seed:Q,host:Z,readyTimeoutMs:J}=V,I=V.worker,W="store"in V?V.store:void 0,[Y,X]=n$({stateMgr:Y$});return bV(()=>{let G=!1,K;return(async()=>{let w=await w$();if(G)return;let N=jV(w),z=I!==void 0?await yV({state:N,clock:$,worker:I,readyTimeoutMs:J}):await yV({state:N,clock:$,store:W,readyTimeoutMs:J});if(G){z.dispose();return}K=z.dispose;let{client:F,mode:R}=z;if(Q)await F.setSeed(Q);if(Z)await F.link(Z);if(G){K();return}X({client:F,entDB:w,stateMgr:N,mode:R,error:void 0})})().catch((w)=>{let N=w instanceof Error?w:Error(String(w));if(console.error("[DIPLOMATIC] useClient init failed",N),!G)X((z)=>({...z,client:void 0,error:N}))}),()=>{G=!0,K?.()}},[$,Q,Z,I,W,J]),Y}import{use as TJ,useEffect as eQ,useRef as DJ,useState as AJ}from"react";function VZ(V,$,Q){let[Z,J]=AJ();return eQ(()=>{async function I(){let W=await Q();J(W)}return I(),V.on($,I),()=>{V.off($,I)}},[V,$,Q]),Z}function _J(V,$,Q){let Z=DJ(Q());return eQ(()=>{async function J(){Z.current=Q()}return V.on($,J),()=>{V.off($,J)}},[V,$,Q]),TJ(Z.current)}function $Z(V,$){return`${V}:${$}`}class y${queue=new Map;async enq(V){for(let $ of V){let Q=$Z($.host,$.seq);this.queue.set(Q,$)}}async deq(V,$){for(let Q of $){let Z=$Z(V,Q);this.queue.delete(Z)}}async list(){let V=[];for(let $ of this.queue.values())V.push($);return V}async count(){return this.queue.size}async wipe(){this.queue.clear()}}class b${hosts=new Map;async add(V){let $={...V,lastSeq:0};this.hosts.set(V.label,$)}async touch(V,$){let Q=this.hosts.get(V);if(!Q||$<=Q.lastSeq)return;this.hosts.set(V,{...Q,lastSeq:$})}async get(V){return this.hosts.get(V)}async set(V,$){let Q=this.hosts.get(V);if(!Q)return 13;return this.hosts.set(V,{...Q,...$}),0}async del(V){this.hosts.delete(V)}async list(){return this.hosts.values()}async wipe(){this.hosts.clear()}}class p${crypto;messages=new Map;constructor(V){this.crypto=V}async add(V){let $=[];for(let{key:Q,data:Z}of V)this.messages.set(L(Q),Z),$.push(0);return $}async del(V){for(let $ of V)this.messages.delete(L($))}async get(V){let $=this.messages.get(L(V));if($)return await L0(V,$,this.crypto);return}async has(V){return this.messages.has(L(V))}async list(V){let $=[];for(let[Q,Z]of this.messages){if(V!==void 0&&XV(Z.apld)!==V)continue;let J=X0(Q);$.push(await L0(J,Z,this.crypto))}return $}async last(V){let $;for(let[Q,Z]of this.messages){if(s(V,Z.eid)===!1)continue;let J=X0(Q);if($===void 0)$={hash:J,data:Z};else if((Z.ctr??0)>($.data.ctr??0)||(Z.ctr??0)===($.data.ctr??0)&&(Z.off??0)>($.data.off??0))$={hash:J,data:Z}}if($)return await L0($.hash,$.data,this.crypto);return}async markApplied(V){for(let $ of V){let Q=this.messages.get(L($));if(!Q)continue;S0(Q,j0)}}async markFailed(V){for(let{key:$,err:Q}of V){let Z=this.messages.get(L($));if(!Z)continue;S0(Z,K0,Q)}}async wipe(){this.messages.clear()}}class l${enclave;async save(V){return this.enclave=new s0(V,J0),this.enclave}async load(){return this.enclave}async wipe(){this.enclave=void 0}}class h${queue=new Map;async enq(V,$){let Q=this.queue.get(V)||new Set;this.queue.set(V,Q);for(let Z of $)Q.add(a(Z))}async deq(V,$){let Q=this.queue.get(V);if(Q)for(let Z of $)Q.delete(a(Z))}async list(V){let $=this.queue.get(V);if(!$)return[];let Q=[];for(let Z of $)Q.push(_0(Z));return Q}async count(){let V=0;for(let $ of this.queue.values())V+=$.size;return V}async wipe(){this.queue.clear()}}class QZ{seed=new l$;hosts=new b$;uploads=new h$;downloads=new y$;messages;constructor(V){this.messages=new p$(V)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}class ZZ{singletonType;latest;latestOff=-1;emitter=new C0;constructor(V){this.singletonType=V}async apply(V){for(let $ of V){let Q=new f($.eid),[Z,J]=Q.readStruct(r);if(J!==0)continue;let I=new k;I.writeVarString(this.singletonType);let W=I.result();if(Z.id.length===W.length&&Z.id.every((Y,X)=>Y===W[X])){if(this.latest===void 0||$.off>this.latestOff)this.latestOff=$.off,this.latest=$.bod,this.emitter.emit(this.singletonType,null)}}return V.map(()=>0)}clear=async()=>{return this.latest=void 0,this.latestOff=-1,this.emitter.emit(this.singletonType,null),0};notify=(V)=>{for(let $ of V)if($===this.singletonType)this.emitter.emit(this.singletonType,null)};refresh=async(V)=>{this.notify([this.singletonType])};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}async function JN(V,$){let Q=await uV(J0),Z=new f0(new R0,V,Q,CV,J0);return{client:Z,setSeed:async(I)=>{let W=_0(I);await Q.seed.save(W),await Q.hosts.add({handle:$,label:"host",idx:0}),await Z.connect()}}}export{PJ as useSyncOnResume,_J as useStateWatcherSuspense,VZ as useStateWatcher,HJ as useClientXferState,qJ as useClientState,CJ as useClient,R$ as shouldEmitItemProgress,S0 as setApld,N$ as revFromHead,yZ as revFromEntity,uV as openIDBStore,w$ as openEntDB,yV as openDiplomaticClient,Y$ as nullStateManager,bZ as nullEntDB,F$ as isTerminalApplyFailure,hZ as isPendingApply,lZ as isApldState,E0 as idleProgress,_0 as htob,CV as hostHTTPTransport,JN as genWebClient,EZ as genSingletonEID,jV as entStateManager,r as eidCodec,YV as defaultPeekProgressEvery,J0 as crypto,a as btoh,L as btob64,X0 as b64tob,XV as apldFromStored,wV as WorkerClient,C0 as TypedEventEmitter,f0 as SyncClient,_ as Status,ZV as StateManager,ZZ as SingletonStateManager,QZ as MemoryStore,u$ as IDBStore,Z$ as HTTPTransport,M$ as EntIDB,_V as EntDBMemory,k as Encoder,f as Decoder,R0 as Clock,JV as CachedEntDB,z0 as APLD_PENDING,K0 as APLD_ERROR,j0 as APLD_APPLIED};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@interncom/diplomatic",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "type": "module",
5
5
  "description": "Secure sync layer and CLI utilities for DIPLOMATIC",
6
6
  "files": [