@interncom/diplomatic 0.6.2 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- function rV($){let V=$.length,Q=0,Z=0;while(Z<V){let J=$.charCodeAt(Z++);if((J&4294967168)===0){Q++;continue}else if((J&4294965248)===0)Q+=2;else{if(J>=55296&&J<=56319){if(Z<V){let W=$.charCodeAt(Z);if((W&64512)===56320)++Z,J=((J&1023)<<10)+(W&1023)+65536}}if((J&4294901760)===0)Q+=3;else Q+=4}}return Q}function JZ($,V,Q){let Z=$.length,J=Q,W=0;while(W<Z){let Y=$.charCodeAt(W++);if((Y&4294967168)===0){V[J++]=Y;continue}else if((Y&4294965248)===0)V[J++]=Y>>6&31|192;else{if(Y>=55296&&Y<=56319){if(W<Z){let X=$.charCodeAt(W);if((X&64512)===56320)++W,Y=((Y&1023)<<10)+(X&1023)+65536}}if((Y&4294901760)===0)V[J++]=Y>>12&15|224,V[J++]=Y>>6&63|128;else V[J++]=Y>>18&7|240,V[J++]=Y>>12&63|128,V[J++]=Y>>6&63|128}V[J++]=Y&63|128}}var WZ=new TextEncoder,YZ=50;function XZ($,V,Q){WZ.encodeInto($,V.subarray(Q))}function cV($,V,Q){if($.length>YZ)XZ($,V,Q);else JZ($,V,Q)}var IZ=4096;function p$($,V,Q){let Z=V,J=Z+Q,W=[],Y="";while(Z<J){let X=$[Z++];if((X&128)===0)W.push(X);else if((X&224)===192){let I=$[Z++]&63;W.push((X&31)<<6|I)}else if((X&240)===224){let I=$[Z++]&63,K=$[Z++]&63;W.push((X&31)<<12|I<<6|K)}else if((X&248)===240){let I=$[Z++]&63,K=$[Z++]&63,G=$[Z++]&63,N=(X&7)<<18|I<<12|K<<6|G;if(N>65535)N-=65536,W.push(N>>>10&1023|55296),N=56320|N&1023;W.push(N)}else W.push(X);if(W.length>=IZ)Y+=String.fromCharCode(...W),W.length=0}if(W.length>0)Y+=String.fromCharCode(...W);return Y}var KZ=new TextDecoder,GZ=200;function MZ($,V,Q){let Z=$.subarray(V,V+Q);return KZ.decode(Z)}function dV($,V,Q){if(Q>GZ)return MZ($,V,Q);else return p$($,V,Q)}class b0{type;data;constructor($,V){this.type=$,this.data=V}}class e extends Error{constructor($){super($);let V=Object.create(e.prototype);Object.setPrototypeOf(this,V),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}}var n0=4294967295;function oV($,V,Q){let Z=Q/4294967296,J=Q;$.setUint32(V,Z),$.setUint32(V+4,J)}function w$($,V,Q){let Z=Math.floor(Q/4294967296),J=Q;$.setUint32(V,Z),$.setUint32(V+4,J)}function R$($,V){let Q=$.getInt32(V),Z=$.getUint32(V+4);return Q*4294967296+Z}function aV($,V){let Q=$.getUint32(V),Z=$.getUint32(V+4);return Q*4294967296+Z}var NZ=-1,wZ=4294967295,RZ=17179869183;function zZ({sec:$,nsec:V}){if($>=0&&V>=0&&$<=RZ)if(V===0&&$<=wZ){let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,$),Q}else{let Q=$/4294967296,Z=$&4294967295,J=new Uint8Array(8),W=new DataView(J.buffer);return W.setUint32(0,V<<2|Q&3),W.setUint32(4,Z),J}else{let Q=new Uint8Array(12),Z=new DataView(Q.buffer);return Z.setUint32(0,V),w$(Z,4,$),Q}}function FZ($){let V=$.getTime(),Q=Math.floor(V/1000),Z=(V-Q*1000)*1e6,J=Math.floor(Z/1e9);return{sec:Q+J,nsec:Z-J*1e9}}function UZ($){if($ instanceof Date){let V=FZ($);return zZ(V)}else return null}function OZ($){let V=new DataView($.buffer,$.byteOffset,$.byteLength);switch($.byteLength){case 4:{let Q=V.getUint32(0),Z=0;return{sec:Q,nsec:0}}case 8:{let Q=V.getUint32(0),Z=V.getUint32(4),J=(Q&3)*4294967296+Z,W=Q>>>2;return{sec:J,nsec:W}}case 12:{let Q=R$(V,4),Z=V.getUint32(0);return{sec:Q,nsec:Z}}default:throw new e(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${$.length}`)}}function qZ($){let V=OZ($);return new Date(V.sec*1000+V.nsec/1e6)}var sV={type:NZ,encode:UZ,decode:qZ};class p0{static defaultCodec=new p0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(sV)}register({type:$,encode:V,decode:Q}){if($>=0)this.encoders[$]=V,this.decoders[$]=Q;else{let Z=-1-$;this.builtInEncoders[Z]=V,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 W=-1-Q;return new b0(W,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 b0(Q,J)}}if($ instanceof b0)return $;return null}decode($,V,Q){let Z=V<0?this.builtInDecoders[-1-V]:this.decoders[V];if(Z)return Z($,V,Q);else return new b0(V,$)}}function HZ($){return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer}function t0($){if($ instanceof Uint8Array)return $;else if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);else if(HZ($))return new Uint8Array($);else return Uint8Array.from($)}var PZ=100,CZ=2048;class z${extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??p0.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.maxDepth=$?.maxDepth??PZ,this.initialBufferSize=$?.initialBufferSize??CZ,this.sortKeys=$?.sortKeys??!1,this.forceFloat32=$?.forceFloat32??!1,this.ignoreUndefined=$?.ignoreUndefined??!1,this.forceIntegerToFloat=$?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new z$({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($){if(this.entered)return this.clone().encodeSharedRef($);try{return this.entered=!0,this.reinitializeState(),this.doEncode($,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode($){if(this.entered)return this.clone().encode($);try{return this.entered=!0,this.reinitializeState(),this.doEncode($,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode($,V){if(V>this.maxDepth)throw Error(`Too deep objects in depth ${V}`);if($==null)this.encodeNil();else if(typeof $==="boolean")this.encodeBoolean($);else if(typeof $==="number")if(!this.forceIntegerToFloat)this.encodeNumber($);else this.encodeNumberAsFloat($);else if(typeof $==="string")this.encodeString($);else if(this.useBigInt64&&typeof $==="bigint")this.encodeBigInt64($);else this.encodeObject($,V)}ensureBufferSizeToWrite($){let V=this.pos+$;if(this.view.byteLength<V)this.resizeBuffer(V*2)}resizeBuffer($){let V=new ArrayBuffer($),Q=new Uint8Array(V),Z=new DataView(V);Q.set(this.bytes),this.view=Z,this.bytes=Q}encodeNil(){this.writeU8(192)}encodeBoolean($){if($===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber($){if(!this.forceIntegerToFloat&&Number.isSafeInteger($))if($>=0)if($<128)this.writeU8($);else if($<256)this.writeU8(204),this.writeU8($);else if($<65536)this.writeU8(205),this.writeU16($);else if($<4294967296)this.writeU8(206),this.writeU32($);else if(!this.useBigInt64)this.writeU8(207),this.writeU64($);else this.encodeNumberAsFloat($);else if($>=-32)this.writeU8(224|$+32);else if($>=-128)this.writeU8(208),this.writeI8($);else if($>=-32768)this.writeU8(209),this.writeI16($);else if($>=-2147483648)this.writeU8(210),this.writeI32($);else if(!this.useBigInt64)this.writeU8(211),this.writeI64($);else this.encodeNumberAsFloat($);else this.encodeNumberAsFloat($)}encodeNumberAsFloat($){if(this.forceFloat32)this.writeU8(202),this.writeF32($);else this.writeU8(203),this.writeF64($)}encodeBigInt64($){if($>=BigInt(0))this.writeU8(207),this.writeBigUint64($);else this.writeU8(211),this.writeBigInt64($)}writeStringHeader($){if($<32)this.writeU8(160+$);else if($<256)this.writeU8(217),this.writeU8($);else if($<65536)this.writeU8(218),this.writeU16($);else if($<4294967296)this.writeU8(219),this.writeU32($);else throw Error(`Too long string: ${$} bytes in UTF-8`)}encodeString($){let Q=rV($);this.ensureBufferSizeToWrite(5+Q),this.writeStringHeader(Q),cV($,this.bytes,this.pos),this.pos+=Q}encodeObject($,V){let Q=this.extensionCodec.tryToEncode($,this.context);if(Q!=null)this.encodeExtension(Q);else if(Array.isArray($))this.encodeArray($,V);else if(ArrayBuffer.isView($))this.encodeBinary($);else if(typeof $==="object")this.encodeMap($,V);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply($)}`)}encodeBinary($){let V=$.byteLength;if(V<256)this.writeU8(196),this.writeU8(V);else if(V<65536)this.writeU8(197),this.writeU16(V);else if(V<4294967296)this.writeU8(198),this.writeU32(V);else throw Error(`Too large binary: ${V}`);let Q=t0($);this.writeU8a(Q)}encodeArray($,V){let Q=$.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 $)this.doEncode(Z,V+1)}countWithoutUndefined($,V){let Q=0;for(let Z of V)if($[Z]!==void 0)Q++;return Q}encodeMap($,V){let Q=Object.keys($);if(this.sortKeys)Q.sort();let Z=this.ignoreUndefined?this.countWithoutUndefined($,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 W=$[J];if(!(this.ignoreUndefined&&W===void 0))this.encodeString(J),this.doEncode(W,V+1)}}encodeExtension($){if(typeof $.data==="function"){let Q=$.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($.type),this.writeU8a(Q);return}let V=$.data.length;if(V===1)this.writeU8(212);else if(V===2)this.writeU8(213);else if(V===4)this.writeU8(214);else if(V===8)this.writeU8(215);else if(V===16)this.writeU8(216);else if(V<256)this.writeU8(199),this.writeU8(V);else if(V<65536)this.writeU8(200),this.writeU16(V);else if(V<4294967296)this.writeU8(201),this.writeU32(V);else throw Error(`Too large extension object: ${V}`);this.writeI8($.type),this.writeU8a($.data)}writeU8($){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,$),this.pos++}writeU8a($){let V=$.length;this.ensureBufferSizeToWrite(V),this.bytes.set($,this.pos),this.pos+=V}writeI8($){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,$),this.pos++}writeU16($){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,$),this.pos+=2}writeI16($){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,$),this.pos+=2}writeU32($){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,$),this.pos+=4}writeI32($){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,$),this.pos+=4}writeF32($){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,$),this.pos+=4}writeF64($){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,$),this.pos+=8}writeU64($){this.ensureBufferSizeToWrite(8),oV(this.view,this.pos,$),this.pos+=8}writeI64($){this.ensureBufferSizeToWrite(8),w$(this.view,this.pos,$),this.pos+=8}writeBigUint64($){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,$),this.pos+=8}writeBigInt64($){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,$),this.pos+=8}}function m0($,V){return new z$(V).encodeSharedRef($)}function F$($){return`${$<0?"-":""}0x${Math.abs($).toString(16).padStart(2,"0")}`}var TZ=16,DZ=16;class h${hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor($=TZ,V=DZ){this.maxKeyLength=$,this.maxLengthPerKey=V,this.caches=[];for(let Q=0;Q<this.maxKeyLength;Q++)this.caches.push([])}canBeCached($){return $>0&&$<=this.maxKeyLength}find($,V,Q){let Z=this.caches[Q-1];$:for(let J of Z){let W=J.bytes;for(let Y=0;Y<Q;Y++)if(W[Y]!==$[V+Y])continue $;return J.str}return null}store($,V){let Q=this.caches[$.length-1],Z={bytes:$,str:V};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=p$($,V,Q),W=Uint8Array.prototype.slice.call($,V,V+Q);return this.store(W,J),J}}var l$="array",$$="map_key",eV="map_value",AZ=($)=>{if(typeof $==="string"||typeof $==="number")return $;throw new e("The type of key must be string or number but "+typeof $)};class $Q{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState($){let V=this.getUninitializedStateFromPool();V.type=l$,V.position=0,V.size=$,V.array=Array($)}pushMapState($){let V=this.getUninitializedStateFromPool();V.type=$$,V.readCount=0,V.size=$,V.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let $={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push($)}return this.stack[this.stackHeadPosition]}release($){if(this.stack[this.stackHeadPosition]!==$)throw Error("Invalid stack state. Released state is not on top of the stack.");if($.type===l$){let Q=$;Q.size=0,Q.array=void 0,Q.position=0,Q.type=void 0}if($.type===$$||$.type===eV){let Q=$;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,r$=new DataView(new ArrayBuffer(0)),_Z=new Uint8Array(r$.buffer);try{r$.getInt8(0)}catch($){if(!($ 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 tV=RangeError("Insufficient data"),jZ=new h$;class U${extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=r$;bytes=_Z;headByte=e0;stack=new $Q;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??p0.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.rawStrings=$?.rawStrings??!1,this.maxStrLength=$?.maxStrLength??n0,this.maxBinLength=$?.maxBinLength??n0,this.maxArrayLength=$?.maxArrayLength??n0,this.maxMapLength=$?.maxMapLength??n0,this.maxExtLength=$?.maxExtLength??n0,this.keyDecoder=$?.keyDecoder!==void 0?$.keyDecoder:jZ,this.mapKeyConverter=$?.mapKeyConverter??AZ}clone(){return new U$({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($){let V=t0($);this.bytes=V,this.view=new DataView(V.buffer,V.byteOffset,V.byteLength),this.pos=0}appendBuffer($){if(this.headByte===e0&&!this.hasRemaining(1))this.setBuffer($);else{let V=this.bytes.subarray(this.pos),Q=t0($),Z=new Uint8Array(V.length+Q.length);Z.set(V),Z.set(Q,V.length),this.setBuffer(Z)}}hasRemaining($){return this.view.byteLength-this.pos>=$}createExtraByteError($){let{view:V,pos:Q}=this;return RangeError(`Extra ${V.byteLength-Q} of ${V.byteLength} byte(s) found at buffer[${$}]`)}decode($){if(this.entered)return this.clone().decode($);try{this.entered=!0,this.reinitializeState(),this.setBuffer($);let V=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return V}finally{this.entered=!1}}*decodeMulti($){if(this.entered){yield*this.clone().decodeMulti($);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer($);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync($){if(this.entered)return this.clone().decodeAsync($);try{this.entered=!0;let V=!1,Q;for await(let Y of $){if(V)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(Y);try{Q=this.doDecodeSync(),V=!0}catch(X){if(!(X instanceof RangeError))throw X}this.totalPos+=this.pos}if(V){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Q}let{headByte:Z,pos:J,totalPos:W}=this;throw RangeError(`Insufficient data in parsing ${F$(Z)} at ${W} (${J} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream($){return this.decodeMultiAsync($,!0)}decodeStream($){return this.decodeMultiAsync($,!1)}async*decodeMultiAsync($,V){if(this.entered){yield*this.clone().decodeMultiAsync($,V);return}try{this.entered=!0;let Q=V,Z=-1;for await(let J of $){if(V&&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(W){if(!(W instanceof RangeError))throw W}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){$:while(!0){let $=this.readHeadByte(),V;if($>=224)V=$-256;else if($<192)if($<128)V=$;else if($<144){let Z=$-128;if(Z!==0){this.pushMapState(Z),this.complete();continue $}else V={}}else if($<160){let Z=$-144;if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else V=[]}else{let Z=$-160;V=this.decodeString(Z,0)}else if($===192)V=null;else if($===194)V=!1;else if($===195)V=!0;else if($===202)V=this.readF32();else if($===203)V=this.readF64();else if($===204)V=this.readU8();else if($===205)V=this.readU16();else if($===206)V=this.readU32();else if($===207)if(this.useBigInt64)V=this.readU64AsBigInt();else V=this.readU64();else if($===208)V=this.readI8();else if($===209)V=this.readI16();else if($===210)V=this.readI32();else if($===211)if(this.useBigInt64)V=this.readI64AsBigInt();else V=this.readI64();else if($===217){let Z=this.lookU8();V=this.decodeString(Z,1)}else if($===218){let Z=this.lookU16();V=this.decodeString(Z,2)}else if($===219){let Z=this.lookU32();V=this.decodeString(Z,4)}else if($===220){let Z=this.readU16();if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else V=[]}else if($===221){let Z=this.readU32();if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else V=[]}else if($===222){let Z=this.readU16();if(Z!==0){this.pushMapState(Z),this.complete();continue $}else V={}}else if($===223){let Z=this.readU32();if(Z!==0){this.pushMapState(Z),this.complete();continue $}else V={}}else if($===196){let Z=this.lookU8();V=this.decodeBinary(Z,1)}else if($===197){let Z=this.lookU16();V=this.decodeBinary(Z,2)}else if($===198){let Z=this.lookU32();V=this.decodeBinary(Z,4)}else if($===212)V=this.decodeExtension(1,0);else if($===213)V=this.decodeExtension(2,0);else if($===214)V=this.decodeExtension(4,0);else if($===215)V=this.decodeExtension(8,0);else if($===216)V=this.decodeExtension(16,0);else if($===199){let Z=this.lookU8();V=this.decodeExtension(Z,1)}else if($===200){let Z=this.lookU16();V=this.decodeExtension(Z,2)}else if($===201){let Z=this.lookU32();V=this.decodeExtension(Z,4)}else throw new e(`Unrecognized type byte: ${F$($)}`);this.complete();let Q=this.stack;while(Q.length>0){let Z=Q.top();if(Z.type===l$)if(Z.array[Z.position]=V,Z.position++,Z.position===Z.size)V=Z.array,Q.release(Z);else continue $;else if(Z.type===$$){if(V==="__proto__")throw new e("The key __proto__ is not allowed");Z.key=this.mapKeyConverter(V),Z.type=eV;continue $}else if(Z.map[Z.key]=V,Z.readCount++,Z.readCount===Z.size)V=Z.map,Q.release(Z);else{Z.key=null,Z.type=$$;continue $}}return V}}readHeadByte(){if(this.headByte===e0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=e0}readArraySize(){let $=this.readHeadByte();switch($){case 220:return this.readU16();case 221:return this.readU32();default:if($<160)return $-144;else throw new e(`Unrecognized array type byte: ${F$($)}`)}}pushMapState($){if($>this.maxMapLength)throw new e(`Max length exceeded: map length (${$}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState($)}pushArrayState($){if($>this.maxArrayLength)throw new e(`Max length exceeded: array length (${$}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState($)}decodeString($,V){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String($,V);return this.decodeBinary($,V)}decodeUtf8String($,V){if($>this.maxStrLength)throw new e(`Max length exceeded: UTF-8 byte length (${$}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+V+$)throw tV;let Q=this.pos+V,Z;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached($))Z=this.keyDecoder.decode(this.bytes,Q,$);else Z=dV(this.bytes,Q,$);return this.pos+=V+$,Z}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===$$;return!1}decodeBinary($,V){if($>this.maxBinLength)throw new e(`Max length exceeded: bin length (${$}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining($+V))throw tV;let Q=this.pos+V,Z=this.bytes.subarray(Q,Q+$);return this.pos+=V+$,Z}decodeExtension($,V){if($>this.maxExtLength)throw new e(`Max length exceeded: ext length (${$}) > maxExtLength (${this.maxExtLength})`);let Q=this.view.getInt8(this.pos+V),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 $=this.view.getUint8(this.pos);return this.pos++,$}readI8(){let $=this.view.getInt8(this.pos);return this.pos++,$}readU16(){let $=this.view.getUint16(this.pos);return this.pos+=2,$}readI16(){let $=this.view.getInt16(this.pos);return this.pos+=2,$}readU32(){let $=this.view.getUint32(this.pos);return this.pos+=4,$}readI32(){let $=this.view.getInt32(this.pos);return this.pos+=4,$}readU64(){let $=aV(this.view,this.pos);return this.pos+=8,$}readI64(){let $=R$(this.view,this.pos);return this.pos+=8,$}readU64AsBigInt(){let $=this.view.getBigUint64(this.pos);return this.pos+=8,$}readI64AsBigInt(){let $=this.view.getBigInt64(this.pos);return this.pos+=8,$}readF32(){let $=this.view.getFloat32(this.pos);return this.pos+=4,$}readF64(){let $=this.view.getFloat64(this.pos);return this.pos+=8,$}}function c$($,V){return new U$(V).decode($)}class C0{listeners=new Map;addEventListener($,V){let Q=this.listeners.get($);if(!Q)Q=new Set,this.listeners.set($,Q);return Q.add(V),()=>{this.removeEventListener($,V)}}removeEventListener($,V){let Q=this.listeners.get($);if(Q){if(Q.delete(V),Q.size===0)this.listeners.delete($)}}emit($,V){let Q=this.listeners.get($);if(Q){let Z=Array.from(Q);for(let J of Z)J(V)}}emitAll($){let V=Array.from(this.listeners.keys());for(let Q of V)this.emit(Q,$)}}class K0{getter;static eventName="update";emitter;constructor($){this.getter=$;this.emitter=new C0}get=()=>this.getter();async emit(){let $=await this.getter();queueMicrotask(()=>this.emitter.emit(K0.eventName,$))}listen($){return this.emitter.addEventListener(K0.eventName,$),()=>{this.emitter.removeEventListener(K0.eventName,$)}}}var T0=64;var VQ=32,D0=8;var O$=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 U($){return[$,0]}function M($){return[void 0,$]}function LZ($){if($<0)console.info("N",$),console.trace();if(typeof $!=="bigint")$=BigInt($);if($<0n)return M(10);let V=[];while($>0n){let Q=Number($&0x7fn);if($>>=7n,$>0n)V.push(Q|128);else V.push(Q)}if(V.length===0)return U(new Uint8Array([0]));if(V.length>8)return M(26);return U(new Uint8Array(V))}function mZ($,V=0){let Q=0n,Z=0,J=V;while(!0){if(J>=$.length)return M(14);let W=$[J++];if(W===void 0)return M(14);if(Q|=BigInt(W&127)<<BigInt(Z),(W&128)===0){if(J-V>8)return M(26);return U({value:Q>0x1fffffffffffffn?Q:Number(Q),bytesRead:J-V})}if(Z+=7,Z>=56)return M(26)}}class x{data;pos=0;constructor($){this.data=$}static async fromResponse($){let V=await $.arrayBuffer(),Q=new Uint8Array(V);return new x(Q)}readBigInt(){if(this.pos+8>this.data.length)return M(7);let $=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,U($)}readDate(){let[$,V]=this.readVarInt();if(V!==0)return M(V);return U(new Date($))}readVarInt(){let[$,V]=mZ(this.data,this.pos);if(V!==0)return M(V);this.pos+=$.bytesRead;let Q=$.value;return U(typeof Q==="bigint"?Number(Q):Q)}readVarString(){let[$,V]=this.readVarInt();if(V!==0)return M(V);let[Q,Z]=this.readBytes($);if(Z!==0)return M(Z);let J=new TextDecoder().decode(Q);return U(J)}readBytes($){if($<0)return M(10);if(this.pos+$>this.data.length)return M(23);let V=this.data.slice(this.pos,this.pos+$);return this.pos+=$,U(V)}readVarBytes(){let[$,V]=this.readVarInt();if(V!==0)return M(V);return this.readBytes($)}readStruct($){return $.decode(this)}readStructs($){let V=[];while(!this.done()){let[Q,Z]=this.readStruct($);if(Z!==0)return M(Z);V.push(Q)}return U(V)}readBytesSeq($){let V=[];while(!this.done()){let[Q,Z]=this.readBytes($);if(Z!==0)return M(Z);V.push(Q)}return U(V)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class B{parts=[];writeBigInt($){let V=new Uint8Array(8);new DataView(V.buffer).setBigUint64(0,$,!1),this.parts.push(V)}writeDate($){let V=$.getTime();return this.writeVarInt(V)}writeVarInt($){let[V,Q]=LZ($);if(Q!==0)return Q;return this.parts.push(V),0}writeVarString($){let V=new TextEncoder().encode($),Q=this.writeVarInt(V.length);if(Q!==0)return Q;return this.writeBytes(V),0}prependBytes($){this.parts.unshift($)}writeBytes($){this.parts.push($)}writeVarBytes($){let V=this.writeVarInt($.length);if(V!==0)return V;return this.writeBytes($),0}writeStruct($,V){return $.encode(this,V)}writeStructs($,V){for(let Q of V){let Z=this.writeStruct($,Q);if(Z!==0)return Z}return 0}writeBytesSeq($){for(let V of $)this.writeBytes(V)}result(){let $=this.parts.reduce((Z,J)=>Z+J.length,0),V=new Uint8Array($),Q=0;for(let Z of this.parts)V.set(Z,Q),Q+=Z.length;return V}*scan(){for(let $ of this.parts)yield $}}async function d$($,V,Q){let Z=new B,J=Z.writeDate(V);if(J!==0)return M(J);let W=Z.result(),Y=await Q.signEd25519(W,$.privateKey);return U({pubKey:$.publicKey,sig:Y,timestamp:V})}async function A0($,V,Q){let Z=Q.now().getTime(),J=$.timestamp.getTime();if(Math.abs(Z-J)>QQ)return 4;let Y=new B;Y.writeDate($.timestamp);let X=Y.result();if(!await V.checkSigEd25519($.sig,X,$.pubKey))return 3;return 0}var r={encode($,V){let Q=$.writeVarBytes(V.id);if(Q!==0)return Q;let Z=$.writeDate(V.ts);if(Z!==0)return Z;return 0},decode($){let[V,Q]=$.readVarBytes();if(Q!==0)return M(Q);let[Z,J]=$.readDate();if(J!==0)return M(J);return U({id:V,ts:Z})}};function h0($){let V=new B,Q=V.writeStruct(r,$);if(Q!==0)return M(Q);let Z=V.result();return U(Z)}async function SZ($){return h0({id:$,ts:new Date(0)})}var X0={encode($,V){let Q=$.writeVarBytes(V.eid);if(Q!==0)return Q;let Z=$.writeVarInt(V.off);if(Z!==0)return Z;let J=$.writeVarInt(V.ctr);if(J!==0)return J;let W=$.writeVarInt(V.len);if(W!==0)return W;if(V.hsh)$.writeBytes(V.hsh);return 0},decode($){let[V,Q]=$.readVarBytes();if(Q!==0)return M(Q);let Z=new x(V),[,J]=r.decode(Z);if(J!==0)return M(J);let[W,Y]=$.readVarInt();if(Y!==0)return M(Y);let[X,I]=$.readVarInt();if(I!==0)return M(I);let[K,G]=$.readVarInt();if(G!==0)return M(G);let N;if(K>0){let[w,z]=$.readBytes(O$);if(z!==0)return M(z);N=w}return U({eid:V,off:W,ctr:X,len:K,hsh:N})}};function a($){return Array.from($).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}function _0($){if($.length%2!==0)throw Error("Invalid hex string");let V=new Uint8Array($.length/2);for(let Q=0;Q<$.length;Q+=2)V[Q/2]=Number.parseInt($.substr(Q,2),16);return V}function s($,V){if($===V)return!0;if($.byteLength!==V.byteLength)return!1;return $.every((Q,Z)=>Q===V[Z])}var L;if(typeof Uint8Array.prototype.toBase64==="function")L=($)=>$.toBase64();else L=($)=>btoa(String.fromCharCode(...$));var I0;if(typeof Uint8Array.fromBase64==="function")I0=($)=>Uint8Array.fromBase64($);else I0=($)=>Uint8Array.from(atob($),(V)=>V.charCodeAt(0));function V$($,V){let Q=new Uint8Array($.length+V.length);return Q.set($,0),Q.set(V,$.length),Q}function JQ($,V,Q){return Q.checkSigEd25519($.sig,$.headCph,V)}async function o$($,V,Q){let Z=V$(V.privateKey,$);return(await Q.blake3(Z)).slice(0,D0)}async function WQ($,V,Q,Z){let J;if($.bod&&$.len>0)J=await Q.blake3($.bod);let W=new B,Y=X0.encode(W,{...$,hsh:J});if(Y!==0)return M(Y);let X=W.result(),I=await o$(X,V,Q),K=await Z.deriveFromKDM(I),G=await Q.encryptXSalsa20Poly1305Combined(X,K),N=$.bod?await Q.encryptXSalsa20Poly1305Combined($.bod,K):new Uint8Array(0),w=await Q.signEd25519(G,V.privateKey);return U({sig:w,kdm:I,headCph:G,bodyCph:N})}async function a$($,V,Q,Z,J){let W=new x($),[Y,X]=X0.decode(W);if(X!==0)return M(14);let I;try{I=V&&V.length>0?await Z.decryptXSalsa20Poly1305Combined(V,Q):void 0}catch{return M(20)}let K=Y.hsh&&I===void 0,G=Y.hsh===void 0&&I!==void 0;if(K||G)return M(19);if(Y.hsh&&I){let w=await Z.blake3(I);if(!s(w,Y.hsh))return M(19)}let N=J??await Z.blake3($);return U({msgHead:Y,bod:I,headHash:N})}class R0{now(){return new Date}}function YQ($,V,Q,Z){let J=V.getTime()-$.getTime(),W=Q.getTime()-Z.getTime();return(J+W)/2}var Q$={encode($,V){if($.writeVarInt(V.quota),V.quota>0){if(V.usage===void 0)return 9;$.writeVarInt(V.usage)}return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return M(Q);let Z;if(V>0){let[J,W]=$.readVarInt();if(W!==0)return M(W);Z=J}return U({quota:V,usage:Z})}};var s$={encode($,V){$.writeBytes(new Uint8Array([V.status]));let Q=$.writeDate(V.timeRcvd);if(Q!==0)return Q;let Z=$.writeDate(V.timeSent);if(Z!==0)return Z;let J=$.writeVarInt(V.subscription.term);if(J!==0)return J;let W=$.writeVarInt(V.subscription.elapsed);if(W!==0)return W;let Y=$.writeStruct(Q$,V.subscription.stat);if(Y!==0)return Y;let X=$.writeStruct(Q$,V.subscription.dyn);if(X!==0)return X;return 0},decode($){let[V,Q]=$.readBytes(1);if(Q!==0)return M(Q);let Z=V[0],[J,W]=$.readDate();if(W!==0)return M(W);let[Y,X]=$.readDate();if(X!==0)return M(X);let[I,K]=$.readVarInt();if(K!==0)return M(K);let[G,N]=$.readVarInt();if(N!==0)return M(N);let[w,z]=$.readStruct(Q$);if(z!==0)return M(z);let[F,R]=$.readStruct(Q$);if(R!==0)return M(R);return U({status:Z,timeRcvd:J,timeSent:Y,subscription:{term:I,elapsed:G,stat:w,dyn:F}})}};async function t$($,V,Q){let{crypto:Z,enclave:J}=$,W=await J.derive(V,Q);return await Z.deriveEd25519KeyPair(W)}var e$={encode($,V){let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;let Z=$.writeVarInt(V.seq);if(Z!==0)return Z;return 0},decode($){let[V,Q]=$.readVarBytes();if(Q!==0)return M(Q);let[Z,J]=$.readVarInt();if(J!==0)return M(J);return U({headCph:V,seq:Z})}};var Z0={encode($,V){$.writeBytes(V.pubKey),$.writeBytes(V.sig);let Q=$.writeDate(V.timestamp);if(Q!==0)return Q;return 0},decode($){let[V,Q]=$.readBytes(VQ);if(Q!==0)return M(Q);let[Z,J]=$.readBytes(T0);if(J!==0)return M(J);let[W,Y]=$.readDate();if(Y!==0)return M(Y);return U({pubKey:V,sig:Z,timestamp:W})}};var XQ={async encodeReq($,V,Q,Z,J){let W=J.writeStruct(Z0,Q);if(W!==0)return W;for(let Y of Z)J.writeVarInt(Y);return 0},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W}=$,[Y,X]=V.readStruct(Z0);if(X!==0)return X;let I=await A0(Y,J,Z);if(I!==0)return I;let{pubKey:K}=Y,[G,N]=await W.hasUser(K);if(N!==0)return N;if(!G)return 5;let[w,z]=V.readVarInt();if(z!==0)return z;if(!V.done())return 8;let[F,R]=await W.listHeads(K,w);if(R!==0)return R;return Q.writeStructs(e$,F)},decodeResp($){return $.readStructs(e$)}};var $V={encode($,V){$.writeVarInt(V.seq);let Q=$.writeVarBytes(V.bodyCph);if(Q!==0)return Q;return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return M(Q);let[Z,J]=$.readVarBytes();if(J!==0)return M(J);return U({seq:V,bodyCph:Z})}};var IQ={async encodeReq($,V,Q,Z,J){let W=J.writeStruct(Z0,Q);if(W!==0)return W;for(let Y of Z){let X=J.writeVarInt(Y);if(X!==0)return X}return 0},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W}=$,[Y,X]=V.readStruct(Z0);if(X!==0)return X;let I=await A0(Y,J,Z);if(I!==0)return I;let{pubKey:K}=Y,[G,N]=await W.hasUser(K);if(N!==0)return N;if(!G)return 5;let w=[];while(!V.done()){let[R,O]=V.readVarInt();if(O!==0)return O;w.push(R)}console.info(`PULL: ${w.length} bags`);let[z,F]=await W.getBodies(K,w);if(F!==0)return F;if(!z)return 17;for(let{seq:R,bodyCph:O}of z){let H={seq:R,bodyCph:O},P=Q.writeStruct($V,H);if(P!==0)return P}return 0},decodeResp($){return $.readStructs($V)}};var VV={encode($,V){$.writeBytes(V.sig),$.writeBytes(V.kdm);let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;let Z=$.writeVarBytes(V.bodyCph);if(Z!==0)return Z;return 0},decode($){let[V,Q]=$.readBytes(T0);if(Q!==0)return M(Q);let[Z,J]=$.readBytes(D0);if(J!==0)return M(J);let[W,Y]=$.readVarBytes();if(Y!==0)return M(Y);let[X,I]=$.readVarBytes();if(I!==0)return M(I);return U({sig:V,kdm:Z,headCph:W,bodyCph:X})}};var q$={encode($,V){let Q=$.writeVarInt(V.seq);if(Q!==0)return Q;let Z=$.writeVarBytes(V.headCph);if(Z!==0)return Z;let J=V.bodyCph?V.bodyCph.length:0,W=$.writeVarInt(J);if(W!==0)return W;if(J>0){if(!V.bodyCph)return 10;$.writeBytes(V.bodyCph)}return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return M(Q);let[Z,J]=$.readVarBytes();if(J!==0)return M(J);let[W,Y]=$.readVarInt();if(Y!==0)return M(Y);let X;if(W>0){let[I,K]=$.readBytes(W);if(K!==0)return M(K);X=I}return U({seq:V,headCph:Z,bodyCph:X})}};var H$={encode($,V){$.writeBytes(V.sig),$.writeBytes(V.kdm);let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;return 0},decode($){let[V,Q]=$.readBytes(T0);if(Q!==0)return M(Q);let[Z,J]=$.readBytes(D0);if(J!==0)return M(J);let[W,Y]=$.readVarBytes();if(Y!==0)return M(Y);return U({sig:V,kdm:Z,headCph:W})}};var P$={encode($,V){if($.writeVarInt(V.idx),$.writeBytes(new Uint8Array([V.status])),V.status===0)$.writeVarInt(V.seq);return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return M(Q);let[Z,J]=$.readBytes(1);if(J!==0)return M(J);let W=Z[0];if(W!==0)return U({idx:V,status:W});let[Y,X]=$.readVarInt();if(X!==0)return M(X);return U({idx:V,status:W,seq:Y})}};var KQ={async encodeReq($,V,Q,Z,J){let W=J.writeStruct(Z0,Q);if(W!==0)return W;let Y=J.writeStructs(VV,Z);if(Y!==0)return Y;return 0},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W,notifier:Y}=$,[X,I]=V.readStruct(Z0);if(I!==0)return I;let K=await A0(X,J,Z);if(K!==0)return K;let{pubKey:G}=X,[N,w]=await W.hasUser(G);if(w!==0)return w;if(!N)return 5;let[z,F]=V.readStructs(VV);if(F!==0)return F;console.info(`PUSH: ${z.length} bags`);let R=[],O=[];for(let q=0;q<z.length;q++){let A=z[q];if(!await JQ(A,G,J)){let f={idx:q,status:3},E=Q.writeStruct(P$,f);if(E!==0)return E;continue}R.push(q),O.push(A)}let[H,P]=await W.setBags(G,O);if(P!==0)return P;if(!H||H.length!==O.length)return 17;let D=[];for(let q=0;q<O.length;q++){let A=O[q],m=R[q],f=H[q],E=new B,S=E.writeStruct(H$,A);if(S!==0)return S;let k=E.result(),C={seq:f,headCph:k};if(z.length===1&&A.bodyCph.length<=ZQ)C.bodyCph=A.bodyCph;D.push(C);let g={idx:m,status:0,seq:f},i=Q.writeStruct(P$,g);if(i!==0)return i}if(D.length>0){let q=new B,A=q.writeStructs(q$,D);if(A!==0)return A;let m=q.result();await Promise.resolve(Y.push(G,m))}return 0},decodeResp($){return $.readStructs(P$)}};var GQ={async encodeReq($,V,Q,Z,J){return J.writeStruct(Z0,Q)},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W}=$,[Y,X]=V.readStruct(Z0);if(X!==0)return X;let I=await A0(Y,J,Z);if(I!==0)return I;let{pubKey:K}=Y;if(!V.done())return 8;let[G,N]=await W.addUser(K);if(N!==0)return N;return 0},decodeResp($){return U(void 0)}};class QV{url;websocket;constructor($){this.url=$}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 W=new B;W.writeStruct(Z0,$);let Y=W.result(),X=a(Y);return J.searchParams.set("t",X),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=(I)=>{let K=new Uint8Array(I.data);V(K)},this.websocket.onerror=(I)=>{console.log(`ERROR: ${JSON.stringify(I)}`),this.websocket=void 0,Q()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var c={user:{path:"/user",endpoint:GQ,name:0},push:{path:"/push",endpoint:KQ,name:2},peek:{path:"/peek",endpoint:XQ,name:1},pull:{path:"/pull",endpoint:IQ,name:3}},EZ={0:c.user,2:c.push,1:c.peek,3:c.pull},xX={[c.user.path]:c.user,[c.push.path]:c.push,[c.peek.path]:c.peek,[c.pull.path]:c.pull};class ZV{url;listener;constructor($){this.url=$;this.listener=new QV($)}async call($,V){let{path:Q}=EZ[$],Z=new URL(Q,this.url);try{return await xZ(Z,V)}catch{return M(25)}}}var C$=($)=>{return new ZV($.handle)};async function xZ($,V){let Q=await fetch($,{method:"POST",body:V.result().slice()});if(!Q.ok)return M(24);let Z=await x.fromResponse(Q);return U(Z)}class T${enclave;crypto;host;clock;transport;updateHostMeta;constructor($,V,Q,Z,J,W){this.enclave=$;this.crypto=V;this.host=Q;this.clock=Z;this.transport=J;this.updateHostMeta=W}async call($,V){let{clock:Q,crypto:Z,transport:J}=this,{endpoint:W,name:Y}=$,X=await this.keys(),I=Q.now(),[K,G]=await d$(X,I,Z);if(G!==0)return M(G);let N=new B,w=await W.encodeReq(this,X,K,V,N);if(w!==0)return M(w);let z=Q.now(),[F,R]=await J.call(Y,N),O=Q.now();if(R!==0)return M(R);let[H,P]=F.readStruct(s$);if(P!==0)return M(P);if(H.status!==0)return M(H.status);let q={clockOffset:YQ(z,H.timeRcvd,H.timeSent,O),subscription:H.subscription},A=await this.updateHostMeta(q);if(A!==0)return M(A);return W.decodeResp(F)}keys=()=>{let{host:$}=this;return t$(this,$.label,$.idx)};seal=async($)=>{let{crypto:V,enclave:Q}=this,Z=await this.keys();return WQ($,Z,V,Q)};register=()=>this.call(c.user,[]);peek=($)=>this.call(c.peek,[$]);push=($)=>this.call(c.push,$);pull=($)=>this.call(c.pull,$);listen=async($,V,Q)=>{let{clock:Z,crypto:J,host:W,transport:Y}=this,{listener:X}=Y,I=await t$(this,W.label,W.idx),K=Z.now(),[G,N]=await d$(I,K,J);if(N!==0)return N;return await X.connect(G,$,V,Q)};isConnected(){let $=this.transport?.listener;if($&&typeof $.connected==="function")return $.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var JV={encode($,V){let Q=$.writeVarString(V.lbl);if(Q!==0)return Q;let Z=$.writeVarInt(V.idx);if(Z!==0)return Z;let J=$.writeVarInt(V.num);if(J!==0)return J;return $.writeBytes(V.hsh),$.writeBytes(V.sig),0},decode($){let[V,Q]=$.readVarString();if(Q!==0)return M(Q);let[Z,J]=$.readVarInt();if(J!==0)return M(J);let[W,Y]=$.readVarInt();if(Y!==0)return M(Y);let[X,I]=$.readBytes(O$);if(I!==0)return M(I);let[K,G]=$.readBytes(T0);if(G!==0)return M(G);return U({lbl:V,idx:Z,num:W,hsh:X,sig:K})}};var WV={encode($,V){let Q=$.writeStruct(JV,V.head);if(Q!==0)return Q;let Z=$.writeVarBytes(V.indexEnc);if(Z!==0)return Z;let J=$.writeVarBytes(V.bodyEnc);if(J!==0)return J;return 0},decode($){let[V,Q]=$.readStruct(JV);if(Q!==0)return M(Q);let[Z,J]=$.readVarBytes();if(J!==0)return M(J);let[W,Y]=$.readVarBytes();if(Y!==0)return M(Y);return U({head:V,indexEnc:Z,bodyEnc:W})}};var YV={encode($,V){$.writeBytes(V.kdm);let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;let Z=$.writeVarInt(V.lenBody);if(Z!==0)return Z;if(V.lenBody>0&&V.offBody!==void 0){let J=$.writeVarInt(V.offBody);if(J!==0)return J}return 0},decode($){let[V,Q]=$.readBytes(D0);if(Q!==0)return M(Q);let[Z,J]=$.readVarBytes();if(J!==0)return M(J);let[W,Y]=$.readVarInt();if(Y!==0)return M(Y);let X;if(W>0){let[I,K]=$.readVarInt();if(K!==0)return M(K);X=I}return U({kdm:V,headCph:Z,lenBody:W,offBody:X})}};async function MQ($,V,Q,Z,J){let W=await J.derive($,V),Y=await Z.deriveEd25519KeyPair(W),X=new B,I=new B,K=0,G=0;for(let P of Q){let D=new B,q=D.writeStruct(X0,P.head);if(q!==0)return M(q);let A=D.result(),m=await o$(A,Y,Z),f=await J.deriveFromKDM(m),E=await Z.encryptXSalsa20Poly1305Combined(A,f),S=P.body?await Z.encryptXSalsa20Poly1305Combined(P.body,f):new Uint8Array(0),k=P.head.len>0&&P.head.hsh!==void 0?S.length:0,C={kdm:m,headCph:E,lenBody:k,offBody:k>0?G:void 0},g=X.writeStruct(YV,C);if(g!==0)return M(g);if(P.body)I.writeBytes(S),G+=S.length;K++}let N=I.result(),w=X.result(),z=await Z.blake3(w),F=await Z.signEd25519(z,Y.privateKey),R={lbl:$,idx:V,num:K,hsh:z,sig:F},O=new B;O.writeStruct(WV,{head:R,indexEnc:w,bodyEnc:N});let H=O.result();return U(H)}async function NQ($,V,Q){let[Z,J]=WV.decode(new x($));if(J!==0)return M(J);let{head:W,indexEnc:Y,bodyEnc:X}=Z,I=await Q.derive(W.lbl,W.idx),K=await V.deriveEd25519KeyPair(I);if(!await V.checkSigEd25519(W.sig,W.hsh,K.publicKey))return M(3);let N=await V.blake3(Y);if(!s(N,W.hsh))return M(19);let w=new x(Y),z=[];for(let R=0;R<W.num;R++){let[O,H]=w.readStruct(YV);if(H!==0)return M(H);z.push(O)}if(z.length!==W.num)return M(14);let F=[];for(let R of z){let O=await Q.deriveFromKDM(R.kdm),H=await V.decryptXSalsa20Poly1305Combined(R.headCph,O),[P,D]=X0.decode(new x(H));if(D!==0)return M(D);let q;if(R.lenBody>0&&R.offBody!==void 0){if(P.hsh===void 0)return M(14);let A=X.slice(R.offBody,R.offBody+R.lenBody);q=await V.decryptXSalsa20Poly1305Combined(A,O);let m=await V.blake3(q);if(!s(m,P.hsh))return M(19)}F.push({head:P,body:q})}return U(F)}async function wQ({now:$,bod:V,crypto:Q}){let Z=await Q.genRandomBytes(8),J=new B,W=J.writeStruct(r,{id:Z,ts:$});if(W!==0)return M(W);let Y=J.result();return D$({now:$,eid:Y,ctr:0,bod:V,crypto:Q})}async function D$({now:$,eid:V,ctr:Q,bod:Z,crypto:J}){let W=new x(V),[Y,X]=r.decode(W);if(X!==0)return M(X);let I=$.getTime()-Y.ts.getTime(),K,G=Z?.length??0;if(Z&&G>0)K=await J.blake3(Z);return U({eid:V,off:I,ctr:Q,len:G,hsh:K})}var CI=Symbol("EntityID");function RQ($){return"type"in $}var TI=Symbol("MasterSeed"),DI=Symbol("DerivationSeed"),AI=Symbol("PublicKey"),_I=Symbol("PrivateKey"),jI=Symbol("HostSpecificKeyPair"),LI=Symbol("Hash");function fZ($){if(!$)return!1;if(typeof $!=="object")return!1;if("body"in $===!1)return!1;if("type"in $===!1)return!1;return!0}function BZ($){if(!$.bod||$.bod.length===0){let Z={off:$.off,ctr:$.ctr,eid:$.eid};return U(Z)}let V=c$($.bod);if(fZ(V)===!1)return console.warn("msg body invalid",V),M(14);let Q={off:$.off,ctr:$.ctr,eid:$.eid,gid:V.gid,pid:V.pid,type:V.type,body:V.body};return U(Q)}class Z${applier;emitter=new C0;clearer;onDirtyEids;cacheDriven;peerIngest;constructor($,V,Q,Z){this.applier=$;this.clearer=V,this.onDirtyEids=Q,this.cacheDriven=Z?.cacheDriven??!1,this.peerIngest=Z?.peerIngest}apply=async($)=>{let V=[],Q=[];for(let X of $){let[I,K]=BZ(X);if(Q.push(K),K!==0)continue;V.push(I)}let{stats:Z,types:J,eids:W}=await this.applier(V),Y=[];for(let X=0;X<$.length;X++){let I=Q[X],K=Z[X];if(I!==0){Y.push(I);continue}if(K!==0){Y.push(K);continue}Y.push(0)}if(!this.cacheDriven)for(let X of J)this.emitter.emit(X,null);if(W.length>0)this.onDirtyEids?.(W);return Y};clear=async()=>{let $=await this.clearer();if($!==0)return $;return this.emitter.emitAll(null),$};notify=($)=>{for(let V of $)this.emitter.emit(V,null)};refresh=async($)=>{if(this.peerIngest){await this.peerIngest($);return}};on=($,V)=>{this.emitter.addEventListener($,V)};off=($,V)=>{this.emitter.removeEventListener($,V)}}var XV={apply:async function($){return $.map(()=>0)},clear:async function(){return 0},notify:function($){},refresh:async function($){},on:function($,V){},off:function($,V){}};var y="entities",A$="entity_type_created_at",IV="entity_type_updated_at",KV="entity_type_group_id",GV="entity_type_parent_id";function kZ($){let V={bod:$.body,crd:$.createdAt,...$.ctr!==0?{ctr:$.ctr}:{},eid:L($.eid),gid:$.gid,pid:$.pid?L($.pid):void 0,typ:$.type,upd:$.updatedAt};if(V.gid===void 0)delete V.gid;if(V.pid===void 0)delete V.pid;if(V.ctr===void 0)delete V.ctr;return V}function l0($){return{body:$.bod,createdAt:$.crd,updatedAt:$.upd,ctr:$.ctr??0,type:$.typ,eid:I0($.eid),gid:$.gid,pid:$.pid?I0($.pid):void 0}}class MV{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(y))Z.createObjectStore(y,{keyPath:"eid",autoIncrement:!1});let W=J.objectStore(y);if(!W.indexNames.contains(A$))W.createIndex(A$,["typ","crd"],{unique:!1});if(!W.indexNames.contains(IV))W.createIndex(IV,["typ","upd"],{unique:!1});if(!W.indexNames.contains(KV))W.createIndex(KV,["typ","gid"],{unique:!1});if(!W.indexNames.contains(GV))W.createIndex(GV,["typ","pid"],{unique:!1})},Q.onsuccess=()=>$(Q.result),Q.onerror=()=>V(Q.error)})}apply=async($)=>{let V=new Set,Q=[];if(!this.db)return{stats:$.map(()=>16),types:V,eids:Q};let Z=this.db.transaction(y,"readwrite"),J=Z.objectStore(y);return new Promise((W)=>{let Y=Array($.length).fill(0);if($.length<1){W({stats:[],types:V,eids:Q});return}Z.oncomplete=()=>{W({stats:Y,types:V,eids:Q})},Z.onerror=()=>{for(let I=0;I<Y.length;I++)if(Y[I]===void 0)Y[I]=18;W({stats:Y,types:V,eids:Q})};let X=new Map;for(let I=0;I<$.length;I++){let K=$[I],G=L(K.eid),N={op:K,index:I},w=X.get(G);if(w)w.push(N);else X.set(G,[N])}for(let[I,K]of X){if(K.length<1)continue;let G=J.get(I);G.onsuccess=()=>{let N=G.result,w=N?l0(N):void 0,z=!1;for(let{op:F,index:R}of K){let[O,H]=r0(w,F);if(H!==0){Y[R]=H;continue}if(z=!0,O)V.add(O.type);else if(w)V.add(w.type);w=O}if(z)Q.push(K[0].op.eid);if(w){let F=kZ(w),R=J.put(F);R.onerror=(O)=>{O.preventDefault();for(let{index:H}of K)Y[H]=18}}else{let F=J.delete(I);F.onerror=()=>{for(let{index:R}of K)Y[R]=18}}},G.onerror=()=>{for(let{index:N}of K)Y[N]=18}}})};async clear(){if(!this.db)return 16;let $=this.db.transaction(y,"readwrite"),V=$.objectStore(y);return new Promise((Q)=>{$.oncomplete=()=>Q(0),$.onerror=()=>Q(18),V.clear()})}async getEnt($){if(!this.db)return M(16);let V=L($),Z=this.db.transaction(y,"readonly").objectStore(y);return new Promise((J)=>{let W=Z.get(V);W.onsuccess=()=>{let Y=W.result;if(!Y)J(U(void 0));else{let X=l0(Y);J(U(X))}},W.onerror=()=>J(M(18))})}async getAllOfTypeUpdatedBetween($,V,Q){if(!this.db)return M(16);let J=this.db.transaction(y,"readonly").objectStore(y).index(IV);return new Promise((W)=>{let Y=J.getAll(IDBKeyRange.bound([$,V],[$,Q]));Y.onsuccess=()=>{let X=Y.result;W(U(X.map(l0)))},Y.onerror=()=>W(M(18))})}async getGroupMembers($,V){if(!this.db)return M(16);let Z=this.db.transaction(y,"readonly").objectStore(y).index(KV);return new Promise((J)=>{let W=Z.getAll(IDBKeyRange.only([$,V]));W.onsuccess=()=>{let Y=W.result;J(U(Y.map(l0)))},W.onerror=()=>J(M(18))})}async getAllOfType($){if(!this.db)return M(16);let Q=this.db.transaction(y,"readonly").objectStore(y).index(A$);return new Promise((Z)=>{let J=Q.getAll(IDBKeyRange.bound([$],[$,[]]));J.onsuccess=()=>{let W=J.result;Z(U(W.map(l0)))},J.onerror=()=>Z(M(18))})}async getAllEntities($){if(!this.db)return M(16);if("pid"in $){let V=L($.pid),Z=this.db.transaction(y,"readonly").objectStore(y).index(GV);return new Promise((J)=>{let W=Z.getAll(IDBKeyRange.only([$.type,V]));W.onsuccess=()=>{let X=W.result.map(l0);J(U(X))},W.onerror=()=>J(M(18))})}else if("gid"in $)return await this.getGroupMembers($.type,$.gid);else if("updatedBetween"in $)return await this.getAllOfTypeUpdatedBetween($.type,$.updatedBetween.start,$.updatedBetween.end);return await this.getAllOfType($.type)}async getEntities($){let[V,Q]=await this.getAllEntities($);if(Q!==0)return M(Q);return U(V)}async countEntities({type:$}){if(!this.db)return M(16);let Q=this.db.transaction(y,"readonly").objectStore(y).index(A$);return new Promise((Z)=>{let J=IDBKeyRange.bound([$],[$,[]]),W=Q.count(J);W.onsuccess=()=>Z(U(W.result)),W.onerror=()=>Z(M(18))})}}async function zQ(){let $=new MV;return await $.init(),$}class _${ents=new Map;useIndex;byType=new Map;byTypePid=new Map;byTypeGid=new Map;constructor($=[],V){this.useIndex=V?.indexes!==!1;for(let Q of $)this.put(Q)}put($){let V=L($.eid),Q=this.ents.get(V);if(Q)this.unindex(V,Q);this.ents.set(V,$),this.index(V,$)}del($){let V=this.ents.get($);if(!V)return;this.unindex($,V),this.ents.delete($)}index($,V){if(!this.useIndex)return;let Q=this.byType.get(V.type);if(!Q)Q=new Map,this.byType.set(V.type,Q);if(Q.set($,V),V.pid){let Z=L(V.pid),J=this.byTypePid.get(V.type);if(!J)J=new Map,this.byTypePid.set(V.type,J);let W=J.get(Z);if(!W)W=new Map,J.set(Z,W);W.set($,V)}if(typeof V.gid==="string"){let Z=this.byTypeGid.get(V.type);if(!Z)Z=new Map,this.byTypeGid.set(V.type,Z);let J=Z.get(V.gid);if(!J)J=new Map,Z.set(V.gid,J);J.set($,V)}}unindex($,V){if(!this.useIndex)return;let Q=this.byType.get(V.type);if(Q){if(Q.delete($),Q.size===0)this.byType.delete(V.type)}if(V.pid){let Z=L(V.pid),J=this.byTypePid.get(V.type),W=J?.get(Z);if(W){if(W.delete($),W.size===0)J?.delete(Z)}if(J&&J.size===0)this.byTypePid.delete(V.type)}if(typeof V.gid==="string"){let Z=this.byTypeGid.get(V.type),J=Z?.get(V.gid);if(J){if(J.delete($),J.size===0)Z?.delete(V.gid)}if(Z&&Z.size===0)this.byTypeGid.delete(V.type)}}clearIndexes(){this.byType.clear(),this.byTypePid.clear(),this.byTypeGid.clear()}bucketList($){if(!$||$.size===0)return[];let V=[];for(let Q of $.values())V.push(Q);return V}async apply($){let V=new Set,Q=[],Z=[];for(let J of $){let W=L(J.eid),Y=this.ents.get(W),[X,I]=r0(Y,J);if(I!==0){Z.push(I);continue}if(X)V.add(X.type);else if(Y)V.add(Y.type);if(X)this.put(X);else this.del(W);Q.push(J.eid),Z.push(0)}return{stats:Z,types:V,eids:Q}}async clear(){return this.ents.clear(),this.clearIndexes(),0}async getEnt($){let V=L($),Q=this.ents.get(V);return U(Q)}async getAllEntities({type:$,gid:V,pid:Q,updatedBetween:Z}){if(this.useIndex){if(Q!==void 0){let W=L(Q);return U(this.bucketList(this.byTypePid.get($)?.get(W)))}if(V!==void 0)return U(this.bucketList(this.byTypeGid.get($)?.get(V)));if(Z!==void 0){let W=[],Y=this.byType.get($);if(Y){for(let X of Y.values())if(X.updatedAt>=Z.start&&X.updatedAt<=Z.end)W.push(X)}return U(W)}return U(this.bucketList(this.byType.get($)))}let J=[];if(Q!==void 0){for(let W of this.ents.values())if(W.type===$&&W.pid&&s(W.pid,Q))J.push(W)}else if(V!==void 0){for(let W of this.ents.values())if(W.type===$&&(typeof W.gid==="string"&&W.gid===V))J.push(W)}else if(Z!==void 0){for(let W of this.ents.values())if(W.type===$&&W.updatedAt>=Z.start&&W.updatedAt<=Z.end)J.push(W)}else for(let W of this.ents.values())if(W.type===$)J.push(W);return U(J)}async getEntities($){let[V,Q]=await this.getAllEntities($);if(Q!==0)return M(Q);return U(V)}async countEntities({type:$}){if(this.useIndex)return U(this.byType.get($)?.size??0);let V=0;for(let Q of this.ents.values())if(Q.type===$)V+=1;return U(V)}}async function NV($){let V=await zQ();if($?.cache===!1)return V;return new J$(V,void 0,{indexes:$?.indexes})}class J${mem;durable;warmed=new Set;listeners=new Set;chain=Promise.resolve();constructor($,V,Q){if(this.durable=$,this.mem=new _$(V??[],{indexes:Q?.indexes}),V)for(let Z of V)this.warmed.add(Z.type)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}emit($){if($.size<1)return;for(let V of this.listeners)V($)}run($){let V=this.chain.then($,$);return this.chain=V.then(()=>{return},()=>{return}),V}apply($){return this.run(async()=>{let V=yZ(this.mem,$);this.emit(V.types);let Q=await this.durable.apply($),{changed:Z,status:J}=await this.pullEids($.map((W)=>W.eid));this.emit(Z);for(let W of Q.types)this.warmed.add(W);if(J!==0)return{stats:$.map(()=>J),types:Q.types,eids:Q.eids};return Q})}clear(){return this.run(async()=>{let $=await this.durable.clear();if($!==0)return $;let V=this.mem.ents.size>0;return await this.mem.clear(),this.warmed.clear(),0})}ingestFromDurable($){return this.run(async()=>{let{changed:V,status:Q}=await this.pullEids($);return this.emit(V),Q})}async pullEids($){let V=new Set,Q=new Set;for(let Z of $){let J=L(Z);if(Q.has(J))continue;Q.add(J);let W=this.mem.ents.get(J),[Y,X]=await this.durable.getEnt(Z);if(X!==0)return{changed:V,status:X};if(Y){if(this.mem.put(Y),this.warmed.add(Y.type),!W||!gZ(W,Y)){if(V.add(Y.type),W&&W.type!==Y.type)V.add(W.type)}}else if(W)this.mem.del(J),V.add(W.type)}return{changed:V,status:0}}async warmType($){if(this.warmed.has($))return 0;let[V,Q]=await this.durable.getEntities({type:$});if(Q!==0)return Q;if(V)for(let Z of V){let J=L(Z.eid),W=this.mem.ents.get(J);if(!W||uZ(Z,W))this.mem.put(Z)}return this.warmed.add($),0}async getEnt($){let V=L($);if(this.mem.ents.has(V))return this.mem.getEnt($);return this.run(async()=>{if(this.mem.ents.has(V))return this.mem.getEnt($);let[Q,Z]=await this.durable.getEnt($);if(Z!==0)return M(Z);if(Q)this.mem.put(Q),this.warmed.add(Q.type);return U(Q)})}async getEntities($){let V=await this.run(()=>this.warmType($.type));if(V!==0)return M(V);return this.mem.getEntities($)}async countEntities({type:$}){let V=await this.run(()=>this.warmType($));if(V!==0)return M(V);return this.mem.countEntities({type:$})}}function gZ($,V){if($.ctr!==V.ctr)return!1;if($.updatedAt.getTime()!==V.updatedAt.getTime())return!1;if($.createdAt.getTime()!==V.createdAt.getTime())return!1;if($.type!==V.type)return!1;if($.gid!==V.gid)return!1;if(!s($.eid,V.eid))return!1;if(!vZ($.pid,V.pid))return!1;return iZ($.body,V.body)}function vZ($,V){if($===void 0&&V===void 0)return!0;if($===void 0||V===void 0)return!1;return s($,V)}function iZ($,V){if(Object.is($,V))return!0;if($ instanceof Uint8Array&&V instanceof Uint8Array)return s($,V);if($ instanceof Date&&V instanceof Date)return $.getTime()===V.getTime();try{return s(m0($),m0(V))}catch{return!1}}function uZ($,V){let Q=$.updatedAt.getTime(),Z=V.updatedAt.getTime();if(Q!==Z)return Q>Z;return $.ctr>V.ctr}function yZ($,V){let Q=new Set,Z=[];for(let J of V){let W=L(J.eid),Y=$.ents.get(W),[X,I]=r0(Y,J);if(I!==0){Z.push(I);continue}if(X)Q.add(X.type);else if(Y)Q.add(Y.type);if(X)$.put(X);else $.del(W);Z.push(0)}return{stats:Z,types:Q}}function j$($){if($ instanceof J$){let V=new Z$((Q)=>$.apply(Q),()=>$.clear(),void 0,{cacheDriven:!0,peerIngest:async(Q)=>{await $.ingestFromDurable(Q)}});return $.subscribe((Q)=>V.notify(Q)),V}return new Z$((V)=>$.apply(V),()=>$.clear())}function bZ($){return{eid:$.eid,ctr:$.ctr,updatedAt:$.updatedAt}}function wV($){let V=new x($.eid),[Q,Z]=V.readStruct(r);if(Z!==0)return M(Z);return U({eid:$.eid,ctr:$.ctr,updatedAt:new Date(Q.ts.getTime()+$.off)})}function r0($,V){let Q=new x(V.eid),[Z,J]=Q.readStruct(r);if(J!==0)return M(J);let W=new Date(Z.ts.getTime()+V.off);if($!==void 0&&W<=$.updatedAt)return M(15);if(RQ(V))return U({eid:V.eid,gid:V.gid,pid:V.pid,type:V.type,createdAt:Z.ts,updatedAt:W,ctr:V.ctr,body:V.body});else return U(void 0)}var nZ={getEnt:async()=>M(21),getEntities:async($)=>M(21),countEntities:async()=>M(21),apply:async($)=>({stats:$.map(()=>21),types:new Set,eids:[]}),clear:async()=>21};class L${inflight=null;again=!1;run($){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain($),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain($){try{this.again=!1;let V=await $();while(this.again)this.again=!1,V=await $();return V}finally{this.inflight=null}}}var m$=100;class W${timer=null;delayMs;work;tail=new L$;constructor($,V){this.delayMs=$<0?0:$,this.work=V}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($){let V=new x($.eid),[Q,Z]=r.decode(V);if(Z!==0)return;return Q.ts.getTime()+$.off}function pZ($,V){let Q=FQ($),Z=FQ(V);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 V.ctr-$.ctr}function Y$($,V){return $.slice().sort((Q,Z)=>pZ(V(Q),V(Z)))}var S0={phase:"idle"},X$=50;function RV($,V,Q){if($<=0||V<=0)return!1;if($===1||$===V)return!0;return $%Q===0}function S$($,V){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob($,V);return}let Q=URL.createObjectURL($),Z=document.createElement("a");Z.href=Q,Z.download=V,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(Q)}function UQ($,V,Q){let Z=[],J=[],W=0;for(let Y of $){let X=V(Y);if(J.length>0&&W+X>Q)Z.push(J),J=[],W=0;if(J.push(Y),W+=X,W>=Q)Z.push(J),J=[],W=0}if(J.length>0)Z.push(J);return Z}async function OQ($,V,Q){let Z=$.length;if(Z<1)return[];let J=Array(Z),W=0,Y=Math.min(Math.max(1,V),Z),X=async()=>{while(!0){let K=W;if(W+=1,K>=Z)return;J[K]=await Q($[K],K)}},I=[];for(let K=0;K<Y;K++)I.push(X());return await Promise.all(I),J}async function zV($,V,Q,Z){let J=new x($.headCph),[W,Y]=J.readStruct(H$);if(Y!==0)return M(Y);let{sig:X,kdm:I,headCph:K}=W;if(!await Z.checkSigEd25519(X,K,V.publicKey))return M(3);let N=await Q.deriveFromKDM(I),w;try{w=await Z.decryptXSalsa20Poly1305Combined(K,N)}catch{return M(20)}return U({kdm:I,headEnc:w})}var z0="f",j0="t",G0="e";function hZ($){return $===z0||$===j0||$===G0}function I$($){if($===!0||$===j0)return j0;if($===G0)return G0;return z0}function lZ($){return I$($.apld)===z0}function FV($){return $!==0&&$!==15&&$!==18&&$!==17}function E0($,V,Q){if($.apld=V,V===G0&&Q!==void 0)$.err=Q;else delete $.err}async function L0($,V,Q){let Z=I$(V.apld),J=V.body,W=J?.length??0,Y;if(J&&W>0)Y=await Q.blake3(J);let X={eid:V.eid,off:V.off??0,ctr:V.ctr??0,len:W,hsh:Y},I={hash:$,head:X,apld:Z};if(J!==void 0)I.body=J;if(Z===G0&&V.err!==void 0)I.err=V.err;return I}var UV=1048576,OV=1048576,rZ=64;function cZ($){return $.sig.length+$.kdm.length+$.headCph.length+$.bodyCph.length}async function dZ($,V,Q,Z,J){if(Z.length<1)return 0;let[W,Y]=await $.push(Z);if(Y!==0)return Y;if(!W)return 27;for(let I of W){if(I.status!==0){console.error("push err",I);continue}let K=J[I.idx];if(!K){console.error("no hash",I);continue}await V.uploads.deq(Q,[K])}let X=await V.hosts.get(Q);if(X){let I=X.lastSeq,K=I,G=[];for(let N of W)if(N.status===0)G.push(N.seq);G.sort((N,w)=>N-w);for(let N of G)if(N===I+1)I=N;if(I>K)await V.hosts.touch(Q,I)}return 0}async function qQ($,V){if(V.length<1)return U([]);let Q=new Map,Z=[];for(let X of V)Q.set(X.seq,X),Z.push(X.seq);let[J,W]=await $.pull(Z);if(W!==0)return M(W);if(!J)return M(27);let Y=[];for(let{seq:X,bodyCph:I}of J){let K=Q.get(X);if(!K)continue;Y.push({dl:K,bodyCph:I})}return U(Y)}async function oZ($,V,Q,Z){if(Z.length<1)return U({parts:[],hashes:[]});let J=[],W=[],Y=[],X=new Map;for(let{dl:K,bodyCph:G}of Z){let{head:N,kdm:w,seq:z,host:F}=K,[R,O]=await HQ(K,Q);if(O!==0||!R){let S=X.get(F)??[];S.push(z),X.set(F,S);continue}let{headEnc:H,headEncHash:P}=R,D=await V.deriveFromKDM(w),[q,A]=await a$(H,G,D,Q,P);if(A!==0||!q){let S=X.get(F)??[];S.push(z),X.set(F,S);continue}let m={head:N,body:q.bod},f=q.headHash;Y.push({key:f,data:AQ(m)}),J.push(m),W.push(f);let E=X.get(F)??[];E.push(z),X.set(F,E)}let I=await $.messages.add(Y);for(let[K,G]of X)await $.downloads.deq(K,G);for(let K=0;K<I.length;K++){let G=I[K];if(G!==0&&G!==15)console.error("ERR storing",_[G],"for message",K)}return U({parts:J,hashes:W})}async function HQ($,V){let Q=$.headEnc;if(!Q){let J=new B,W=J.writeStruct(X0,$.head);if(W!==0)return M(W);Q=J.result()}if($.headEncHash)return U({headEnc:Q,headEncHash:$.headEncHash});let Z=await V.blake3(Q);return U({headEnc:Q,headEncHash:Z})}async function PQ($,V,Q){let Z=new Set;for(let Y of V)Z.add(L(Y));if(Z.size<1)return;let J=Array.from(await $.downloads.list());if(J.length<1)return;let W=new Map;for(let Y of J){let X;if(Y.headEncHash)X=L(Y.headEncHash);else{let[K,G]=await HQ(Y,Q);if(G!==0||!K)continue;X=L(K.headEncHash)}if(!Z.has(X))continue;let I=W.get(Y.host)??[];I.push(Y.seq),W.set(Y.host,I)}for(let[Y,X]of W)await $.downloads.deq(Y,X)}async function CQ({conn:$,store:V,enclave:Q,host:Z,crypto:J,onProgress:W,peekProgressEvery:Y,peekConcurrency:X}){let I=await $.keys(),K=[],[G,N]=await $.peek(Z.lastSeq);if(N!==0)return N;let w=G.length,z=Y??X$,F=X??rZ;if(W&&w>0)W({phase:"peek",host:Z.label,done:0,total:w});let R=0,O=await OQ(G,F,async(H)=>{let[P,D]=await zV(H,I,Q,J),q;if(D!==0||!P)q={ok:!1,seq:H.seq,stat:D};else{let A=await J.blake3(P.headEnc);q={ok:!0,seq:H.seq,kdm:P.kdm,headEnc:P.headEnc,headEncHash:A}}if(R+=1,W&&RV(R,w,z))W({phase:"peek",host:Z.label,done:R,total:w});return q});for(let H of O){if(!H.ok){console.error("peek: decrypting item head",H.stat);continue}if(await V.messages.has(H.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await V.uploads.deq(Z.label,[H.headEncHash]),await V.downloads.deq(Z.label,[H.seq]);continue}let D=new x(H.headEnc),[q,A]=D.readStruct(X0);if(A!==0){console.error("peek: reading item head",A);continue}K.push({kdm:H.kdm,head:q,seq:H.seq,host:Z.label,headEnc:H.headEnc,headEncHash:H.headEncHash})}if(await V.downloads.enq(K),G.length>0){let H=Math.max(...G.map((P)=>P.seq));await V.hosts.touch(Z.label,H)}if(W)W({phase:"peek",host:Z.label,done:w,total:w});return 0}async function TQ({conn:$,store:V,host:Q,maxPushBytes:Z,onProgress:J}){let W=Z??UV,Y=await V.uploads.list(Q.label),X=Y.length,I=0;if(J&&X>0)J({phase:"push",host:Q.label,done:0,total:X});let K=[],G=[],N=0,w=async()=>{if(K.length<1)return 0;let z=K.length,F=await dZ($,V,Q.label,K,G);if(K=[],G=[],N=0,F===0){if(I+=z,J)J({phase:"push",host:Q.label,done:I,total:X})}return F};for(let z of Y){let F=await V.messages.get(z);if(!F){I+=1;continue}let R={...F.head,bod:F.body},[O,H]=await $.seal(R);if(H!==0)return H;if(!O)return 12;let P=cZ(O);if(K.length>0&&N+P>W){let D=await w();if(D!==0)return D}if(K.push(O),G.push(z),N+=P,N>=W){let D=await w();if(D!==0)return D}}return w()}async function DQ({conn:$,store:V,enclave:Q,host:Z,crypto:J,maxPullBytes:W,onProgress:Y},X){let I=W??OV,K=await V.downloads.list(),G=Array.from(K).filter((O)=>O.host===Z.label);if(G.length<1)return 15;let N=Y$(G,(O)=>O.head),w=UQ(N,(O)=>O.head.len,I),z=N.length,F=0;if(Y)Y({phase:"pull",host:Z.label,done:0,total:z});let R=qQ($,w[0]);for(let O=0;O<w.length;O++){let[H,P]=await R;if(P!==0||!H)return P;if(F+=w[O].length,Y)Y({phase:"pull",host:Z.label,done:F,total:z});let D=w[O+1];if(D)R=qQ($,D);if(Y)Y({phase:"open",host:Z.label,done:F,total:z});let q=Y$(H,(m)=>m.dl.head),[,A]=await oZ(V,Q,J,q);if(A!==0)return A;if(X){if(Y)Y({phase:"exec",host:Z.label,done:F,total:z});await X()}}return 0}function AQ({head:$,body:V}){let Q={eid:$.eid,body:V,apld:z0};if($.off!==0)Q.off=$.off;if($.ctr!==0)Q.ctr=$.ctr;return Q}async function _Q($,{conn:V,store:Q,enclave:Z,host:J,crypto:W,onProgress:Y},X){let I=J.label,K=await V.keys(),G=new x($),[N,w]=G.readStructs(q$);if(w!==0){console.error("Failed decoding notif",_[w]);return}let z=!1,R=(await Q.hosts.get(I))?.lastSeq,O=[],H=!1;for(let q of N){let[A,m]=await zV({seq:q.seq,headCph:q.headCph},K,Z,W);if(m!==0){console.error("Failed decrypting notif",_[m]);continue}let f=await W.blake3(A.headEnc);if(await Q.messages.has(f))continue;let E=new x(A.headEnc),[S,k]=E.readStruct(X0);if(k!==0){console.error("Failed to parse head",_[k]);continue}if(!q.bodyCph&&S.len>0)H=!0,await Q.downloads.enq([{seq:q.seq,host:I,kdm:A.kdm,head:S,headEnc:A.headEnc,headEncHash:f}]);else O.push({...A,head:S,bodyCph:q.bodyCph,headEncHash:f});if(R===void 0||q.seq!==R+1)console.log("out of seq",q.seq,R),z=!0;else R=q.seq}if(R!==void 0)await Q.hosts.touch(J.label,R);let P=[];for(let q of O){let A=await Z.deriveFromKDM(q.kdm),[m,f]=await a$(q.headEnc,q.bodyCph,A,W);if(f!==0){console.error("Failed to open body",_[f]);continue}P.push({key:q.headEncHash,data:AQ({head:q.head,body:m.bod})})}let D=await Q.messages.add(P);for(let q=0;q<D.length;q++){let A=D[q];if(A!==0&&A!==15)console.error("ERR storing",_[A],"for message",q)}if(Y&&P.length>0)Y({phase:"open",host:J.label,done:P.length,total:P.length});if(z||H||P.length>0)X()}class x0{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new L$;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=X$;lastProgress=S0;scheduledSync;constructor($,V,Q,Z,J,W=!0,Y=UV,X=OV,I){this.clock=$;this.state=V;this.store=Q;this.transport=Z;this.crypto=J;this.forceSkewHandlingByDefault=W;this.onScheduleSync=I;this.maxPushBytes=Y,this.maxPullBytes=X,this.clientState=new K0(()=>this.getClientState()),this.xferState=new K0(()=>this.getXferState()),this.scheduledSync=new W$(m$,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(K){console.error("Debounced sync failed:",K)}})}emitProgress=($)=>{this.lastProgress=$,this.xferState.emit()};async setSeed($){await this.store.seed.save($),this.clientState.emit()}async getClientState(){let{store:$,connections:V}=this,Q=await $.seed.load(),Z=await $.hosts.list(),J=!1;for(let W of V.values())if(W.isConnected()){J=!0;break}return{hasSeed:Q!==void 0,hasHost:Array.from(Z).length>0,connected:J}}async getXferState(){let{uploads:$,downloads:V}=this.store,Q=await $.count();return{numDownloads:await V.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:W,body:Y}of $){let X=new B;X.writeStruct(X0,W);let I=X.result(),K=await this.crypto.blake3(I),G={eid:W.eid,body:Y,apld:z0};if(W.off!==0)G.off=W.off;if(W.ctr!==0)G.ctr=W.ctr;Q.push(K),Z.push({key:K,data:G})}await this.store.messages.add(Z),await PQ(this.store,Q,this.crypto);let J=await this.doApplyHashes(Q);if(V.enqueueUpload){let W=[];for(let Y=0;Y<Q.length;Y++){let X=J[Y];if(X===0||X===15)W.push(Q[Y])}if(W.length>0){let Y=await this.store.hosts.list();for(let X of Y)await this.store.uploads.enq(X.label,W);this.xferState.emit()}}if(V.triggerUpload)this.scheduleSync();return J}enqueueApplyJob($){let V=this.applyChain.then($,$);return this.applyChain=V.then(()=>{return},()=>{return}),V}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let $=await this.store.messages.list(z0);if($.length<1)return[];let V=Y$($,(Q)=>Q.head);return this.applyStored(V)}applyHashes=($)=>{return this.enqueueApplyJob(()=>this.doApplyHashes($))};async doApplyHashes($){let V=[];for(let J of $){let W=await this.store.messages.get(J);if(W)V.push(W)}let Q=await this.applyStored(V),Z=new Map;for(let J=0;J<V.length;J++)Z.set(L(V[J].hash),Q[J]??12);return $.map((J)=>Z.get(L(J))??13)}async applyStored($){if($.length<1)return[];let V=$.map((W)=>({...W.head,bod:W.body})),Q=await this.state.apply(V),Z=[],J=[];for(let W=0;W<$.length;W++){let Y=Q[W];if(Y===0||Y===15)Z.push($[W].hash);else if(Y!==void 0&&FV(Y))J.push({key:$[W].hash,err:Y})}if(Z.length>0)await this.store.messages.markApplied(Z);if(J.length>0)await this.store.messages.markFailed(J);return Q}async insertRaw($){let{clock:V,crypto:Q}=this,[Z,J]=await wQ({now:V.now(),bod:$,crypto:Q});if(J!==0)return M(J);let Y=(await this.apply([{head:Z,body:$}]))[0];if(Y!==0&&Y!==15)return M(Y??12);return U(Z)}async makeUpdate($,V){let{clock:Q,crypto:Z}=this,J=Q.now();if($.updatedAt.getTime()>J.getTime())return M(4);let W=$.ctr+1,[Y,X]=await D$({now:J,eid:$.eid,ctr:W,bod:V,crypto:Z});if(X!==0)return M(X);return U({head:Y,body:V})}async updateWithSkew($,V,Q){if(Q===!1)return M(4);let{clock:Z,crypto:J}=this,W=Z.now(),Y=new x($.eid),[X,I]=Y.readStruct(r);if(I!==0)return M(I);let K=$.updatedAt.getTime()-X.ts.getTime(),G={eid:$.eid,off:K+1,ctr:$.ctr+1,len:0},w=(await this.apply([{head:G,body:void 0}]))[0];if(w!==0&&w!==15)return M(w??12);if(V===void 0)return U(G);let[z,F]=h0({id:X.id,ts:W});if(F!==0)return M(F);let[R,O]=await D$({now:W,eid:z,ctr:0,bod:V,crypto:J});if(O!==0)return M(O);let P=(await this.apply([{head:R,body:V}]))[0];if(P!==0&&P!==15)return M(P??12);return U(R)}async updateRaw($,V,Q=this.forceSkewHandlingByDefault){if($.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 Y=(await this.doApply([Z]))[0];if(Y!==0&&Y!==15)return M(Y??12);return U(Z.head)})}async insert($){let{body:V,type:Q,gid:Z,pid:J}=$,Y=m0({body:V,type:Q,gid:Z,pid:J});return this.insertRaw(Y)}async update($){let{prior:V,body:Q,type:Z,gid:J,pid:W,force:Y}=$,I=m0({body:Q,type:Z,gid:J,pid:W});return this.updateRaw(V,I,Y??this.forceSkewHandlingByDefault)}async delete($){let V=$.force??!0;if("prior"in $)return this.updateRaw($.prior,void 0,V);let[Q,Z]=await this.revFromArchive($.eid);if(Z!==0)return M(Z);return this.updateRaw(Q,void 0,V)}async revFromArchive($){let V=await this.store.messages.last($);if(V)return wV(V.head);let Q=new x($),[Z,J]=Q.readStruct(r);if(J!==0)return M(J);return U({eid:$,ctr:-1,updatedAt:Z.ts})}async genEID($){let{clock:V,crypto:Q}=this,Z=V.now();if($!==void 0)return h0({id:$,ts:Z});let J=await Q.genRandomBytes(8);return h0({id:J,ts:Z})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:$,crypto:V,store:Q}=this,Z=await Q.seed.load();if(!Z)return 22;await this.drainApplyQueue();for(let[J,W]of $){let Y=await Q.hosts.get(J);if(!Y)continue;let X={conn:W,store:Q,enclave:Z,host:Y,crypto:V,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},I=await CQ(X);if(I!==0)return console.error(`Failed to peek: ${I}`),I;this.xferState.emit();let K=await TQ(X);if(K!==0)return console.error(`Failed to push: ${K}`),K;this.xferState.emit();let G=await DQ(X,async()=>{await this.drainApplyQueue()});if(G!==0&&G!==15)return console.error(`Failed to pull: ${G}`),G;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=S0,this.clientState.emit(),this.xferState.emit()}import=async($,V)=>{let{crypto:Q,store:Z}=this,J=V?.onProgress,W=await Z.seed.load();if(!W)return 22;console.time("import: decoding file...");let Y=await $.bytes(),[X,I]=await NQ(Y,Q,W);if(I!==0)return I;console.timeEnd("import: decoding file...");let K=0;while(K<X.length){let G=0,N=0,w=K;for(let R=K;R<X.length&&N<100&&G<102400;R++)G+=X[R].head.len,N++,w=R+1;let z=X.slice(K,w);console.time(`import: applying [${K}, ${w}]`);let F=await this.apply(z,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${K}, ${w}]`);for(let R=0;R<z.length;R++){let O=F[R];if(O!==0&&O!==15)console.warn(`failed to import msg ${K+R}: ${_[O]}`)}if(J)queueMicrotask(()=>J(w,X.length,0));this.emitProgress({phase:"import",done:w,total:X.length}),K=w}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:$,store:V}=this,Q=await V.seed.load();if(!Q)return M(22);let Z=await V.messages.list();return MQ("export",0,Z,$,Q)}async export($){let[V,Q]=await this.exportBytes();if(Q!==0)return Q;if(!V)return 12;let Z=new Blob([V.slice()]);return S$(Z,$),0}async link($,V=!0){if(await this.store.hosts.add($),this.clientState.emit(),V){let Q=await this.store.hosts.get($.label);if(Q)await this.connectToHost(Q)}}async unlink($){await this.store.hosts.del($),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:W,store:Y,transport:X}=this,I=J.get($.label);if(I){if(I.isConnected())return;try{I.closeListener()}catch{}J.delete($.label)}let K=await Y.seed.load();if(!K)return;console.info(`Connecting to ${$.handle} (${$.label})`);let G=new T$(K,W,$,Z,X($),(N)=>Y.hosts.set($.label,N));if(await G.register(),V)await G.listen(async(N)=>{let w={conn:G,store:Y,enclave:K,host:$,crypto:W,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return _Q(N,w,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(J.set($.label,G),this.clientState.emit(),Q)this.scheduleSync()};async connect($=!0,V=!0){let{connectToHost:Q,scheduleSync:Z,store:J}=this;if(!await J.seed.load())return;await this.drainApplyQueue();let Y=await J.hosts.list();for(let X of Y)await Q(X,$,!1);if(V)Z()}disconnect=async()=>{for(let $ of this.connections.values())try{$.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var f0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function E$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function qV($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function l($,...V){if(!qV($))throw Error("Uint8Array expected");if(V.length>0&&!V.includes($.length))throw Error("Uint8Array expected of length "+V+", got length="+$.length)}function HV($,V=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(V&&$.finished)throw Error("Hash#digest() has already been called")}function jQ($,V){l($);let Q=V.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function PV($){if(typeof $!=="boolean")throw Error(`boolean expected, not ${$}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var F0=($)=>new Uint32Array($.buffer,$.byteOffset,Math.floor($.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($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function x$($){if(typeof $==="string")$=sZ($);else if(qV($))$=f$($);else throw Error("Uint8Array expected, got "+typeof $);return $}function LQ($,V){if(V==null||typeof V!=="object")throw Error("options must be defined");return Object.assign($,V)}function mQ($,V){if($.length!==V.length)return!1;let Q=0;for(let Z=0;Z<$.length;Z++)Q|=$[Z]^V[Z];return Q===0}var SQ=($,V)=>{function Q(Z,...J){if(l(Z),$.nonceLength!==void 0){let G=J[0];if(!G)throw Error("nonce / iv required");if($.varSizeNonce)l(G);else l(G,$.nonceLength)}let W=$.tagLength;if(W&&J[1]!==void 0)l(J[1]);let Y=V(Z,...J),X=(G,N)=>{if(N!==void 0){if(G!==2)throw Error("cipher output not supported");l(N)}},I=!1;return{encrypt(G,N){if(I)throw Error("cannot encrypt() twice with same key + nonce");return I=!0,l(G),X(Y.encrypt.length,N),Y.encrypt(G,N)},decrypt(G,N){if(l(G),W&&G.length<W)throw Error("invalid ciphertext length: smaller than tagLength="+W);return X(Y.decrypt.length,N),Y.decrypt(G,N)}}}return Object.assign(Q,$),Q};function CV($,V,Q=!0){if(V===void 0)return new Uint8Array($);if(V.length!==$)throw Error("invalid output length, expected "+$+", got: "+V.length);if(Q&&!tZ(V))throw Error("invalid output, must be aligned");return V}function tZ($){return $.byteOffset%4===0}function f$($){return Uint8Array.from($)}function M0(...$){for(let V=0;V<$.length;V++)$[V].fill(0)}function B$($=32){if(f0&&typeof f0.getRandomValues==="function")return f0.getRandomValues(new Uint8Array($));if(f0&&typeof f0.randomBytes==="function")return f0.randomBytes($);throw Error("crypto.getRandomValues must be defined")}var xQ=($)=>Uint8Array.from($.split("").map((V)=>V.charCodeAt(0))),eZ=xQ("expand 16-byte k"),$J=xQ("expand 32-byte k"),VJ=F0(eZ),QJ=F0($J);function T($,V){return $<<V|$>>>32-V}function TV($){return $.byteOffset%4===0}var k$=64,ZJ=16,fQ=4294967295,EQ=new Uint32Array;function JJ($,V,Q,Z,J,W,Y,X){let I=J.length,K=new Uint8Array(k$),G=F0(K),N=TV(J)&&TV(W),w=N?F0(J):EQ,z=N?F0(W):EQ;for(let F=0;F<I;Y++){if($(V,Q,Z,G,Y,X),Y>=fQ)throw Error("arx: counter overflow");let R=Math.min(k$,I-F);if(N&&R===k$){let O=F/4;if(F%4!==0)throw Error("arx: invalid block position");for(let H=0,P;H<ZJ;H++)P=O+H,z[P]=w[P]^G[H];F+=k$;continue}for(let O=0,H;O<R;O++)H=F+O,W[H]=J[H]^K[O];F+=R}}function BQ($,V){let{allowShortKeys:Q,extendNonceFn:Z,counterLength:J,counterRight:W,rounds:Y}=LQ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},V);if(typeof $!=="function")throw Error("core must be a function");return E$(J),E$(Y),PV(W),PV(Q),(X,I,K,G,N=0)=>{l(X),l(I),l(K);let w=K.length;if(G===void 0)G=new Uint8Array(w);if(l(G),E$(N),N<0||N>=fQ)throw Error("arx: counter overflow");if(G.length<w)throw Error(`arx: output (${G.length}) is shorter than data (${w})`);let z=[],F=X.length,R,O;if(F===32)z.push(R=f$(X)),O=QJ;else if(F===16&&Q)R=new Uint8Array(32),R.set(X),R.set(X,16),O=VJ,z.push(R);else throw Error(`arx: invalid 32-byte key, got length=${F}`);if(!TV(I))z.push(I=f$(I));let H=F0(R);if(Z){if(I.length!==24)throw Error("arx: extended nonce must be 24 bytes");Z(O,H,F0(I.subarray(0,16)),H),I=I.subarray(16)}let P=16-J;if(P!==I.length)throw Error(`arx: nonce must be ${P} or 16 bytes`);if(P!==12){let q=new Uint8Array(12);q.set(I,W?0:12-I.length),I=q,z.push(I)}let D=F0(I);return JJ($,O,H,D,K,G,N,Y),M0(...z),G}}var d=($,V)=>$[V++]&255|($[V++]&255)<<8;class kQ{constructor($){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,$=x$($),l($,32);let V=d($,0),Q=d($,2),Z=d($,4),J=d($,6),W=d($,8),Y=d($,10),X=d($,12),I=d($,14);this.r[0]=V&8191,this.r[1]=(V>>>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|W<<12)&255,this.r[5]=W>>>1&8190,this.r[6]=(W>>>14|Y<<2)&8191,this.r[7]=(Y>>>11|X<<5)&8065,this.r[8]=(X>>>8|I<<8)&8191,this.r[9]=I>>>5&127;for(let K=0;K<8;K++)this.pad[K]=d($,16+2*K)}process($,V,Q=!1){let Z=Q?0:2048,{h:J,r:W}=this,Y=W[0],X=W[1],I=W[2],K=W[3],G=W[4],N=W[5],w=W[6],z=W[7],F=W[8],R=W[9],O=d($,V+0),H=d($,V+2),P=d($,V+4),D=d($,V+6),q=d($,V+8),A=d($,V+10),m=d($,V+12),f=d($,V+14),E=J[0]+(O&8191),S=J[1]+((O>>>13|H<<3)&8191),k=J[2]+((H>>>10|P<<6)&8191),C=J[3]+((P>>>7|D<<9)&8191),g=J[4]+((D>>>4|q<<12)&8191),i=J[5]+(q>>>1&8191),b=J[6]+((q>>>14|A<<2)&8191),n=J[7]+((A>>>11|m<<5)&8191),p=J[8]+((m>>>8|f<<8)&8191),h=J[9]+(f>>>5|Z),j=0,o=j+E*Y+S*(5*R)+k*(5*F)+C*(5*z)+g*(5*w);j=o>>>13,o&=8191,o+=i*(5*N)+b*(5*G)+n*(5*K)+p*(5*I)+h*(5*X),j+=o>>>13,o&=8191;let t=j+E*X+S*Y+k*(5*R)+C*(5*F)+g*(5*z);j=t>>>13,t&=8191,t+=i*(5*w)+b*(5*N)+n*(5*G)+p*(5*K)+h*(5*I),j+=t>>>13,t&=8191;let Q0=j+E*I+S*X+k*Y+C*(5*R)+g*(5*F);j=Q0>>>13,Q0&=8191,Q0+=i*(5*z)+b*(5*w)+n*(5*N)+p*(5*G)+h*(5*K),j+=Q0>>>13,Q0&=8191;let v=j+E*K+S*I+k*X+C*Y+g*(5*R);j=v>>>13,v&=8191,v+=i*(5*F)+b*(5*z)+n*(5*w)+p*(5*N)+h*(5*G),j+=v>>>13,v&=8191;let w0=j+E*G+S*K+k*I+C*X+g*Y;j=w0>>>13,w0&=8191,w0+=i*(5*R)+b*(5*F)+n*(5*z)+p*(5*w)+h*(5*N),j+=w0>>>13,w0&=8191;let g0=j+E*N+S*G+k*K+C*I+g*X;j=g0>>>13,g0&=8191,g0+=i*Y+b*(5*R)+n*(5*F)+p*(5*z)+h*(5*w),j+=g0>>>13,g0&=8191;let v0=j+E*w+S*N+k*G+C*K+g*I;j=v0>>>13,v0&=8191,v0+=i*X+b*Y+n*(5*R)+p*(5*F)+h*(5*z),j+=v0>>>13,v0&=8191;let i0=j+E*z+S*w+k*N+C*G+g*K;j=i0>>>13,i0&=8191,i0+=i*I+b*X+n*Y+p*(5*R)+h*(5*F),j+=i0>>>13,i0&=8191;let u0=j+E*F+S*z+k*w+C*N+g*G;j=u0>>>13,u0&=8191,u0+=i*K+b*I+n*X+p*Y+h*(5*R),j+=u0>>>13,u0&=8191;let y0=j+E*R+S*F+k*z+C*w+g*N;j=y0>>>13,y0&=8191,y0+=i*G+b*K+n*I+p*X+h*Y,j+=y0>>>13,y0&=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]=v,J[4]=w0,J[5]=g0,J[6]=v0,J[7]=i0,J[8]=u0,J[9]=y0}finalize(){let{h:$,pad:V}=this,Q=new Uint16Array(10),Z=$[1]>>>13;$[1]&=8191;for(let Y=2;Y<10;Y++)$[Y]+=Z,Z=$[Y]>>>13,$[Y]&=8191;$[0]+=Z*5,Z=$[0]>>>13,$[0]&=8191,$[1]+=Z,Z=$[1]>>>13,$[1]&=8191,$[2]+=Z,Q[0]=$[0]+5,Z=Q[0]>>>13,Q[0]&=8191;for(let Y=1;Y<10;Y++)Q[Y]=$[Y]+Z,Z=Q[Y]>>>13,Q[Y]&=8191;Q[9]-=8192;let J=(Z^1)-1;for(let Y=0;Y<10;Y++)Q[Y]&=J;J=~J;for(let Y=0;Y<10;Y++)$[Y]=$[Y]&J|Q[Y];$[0]=($[0]|$[1]<<13)&65535,$[1]=($[1]>>>3|$[2]<<10)&65535,$[2]=($[2]>>>6|$[3]<<7)&65535,$[3]=($[3]>>>9|$[4]<<4)&65535,$[4]=($[4]>>>12|$[5]<<1|$[6]<<14)&65535,$[5]=($[6]>>>2|$[7]<<11)&65535,$[6]=($[7]>>>5|$[8]<<8)&65535,$[7]=($[8]>>>8|$[9]<<5)&65535;let W=$[0]+V[0];$[0]=W&65535;for(let Y=1;Y<8;Y++)W=($[Y]+V[Y]|0)+(W>>>16)|0,$[Y]=W&65535;M0(Q)}update($){HV(this);let{buffer:V,blockLen:Q}=this;$=x$($);let Z=$.length;for(let J=0;J<Z;){let W=Math.min(Q-this.pos,Z-J);if(W===Q){for(;Q<=Z-J;J+=Q)this.process($,J);continue}if(V.set($.subarray(J,J+W),this.pos),this.pos+=W,J+=W,this.pos===Q)this.process(V,0,!1),this.pos=0}return this}destroy(){M0(this.h,this.r,this.buffer,this.pad)}digestInto($){HV(this),jQ($,this),this.finished=!0;let{buffer:V,h:Q}=this,{pos:Z}=this;if(Z){V[Z++]=1;for(;Z<16;Z++)V[Z]=0;this.process(V,0,!0)}this.finalize();let J=0;for(let W=0;W<8;W++)$[J++]=Q[W]>>>0,$[J++]=Q[W]>>>8;return $}digest(){let{buffer:$,outputLen:V}=this;this.digestInto($);let Q=$.slice(0,V);return this.destroy(),Q}}function WJ($){let V=(Z,J)=>$(J).update(x$(Z)).digest(),Q=$(new Uint8Array(32));return V.outputLen=Q.outputLen,V.blockLen=Q.blockLen,V.create=(Z)=>$(Z),V}var DV=WJ(($)=>new kQ($));function YJ($,V,Q,Z,J,W=20){let Y=$[0],X=V[0],I=V[1],K=V[2],G=V[3],N=$[1],w=Q[0],z=Q[1],F=J,R=0,O=$[2],H=V[4],P=V[5],D=V[6],q=V[7],A=$[3],m=Y,f=X,E=I,S=K,k=G,C=N,g=w,i=z,b=F,n=R,p=O,h=H,j=P,o=D,t=q,Q0=A;for(let w0=0;w0<W;w0+=2)k^=T(m+j|0,7),b^=T(k+m|0,9),j^=T(b+k|0,13),m^=T(j+b|0,18),n^=T(C+f|0,7),o^=T(n+C|0,9),f^=T(o+n|0,13),C^=T(f+o|0,18),t^=T(p+g|0,7),E^=T(t+p|0,9),g^=T(E+t|0,13),p^=T(g+E|0,18),S^=T(Q0+h|0,7),i^=T(S+Q0|0,9),h^=T(i+S|0,13),Q0^=T(h+i|0,18),f^=T(m+S|0,7),E^=T(f+m|0,9),S^=T(E+f|0,13),m^=T(S+E|0,18),g^=T(C+k|0,7),i^=T(g+C|0,9),k^=T(i+g|0,13),C^=T(k+i|0,18),h^=T(p+n|0,7),b^=T(h+p|0,9),n^=T(b+h|0,13),p^=T(n+b|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 v=0;Z[v++]=Y+m|0,Z[v++]=X+f|0,Z[v++]=I+E|0,Z[v++]=K+S|0,Z[v++]=G+k|0,Z[v++]=N+C|0,Z[v++]=w+g|0,Z[v++]=z+i|0,Z[v++]=F+b|0,Z[v++]=R+n|0,Z[v++]=O+p|0,Z[v++]=H+h|0,Z[v++]=P+j|0,Z[v++]=D+o|0,Z[v++]=q+t|0,Z[v++]=A+Q0|0}function XJ($,V,Q,Z){let J=$[0],W=V[0],Y=V[1],X=V[2],I=V[3],K=$[1],G=Q[0],N=Q[1],w=Q[2],z=Q[3],F=$[2],R=V[4],O=V[5],H=V[6],P=V[7],D=$[3];for(let A=0;A<20;A+=2)I^=T(J+O|0,7),w^=T(I+J|0,9),O^=T(w+I|0,13),J^=T(O+w|0,18),z^=T(K+W|0,7),H^=T(z+K|0,9),W^=T(H+z|0,13),K^=T(W+H|0,18),P^=T(F+G|0,7),Y^=T(P+F|0,9),G^=T(Y+P|0,13),F^=T(G+Y|0,18),X^=T(D+R|0,7),N^=T(X+D|0,9),R^=T(N+X|0,13),D^=T(R+N|0,18),W^=T(J+X|0,7),Y^=T(W+J|0,9),X^=T(Y+W|0,13),J^=T(X+Y|0,18),G^=T(K+I|0,7),N^=T(G+K|0,9),I^=T(N+G|0,13),K^=T(I+N|0,18),R^=T(F+z|0,7),w^=T(R+F|0,9),z^=T(w+R|0,13),F^=T(z+w|0,18),O^=T(D+P|0,7),H^=T(O+D|0,9),P^=T(H+O|0,13),D^=T(P+H|0,18);let q=0;Z[q++]=J,Z[q++]=K,Z[q++]=F,Z[q++]=D,Z[q++]=G,Z[q++]=N,Z[q++]=w,Z[q++]=z}var AV=BQ(YJ,{counterRight:!0,extendNonceFn:XJ}),_V=SQ({blockSize:64,nonceLength:24,tagLength:16},($,V)=>{return{encrypt(Q,Z){Z=CV(Q.length+32,Z,!1);let J=Z.subarray(0,32),W=Z.subarray(32);Z.set(Q,32),M0(J),AV($,V,Z,Z);let Y=DV(W,J);return Z.set(Y,16),M0(Z.subarray(0,16),Y),Z.subarray(16)},decrypt(Q,Z){l(Q),Z=CV(Q.length+32,Z,!1);let J=Z.subarray(0,32),W=Z.subarray(32,48),Y=Z.subarray(48);Z.set(Q,32),M0(J);let X=AV($,V,J,J),I=DV(Y,X);if(!mQ(W,I))throw Error("invalid tag");return AV($,V,Z.subarray(16),Z.subarray(16)),M0(J,W,I),Y}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function IJ($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function K$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function B0($,...V){if(!IJ($))throw Error("Uint8Array expected");if(V.length>0&&!V.includes($.length))throw Error("Uint8Array expected of length "+V+", got length="+$.length)}function G$($,V=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(V&&$.finished)throw Error("Hash#digest() has already been called")}function g$($,V){B0($);let Q=V.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function gQ($){return new Uint8Array($.buffer,$.byteOffset,$.byteLength)}function c0($){return new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4))}function d0(...$){for(let V=0;V<$.length;V++)$[V].fill(0)}function M$($,V){return $<<32-V|$>>>V}var vQ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function iQ($){return $<<24&4278190080|$<<8&16711680|$>>>8&65280|$>>>24&255}var uQ=vQ?($)=>$:($)=>iQ($);function KJ($){for(let V=0;V<$.length;V++)$[V]=iQ($[V]);return $}var $0=vQ?($)=>$:KJ;function GJ($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function o0($){if(typeof $==="string")$=GJ($);return B0($),$}class jV{}function yQ($){let V=(Z,J)=>$(J).update(o0(Z)).digest(),Q=$({});return V.outputLen=Q.outputLen,V.blockLen=Q.blockLen,V.create=(Z)=>$(Z),V}var bQ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var v$=BigInt(4294967295),nQ=BigInt(32);function LV($,V=!1){if(V)return{h:Number($&v$),l:Number($>>nQ&v$)};return{h:Number($>>nQ&v$)|0,l:Number($&v$)|0}}function U0($,V,Q,Z,J){return $=$+V+J|0,Z=M$(Z^$,16),Q=Q+Z|0,V=M$(V^Q,12),{a:$,b:V,c:Q,d:Z}}function O0($,V,Q,Z,J){return $=$+V+J|0,Z=M$(Z^$,8),Q=Q+Z|0,V=M$(V^Q,7),{a:$,b:V,c:Q,d:Z}}class mV extends jV{constructor($,V){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,K$($),K$(V),this.blockLen=$,this.outputLen=V,this.buffer=new Uint8Array($),this.buffer32=c0(this.buffer)}update($){G$(this),$=o0($),B0($);let{blockLen:V,buffer:Q,buffer32:Z}=this,J=$.length,W=$.byteOffset,Y=$.buffer;for(let X=0;X<J;){if(this.pos===V)$0(Z),this.compress(Z,0,!1),$0(Z),this.pos=0;let I=Math.min(V-this.pos,J-X),K=W+X;if(I===V&&!(K%4)&&X+I<J){let G=new Uint32Array(Y,K,Math.floor((J-X)/4));$0(G);for(let N=0;X+V<J;N+=Z.length,X+=V)this.length+=V,this.compress(G,N,!1);$0(G);continue}Q.set($.subarray(X,X+I),this.pos),this.pos+=I,this.length+=I,X+=I}return this}digestInto($){G$(this),g$($,this);let{pos:V,buffer32:Q}=this;this.finished=!0,d0(this.buffer.subarray(V)),$0(Q),this.compress(Q,0,!0),$0(Q);let Z=c0($);this.get().forEach((J,W)=>Z[W]=uQ(J))}digest(){let{buffer:$,outputLen:V}=this;this.digestInto($);let Q=$.slice(0,V);return this.destroy(),Q}_cloneInto($){let{buffer:V,length:Q,finished:Z,destroyed:J,outputLen:W,pos:Y}=this;return $||($=new this.constructor({dkLen:W})),$.set(...this.get()),$.buffer.set(V),$.destroyed=J,$.finished=Z,$.length=Q,$.pos=Y,$.outputLen=W,$}clone(){return this._cloneInto()}}function SV($,V,Q,Z,J,W,Y,X,I,K,G,N,w,z,F,R,O,H,P,D){let q=0;for(let A=0;A<Z;A++)({a:J,b:I,c:w,d:O}=U0(J,I,w,O,Q[V+$[q++]])),{a:J,b:I,c:w,d:O}=O0(J,I,w,O,Q[V+$[q++]]),{a:W,b:K,c:z,d:H}=U0(W,K,z,H,Q[V+$[q++]]),{a:W,b:K,c:z,d:H}=O0(W,K,z,H,Q[V+$[q++]]),{a:Y,b:G,c:F,d:P}=U0(Y,G,F,P,Q[V+$[q++]]),{a:Y,b:G,c:F,d:P}=O0(Y,G,F,P,Q[V+$[q++]]),{a:X,b:N,c:R,d:D}=U0(X,N,R,D,Q[V+$[q++]]),{a:X,b:N,c:R,d:D}=O0(X,N,R,D,Q[V+$[q++]]),{a:J,b:K,c:F,d:D}=U0(J,K,F,D,Q[V+$[q++]]),{a:J,b:K,c:F,d:D}=O0(J,K,F,D,Q[V+$[q++]]),{a:W,b:G,c:R,d:O}=U0(W,G,R,O,Q[V+$[q++]]),{a:W,b:G,c:R,d:O}=O0(W,G,R,O,Q[V+$[q++]]),{a:Y,b:N,c:w,d:H}=U0(Y,N,w,H,Q[V+$[q++]]),{a:Y,b:N,c:w,d:H}=O0(Y,N,w,H,Q[V+$[q++]]),{a:X,b:I,c:z,d:P}=U0(X,I,z,P,Q[V+$[q++]]),{a:X,b:I,c:z,d:P}=O0(X,I,z,P,Q[V+$[q++]]);return{v0:J,v1:W,v2:Y,v3:X,v4:I,v5:K,v6:G,v7:N,v8:w,v9:z,v10:F,v11:R,v12:O,v13:H,v14:P,v15:D}}var N0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},q0=bQ.slice(),pQ=(()=>{let $=Array.from({length:16},(Z,J)=>J),V=(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=$;Z<7;Z++,J=V(J))Q.push(...J);return Uint8Array.from(Q)})();class EV extends mV{constructor($={},V=0){super(64,$.dkLen===void 0?32:$.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}=$,J=Z!==void 0;if(Q!==void 0){if(J)throw Error('Only "key" or "context" can be specified at same time');let W=o0(Q).slice();B0(W,32),this.IV=c0(W),$0(this.IV),this.flags=V|N0.KEYED_HASH}else if(J){let W=o0(Z),Y=new EV({dkLen:32},N0.DERIVE_KEY_CONTEXT).update(W).digest();this.IV=c0(Y),$0(this.IV),this.flags=V|N0.DERIVE_KEY_MATERIAL}else this.IV=q0.slice(),this.flags=V;this.state=this.IV.slice(),this.bufferOut=gQ(this.bufferOut32)}get(){return[]}set(){}b2Compress($,V,Q,Z=0){let{state:J,pos:W}=this,{h:Y,l:X}=LV(BigInt($),!0),{v0:I,v1:K,v2:G,v3:N,v4:w,v5:z,v6:F,v7:R,v8:O,v9:H,v10:P,v11:D,v12:q,v13:A,v14:m,v15:f}=SV(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],Y,X,W,V);J[0]=I^O,J[1]=K^H,J[2]=G^P,J[3]=N^D,J[4]=w^q,J[5]=z^A,J[6]=F^m,J[7]=R^f}compress($,V=0,Q=!1){let Z=this.flags;if(!this.chunkPos)Z|=N0.CHUNK_START;if(this.chunkPos===15||Q)Z|=N0.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 W,Y=this.chunksDone+1;Q||!(Y&1);Y>>=1){if(!(W=this.stack.pop()))break;this.buffer32.set(W,0),this.buffer32.set(J,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|N0.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($){$=super._cloneInto($);let{IV:V,flags:Q,state:Z,chunkPos:J,posOut:W,chunkOut:Y,stack:X,chunksDone:I}=this;return $.state.set(Z.slice()),$.stack=X.map((K)=>Uint32Array.from(K)),$.IV.set(V),$.flags=Q,$.chunkPos=J,$.chunksDone=I,$.posOut=W,$.chunkOut=Y,$.enableXOF=this.enableXOF,$.bufferOut32.set(this.bufferOut32),$}destroy(){this.destroyed=!0,d0(this.state,this.buffer32,this.IV,this.bufferOut32),d0(...this.stack)}b2CompressOut(){let{state:$,pos:V,flags:Q,buffer32:Z,bufferOut32:J}=this,{h:W,l:Y}=LV(BigInt(this.chunkOut++));$0(Z);let{v0:X,v1:I,v2:K,v3:G,v4:N,v5:w,v6:z,v7:F,v8:R,v9:O,v10:H,v11:P,v12:D,v13:q,v14:A,v15:m}=SV(pQ,0,Z,7,$[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],q0[0],q0[1],q0[2],q0[3],Y,W,V,Q);J[0]=X^R,J[1]=I^O,J[2]=K^H,J[3]=G^P,J[4]=N^D,J[5]=w^q,J[6]=z^A,J[7]=F^m,J[8]=$[0]^R,J[9]=$[1]^O,J[10]=$[2]^H,J[11]=$[3]^P,J[12]=$[4]^D,J[13]=$[5]^q,J[14]=$[6]^A,J[15]=$[7]^m,$0(Z),$0(J),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,d0(this.buffer.subarray(this.pos));let $=this.flags|N0.ROOT;if(this.stack.length)$|=N0.PARENT,$0(this.buffer32),this.compress(this.buffer32,0,!0),$0(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else $|=(!this.chunkPos?N0.CHUNK_START:0)|N0.CHUNK_END;this.flags=$,this.b2CompressOut()}writeInto($){G$(this,!1),B0($),this.finish();let{blockLen:V,bufferOut:Q}=this;for(let Z=0,J=$.length;Z<J;){if(this.posOut>=V)this.b2CompressOut();let W=Math.min(V-this.posOut,J-Z);$.set(Q.subarray(this.posOut,this.posOut+W),Z),this.posOut+=W,Z+=W}return $}xofInto($){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto($)}xof($){return K$($),this.xofInto(new Uint8Array($))}digestInto($){if(g$($,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto($),this.destroy(),$}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var hQ=yQ(($)=>new EV($));var xV=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function lQ($){let V=new Uint8Array(xV.length+32);return V.set(xV),V.set($.subarray(0,32),xV.length),V}function rQ($){return typeof $==="string"?new TextEncoder().encode($):$}function a0($){let V=new ArrayBuffer($.byteLength);return new Uint8Array(V).set($),V}class fV{verifyKeys=new Map;signKeys=new Map;async genRandomBytes($){return B$($)}async gen256BitSecureRandomSeed(){return B$(32)}async encryptXSalsa20Poly1305Combined($,V){let Q=B$(24),J=_V(V,Q).encrypt($);return new Uint8Array([...Q,...J])}async decryptXSalsa20Poly1305Combined($,V){let Q=$.slice(0,24),Z=$.slice(24);return _V(V,Q).decrypt(Z)}async deriveEd25519KeyPair($){let V=$,Q=lQ(V),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 W=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:J.x},{name:"Ed25519"},!0,["verify"]),Y=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",W)),X=new Uint8Array(64);return X.set(V,0),X.set(Y,32),this.signKeys.set(a(V),Z),this.verifyKeys.set(a(Y),W),{keyType:"ed25519",privateKey:X,publicKey:Y}}async importSignKey($){let V=$.subarray(0,32),Q=a(V),Z=this.signKeys.get(Q);if(Z)return Z;let J=lQ(V),W=await globalThis.crypto.subtle.importKey("pkcs8",a0(J),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Q,W),W}async importVerifyKey($){let V=a($),Q=this.verifyKeys.get(V);if(Q)return Q;let Z=await globalThis.crypto.subtle.importKey("raw",a0($),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set(V,Z),Z}async signEd25519($,V){let Q=rQ($),Z=await this.importSignKey(V),J=await globalThis.crypto.subtle.sign({name:"Ed25519"},Z,a0(Q));return new Uint8Array(J)}async checkSigEd25519($,V,Q){let Z=rQ(V);try{let J=await this.importVerifyKey(Q);return await globalThis.crypto.subtle.verify({name:"Ed25519"},J,a0($),a0(Z))}catch{return!1}}async blake3($){return hQ($)}}var MJ=new fV,J0=MJ;import{useEffect as n$,useState as yV}from"react";class BV{db;constructor($){this.db=$}async enq($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(W0,"readwrite"),Z=Q.objectStore(W0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let Y of V){let X=`${Y.host}:${Y.seq}`;Z.put(Y,X)}})}async deq($,V){let Q=[...V];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((W,Y)=>{Z.oncomplete=()=>W(),Z.onerror=()=>Y(Z.error);for(let X of Q){let I=`${$}:${X}`;J.delete(I)}})}async list(){let V=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Q,Z)=>{let J=V.getAll();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async count(){let V=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Q,Z)=>{let J=V.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let $=this.db.transaction(W0,"readwrite"),V=$.objectStore(W0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}function cQ($){return{label:$.label,handle:new URL($.handle),idx:$.idx,lastSeq:$.lastSeq||0,clockOffset:$.clockOffset,subscription:$.subscription}}class kV{db;constructor($){this.db=$}async add($){return this.put($)}async put($){let V={...$,handle:$.handle.toString(),lastSeq:$.lastSeq??0},Q=this.db.transaction(V0,"readwrite"),Z=Q.objectStore(V0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error),Z.put(V)})}async touch($,V){let Q=this.db.transaction(V0,"readwrite"),Z=Q.objectStore(V0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);let Y=Z.get($);Y.onsuccess=()=>{let X=Y.result;if(!X)return;let I=X.lastSeq||0;if(V<=I)return;Z.put({...X,lastSeq:V})}})}async get($){let Q=this.db.transaction(V0,"readonly").objectStore(V0);return new Promise((Z,J)=>{let W=Q.get($);W.onsuccess=()=>{let Y=W.result;if(!Y)Z(void 0);else Z(cQ(Y))},W.onerror=()=>J(W.error)})}async set($,V){let Q=await this.get($);if(!Q)return 13;try{return await this.put({...Q,...V}),0}catch{return 18}}async del($){let V=this.db.transaction(V0,"readwrite"),Q=V.objectStore(V0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),Q.delete($)})}async list(){let V=this.db.transaction(V0,"readonly").objectStore(V0);return new Promise((Q,Z)=>{let J=V.getAll();J.onsuccess=()=>{let W=J.result;Q(W.map(cQ))},J.onerror=()=>Z(J.error)})}async wipe(){let $=this.db.transaction(V0,"readwrite"),V=$.objectStore(V0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}class gV{crypto;db;constructor($,V){this.crypto=V;this.db=$}async add($){let V=this.db.transaction(u,"readwrite"),Q=V.objectStore(u);return new Promise((Z)=>{if($.length===0){Z([]);return}let J=Array($.length).fill(0);V.oncomplete=()=>Z(J),V.onerror=()=>{for(let W=0;W<J.length;W++)J[W]=18;Z(J)};for(let W=0;W<$.length;W++){let{key:Y,data:X}=$[W],I=L(Y),K=Q.put(X,I);K.onerror=(G)=>{G.preventDefault(),J[W]=18}}})}async del($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let Y of V){let X=L(Y);Z.delete(X)}})}async get($){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let W=L($),Y=Q.get(W);Y.onsuccess=async()=>{let X=Y.result;if(X)Z(await L0($,X,this.crypto));else Z(void 0)},Y.onerror=()=>J(Y.error)})}async has($){return await this.get($)!==void 0}async list($){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let W=[],Y=$===void 0?Q.openCursor():Q.index(i$).openCursor(IDBKeyRange.only($));Y.onsuccess=(X)=>{let I=X.target.result;if(I){let K=$===void 0?I.key:I.primaryKey,G=I.value;W.push({hash:I0(K),data:G}),I.continue()}else Promise.all(W.map(({hash:K,data:G})=>L0(K,G,this.crypto))).then(Z).catch(J)},Y.onerror=()=>J(Y.error)})}async last($){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let W,Y=Q.openCursor();Y.onsuccess=async(X)=>{let I=X.target.result;if(I){let{key:K,value:G}=I;if(s($,G.eid)){if(!W||(G.ctr??0)>(W.data.ctr??0)||(G.ctr??0)===(W.data.ctr??0)&&(G.off??0)>(W.data.off??0))W={key:K,data:G}}I.continue()}else if(W){let K=I0(W.key);Z(await L0(K,W.data,this.crypto))}else Z(void 0)},Y.onerror=()=>J(Y.error)})}async markApplied($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let Y of V){let X=L(Y),I=Z.get(X);I.onsuccess=()=>{let K=I.result;if(!K)return;E0(K,j0),Z.put(K,X)},I.onerror=(K)=>{K.preventDefault()}}})}async markFailed($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let{key:Y,err:X}of V){let I=L(Y),K=Z.get(I);K.onsuccess=()=>{let G=K.result;if(!G)return;E0(G,G0,X),Z.put(G,I)},K.onerror=(G)=>{G.preventDefault()}}})}async wipe(){let $=this.db.transaction(u,"readwrite"),V=$.objectStore(u);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}class s0{seed;crypto;constructor($,V){this.seed=$,this.crypto=V}async deriveFromKDM($){let V=V$(this.seed,$);return await this.crypto.blake3(V)}async derive($,V=0){let Q=new TextEncoder().encode($),Z=new Uint8Array(8);new DataView(Z.buffer).setBigUint64(0,BigInt(V),!1);let J=V$(Q,Z);return await this.deriveFromKDM(J)}}class vV{enclave;db;constructor($){this.db=$}async save($){let V=a($),Q=this.db.transaction(H0,"readwrite"),Z=Q.objectStore(H0);return new Promise((J,W)=>{Q.oncomplete=()=>{this.enclave=new s0($,J0),J(this.enclave)},Q.onerror=()=>W(Q.error),Z.put(V,"seed")})}async load(){if(this.enclave)return this.enclave;let V=this.db.transaction(H0,"readonly").objectStore(H0);return new Promise((Q,Z)=>{let J=V.get("seed");J.onsuccess=()=>{let W=J.result;if(!W)Q(void 0);else{let Y=_0(W);this.enclave=new s0(Y,J0),Q(this.enclave)}},J.onerror=()=>Z(J.error)})}async wipe(){this.enclave=void 0;let $=this.db.transaction(H0,"readwrite"),V=$.objectStore(H0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.delete("seed")})}}class iV{db;constructor($){this.db=$}async enq($,V){let Q=[...V];if(Q.length===0)return;let Z=this.db.transaction(Y0,"readwrite"),J=Z.objectStore(Y0);return new Promise((W,Y)=>{Z.oncomplete=()=>W(),Z.onerror=()=>Y(Z.error);for(let X of Q){let I=a(X);J.put({host:$,hash:I})}})}async deq($,V){let Q=[...V];if(Q.length===0)return;let Z=this.db.transaction(Y0,"readwrite"),J=Z.objectStore(Y0);return new Promise((W,Y)=>{Z.oncomplete=()=>W(),Z.onerror=()=>Y(Z.error);for(let X of Q){let I=a(X);J.delete([$,I])}})}async list($){let Q=this.db.transaction(Y0,"readonly").objectStore(Y0);return new Promise((Z,J)=>{let W=Q.getAll();W.onsuccess=()=>{let X=W.result.filter((I)=>I.host===$).map((I)=>I.hash);Z(X.map((I)=>_0(I)))},W.onerror=()=>J(W.error)})}async count(){let V=this.db.transaction(Y0,"readonly").objectStore(Y0);return new Promise((Q,Z)=>{let J=V.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let $=this.db.transaction(Y0,"readwrite"),V=$.objectStore(Y0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}var H0="seedMeta",V0="hosts",Y0="uploadQueue",W0="downloadQueue",u="messages",i$="apld",NJ=3;class uV{seed;hosts;uploads;downloads;messages;db;constructor($,V){this.db=$,this.seed=new vV($),this.hosts=new kV($),this.uploads=new iV($),this.downloads=new BV($),this.messages=new gV($,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 wJ(){return new Promise(($,V)=>{let Q=indexedDB.open("diplomatic-store-db",NJ);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!Z.objectStoreNames.contains(H0))Z.createObjectStore(H0);if(!Z.objectStoreNames.contains(V0))Z.createObjectStore(V0,{keyPath:"label"});if(!Z.objectStoreNames.contains(Y0))Z.createObjectStore(Y0,{keyPath:["host","hash"]});if(!Z.objectStoreNames.contains(W0))Z.createObjectStore(W0);let W;if(!Z.objectStoreNames.contains(u))W=Z.createObjectStore(u);else{if(!J)throw Error("missing upgrade transaction for messages store");W=J.objectStore(u)}if(!W.indexNames.contains(i$))W.createIndex(i$,"apld",{unique:!1})},Q.onsuccess=()=>$(Q.result),Q.onerror=()=>V(Q.error)})}async function u$($){let V=await wJ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new uV(V,$)}function dQ($){if(!$||typeof $!=="object")return!1;if(!("kind"in $))return!1;return typeof $.kind==="string"}function oQ($){if(typeof $!=="number")return;return $}function aQ($){if(!$||typeof $!=="object")return;if(!("hasSeed"in $)||!("hasHost"in $)||!("connected"in $))return;if(typeof $.hasSeed!=="boolean"||typeof $.hasHost!=="boolean"||typeof $.connected!=="boolean")return;return{hasSeed:$.hasSeed,hasHost:$.hasHost,connected:$.connected}}function RJ($){if(!$||typeof $!=="object")return;if(!("phase"in $))return;let V=zJ($.phase);if(V===void 0)return;let Q={phase:V};if("host"in $&&typeof $.host==="string")Q.host=$.host;if("done"in $&&typeof $.done==="number")Q.done=$.done;if("total"in $&&typeof $.total==="number")Q.total=$.total;if("bytesDone"in $&&typeof $.bytesDone==="number")Q.bytesDone=$.bytesDone;if("bytesTotal"in $&&typeof $.bytesTotal==="number")Q.bytesTotal=$.bytesTotal;return Q}function zJ($){if($==="peek"||$==="pull"||$==="open"||$==="exec"||$==="push"||$==="import"||$==="idle"||$==="apply")return $==="apply"?"exec":$;return}function sQ($){if(!$||typeof $!=="object")return;if(!("numUploads"in $)||!("numDownloads"in $))return;if(typeof $.numUploads!=="number"||typeof $.numDownloads!=="number")return;let V={phase:"idle"};if("progress"in $){let Q=RJ($.progress);if(Q===void 0)return;V=Q}return{numUploads:$.numUploads,numDownloads:$.numDownloads,progress:V}}var P0="[DIPLOMATIC]";class N${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:S0};clientState;xferState;constructor($,V,Q,Z,J){this.worker=$,this.state=V,this.clientState=new K0(async()=>this.cachedClientState),this.xferState=new K0(async()=>this.cachedXferState),this.scheduledSync=new W$(J,async()=>{try{await this.request({id:this.allocId(),op:"sync"})}catch(W){console.error(`${P0} worker sync after local write failed`,W)}}),this.local=new x0(Z,V,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((W,Y)=>{this.resolveReady=W,this.rejectReady=Y}),this.worker.onmessage=(W)=>{this.onMessage(W.data)},this.worker.onerror=(W)=>{console.error(`${P0} worker error`,W),this.failReady(Error(`${P0} worker failed to load`))},this.worker.onmessageerror=()=>{this.failReady(Error(`${P0} worker message error`))}}failReady($){let V=this.rejectReady;if(this.rejectReady=void 0,this.resolveReady=void 0,V)V($)}async flushScheduledSync(){await this.scheduledSync.flush()}static async connect($,V,Q){let Z=Q.clock??new R0,J=Q.syncDebounceMs??m$,W=new N$(Q.worker,$,V,Z,J),Y=Q.readyTimeoutMs??15000,X;try{let I=W.probeReady();if(await Promise.race([W.ready,I,new Promise((K,G)=>{X=setTimeout(()=>{G(Error(`${P0} worker ready timeout after ${Y}ms`))},Y)})]),X!==void 0)clearTimeout(X),X=void 0;I.catch(()=>{}),await W.hydrateStateFromStore(V),await W.pullRemoteState()}catch(I){throw W.terminate(),I}finally{if(X!==void 0)clearTimeout(X)}return W}async hydrateStateFromStore($){let V=await $.seed.load(),Q=await $.hosts.list();this.cachedClientState={hasSeed:V!==void 0,hasHost:Array.from(Q).length>0,connected:!1};let Z=await $.uploads.count(),J=await $.downloads.count();this.cachedXferState={numUploads:Z,numDownloads:J,progress:S0}}async pullRemoteState(){let $=await this.request({id:this.allocId(),op:"getClientState"}),V=aQ($);if(V!==void 0)this.cachedClientState=V;let Q=await this.request({id:this.allocId(),op:"getXferState"}),Z=sQ(Q);if(Z!==void 0)this.cachedXferState=Z}markReady(){let $=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,$)$()}probeReady(){return new Promise(($,V)=>{let Q=this.allocId();this.pending.set(Q,{resolve:(Z)=>{if(Z==="pong"){this.markReady(),$();return}V(Error(`${P0} worker probe ping failed`))},reject:V}),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[,$]of this.pending)$.reject(Error(`${P0} worker terminated`));this.pending.clear()}onMessage($){if(!dQ($))return;let V=$;switch(V.kind){case"ready":{this.markReady();return}case"clientState":{this.cachedClientState=V.state,this.clientState.emit();return}case"xferState":{this.cachedXferState=V.state,this.xferState.emit();return}case"dirty":{this.state.refresh(V.eids.map(FJ));return}case"wiped":{this.state.clear();return}case"reply":{let Q=this.pending.get(V.id);if(!Q)return;if(this.pending.delete(V.id),V.ok)Q.resolve(V.result);else Q.reject(new y$(V.status));return}default:return}}allocId(){let $=this.nextId;return this.nextId+=1,$}request($,V){return new Promise((Q,Z)=>{if(this.pending.set($.id,{resolve:Q,reject:Z}),V&&V.length>0)this.worker.postMessage($,V);else this.worker.postMessage($)})}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 y$)return Q.status;return 12}}serializeHost($){return{handle:$.handle.href,label:$.label,idx:$.idx??0}}async setSeed($){await this.ready,await this.local.setSeed($);let V=$.slice();await this.request({id:this.allocId(),op:"setSeed",seed:V},[V.buffer])}async link($,V=!0){await this.ready,await this.local.link($,!1),await this.request({id:this.allocId(),op:"link",host:this.serializeHost($),connect:V})}async unlink($){await this.ready,await this.local.unlink($),await this.request({id:this.allocId(),op:"unlink",label:$})}async hosts(){return await this.ready,this.local.hosts()}async connect($=!0,V=!0){await this.ready,await this.request({id:this.allocId(),op:"connect",listen:$,sync:V})}async disconnect(){await this.ready,await this.request({id:this.allocId(),op:"disconnect"})}async insertRaw($){return await this.ready,this.local.insertRaw($)}async updateRaw($,V,Q){return await this.ready,this.local.updateRaw($,V,Q)}async insert($){return await this.ready,this.local.insert($)}async update($){return await this.ready,this.local.update($)}async delete($){return await this.ready,this.local.delete($)}async genEID($){return await this.ready,this.local.genEID($)}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($){await this.ready;let V=new Uint8Array(await $.arrayBuffer());return this.requestStatus({id:this.allocId(),op:"import",bytes:V},[V.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 S$(Z,$),0}catch(Q){if(Q instanceof y$)return Q.status;return 12}}}class y$ extends Error{status;constructor($){super(`WorkerReplyError: ${_[$]}`);this.status=$;this.name="WorkerReplyError"}}function FJ($){return $}var k0="[DIPLOMATIC]";async function b$($){let V=$.clock??new R0;if($.worker!==void 0&&UJ($)!==void 0)throw Error(`${k0} worker path requires IndexedDB on both sides; do not pass store (got a custom store)`);if($.worker===void 0){console.info(`${k0} sync on main thread `+"(no worker — app did not request a worker)");let J=await tQ($.store);return OJ(V,$.state,J)}if(typeof Worker>"u")throw Error(`${k0} worker was provided but Worker API is unavailable`);let Q=await tQ(void 0);console.info(`${k0} attaching app-provided sync worker…`);let Z=await N$.connect($.state,Q,{worker:$.worker,readyTimeoutMs:$.readyTimeoutMs,clock:V,syncDebounceMs:$.syncDebounceMs});return await Z.ping(),console.info(`${k0} sync worker active (network + EntDB writes off main; local mutates on main; dirty signals only)`),{client:Z,mode:"worker",dispose:()=>{console.info(`${k0} terminating sync worker`),Z.terminate()}}}function UJ($){if("store"in $)return $.store;return}async function OJ($,V,Q){let Z=new x0($,V,Q,C$,J0);return{client:Z,mode:"main",dispose:()=>{Z.disconnect()}}}async function tQ($){if($!==void 0)return $;if(typeof indexedDB>"u")throw Error(`${k0} IndexedDB is unavailable; pass store explicitly (e.g. new MemoryStore(crypto))`);return u$(J0)}function qJ($){let[V,Q]=yV();return n$(()=>{async function Z(){let W=await $.clientState.get();Q(W)}let J=$.clientState.listen(Z);return Z(),()=>{J()}},[$]),V}function HJ($){let[V,Q]=yV();return n$(()=>{async function Z(){let W=await $.xferState.get();Q(W)}let J=$.xferState.listen(Z);return Z(),()=>{J()}},[$]),V}function PJ($){n$(()=>{async function V(){try{await $.connect(),await $.sync()}catch(W){console.error("reconnectAndSync failed",W)}}function Q(){V()}function Z(){if(typeof document<"u"&&document.visibilityState==="visible")V()}function J(){V()}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)}},[$])}function CJ($={}){let V=$.clock??new R0,{seed:Q,host:Z,readyTimeoutMs:J}=$,W=$.worker,Y="store"in $?$.store:void 0,[X,I]=yV({stateMgr:XV});return n$(()=>{let K=!1,G;return(async()=>{let N=await NV();if(K)return;let w=j$(N),z=W!==void 0?await b$({state:w,clock:V,worker:W,readyTimeoutMs:J}):await b$({state:w,clock:V,store:Y,readyTimeoutMs:J});if(K){z.dispose();return}G=z.dispose;let{client:F,mode:R}=z;if(Q)await F.setSeed(Q);if(Z)await F.link(Z);if(K){G();return}I({client:F,entDB:N,stateMgr:w,mode:R,error:void 0})})().catch((N)=>{let w=N instanceof Error?N:Error(String(N));if(console.error("[DIPLOMATIC] useClient init failed",w),!K)I((z)=>({...z,client:void 0,error:w}))}),()=>{K=!0,G?.()}},[V,Q,Z,W,Y,J]),X}import{use as TJ,useEffect as eQ,useRef as DJ,useState as AJ}from"react";function $Z($,V,Q){let[Z,J]=AJ();return eQ(()=>{async function W(){let Y=await Q();J(Y)}return W(),$.on(V,W),()=>{$.off(V,W)}},[$,V,Q]),Z}function _J($,V,Q){let Z=DJ(Q());return eQ(()=>{async function J(){Z.current=Q()}return $.on(V,J),()=>{$.off(V,J)}},[$,V,Q]),TJ(Z.current)}function VZ($,V){return`${$}:${V}`}class bV{queue=new Map;async enq($){for(let V of $){let Q=VZ(V.host,V.seq);this.queue.set(Q,V)}}async deq($,V){for(let Q of V){let Z=VZ($,Q);this.queue.delete(Z)}}async list(){let $=[];for(let V of this.queue.values())$.push(V);return $}async count(){return this.queue.size}async wipe(){this.queue.clear()}}class nV{hosts=new Map;async add($){let V={...$,lastSeq:0};this.hosts.set($.label,V)}async touch($,V){let Q=this.hosts.get($);if(!Q||V<=Q.lastSeq)return;this.hosts.set($,{...Q,lastSeq:V})}async get($){return this.hosts.get($)}async set($,V){let Q=this.hosts.get($);if(!Q)return 13;return this.hosts.set($,{...Q,...V}),0}async del($){this.hosts.delete($)}async list(){return this.hosts.values()}async wipe(){this.hosts.clear()}}class pV{crypto;messages=new Map;constructor($){this.crypto=$}async add($){let V=[];for(let{key:Q,data:Z}of $)this.messages.set(L(Q),Z),V.push(0);return V}async del($){for(let V of $)this.messages.delete(L(V))}async get($){let V=this.messages.get(L($));if(V)return await L0($,V,this.crypto);return}async has($){return this.messages.has(L($))}async list($){let V=[];for(let[Q,Z]of this.messages){if($!==void 0&&I$(Z.apld)!==$)continue;let J=I0(Q);V.push(await L0(J,Z,this.crypto))}return V}async last($){let V;for(let[Q,Z]of this.messages){if(s($,Z.eid)===!1)continue;let J=I0(Q);if(V===void 0)V={hash:J,data:Z};else if((Z.ctr??0)>(V.data.ctr??0)||(Z.ctr??0)===(V.data.ctr??0)&&(Z.off??0)>(V.data.off??0))V={hash:J,data:Z}}if(V)return await L0(V.hash,V.data,this.crypto);return}async markApplied($){for(let V of $){let Q=this.messages.get(L(V));if(!Q)continue;E0(Q,j0)}}async markFailed($){for(let{key:V,err:Q}of $){let Z=this.messages.get(L(V));if(!Z)continue;E0(Z,G0,Q)}}async wipe(){this.messages.clear()}}class hV{enclave;async save($){return this.enclave=new s0($,J0),this.enclave}async load(){return this.enclave}async wipe(){this.enclave=void 0}}class lV{queue=new Map;async enq($,V){let Q=this.queue.get($)||new Set;this.queue.set($,Q);for(let Z of V)Q.add(a(Z))}async deq($,V){let Q=this.queue.get($);if(Q)for(let Z of V)Q.delete(a(Z))}async list($){let V=this.queue.get($);if(!V)return[];let Q=[];for(let Z of V)Q.push(_0(Z));return Q}async count(){let $=0;for(let V of this.queue.values())$+=V.size;return $}async wipe(){this.queue.clear()}}class QZ{seed=new hV;hosts=new nV;uploads=new lV;downloads=new bV;messages;constructor($){this.messages=new pV($)}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($){this.singletonType=$}async apply($){for(let V of $){let Q=new x(V.eid),[Z,J]=Q.readStruct(r);if(J!==0)continue;let W=new B;W.writeVarString(this.singletonType);let Y=W.result();if(Z.id.length===Y.length&&Z.id.every((X,I)=>X===Y[I])){if(this.latest===void 0||V.off>this.latestOff)this.latestOff=V.off,this.latest=V.bod,this.emitter.emit(this.singletonType,null)}}return $.map(()=>0)}clear=async()=>{return this.latest=void 0,this.latestOff=-1,this.emitter.emit(this.singletonType,null),0};notify=($)=>{for(let V of $)if(V===this.singletonType)this.emitter.emit(this.singletonType,null)};refresh=async($)=>{this.notify([this.singletonType])};on=($,V)=>{this.emitter.addEventListener($,V)};off=($,V)=>{this.emitter.removeEventListener($,V)}}async function Jw($,V){let Q=await u$(J0),Z=new x0(new R0,$,Q,C$,J0);return{client:Z,setSeed:async(W)=>{let Y=_0(W);await Q.seed.save(Y),await Q.hosts.add({handle:V,label:"host",idx:0}),await Z.connect()}}}export{PJ as useSyncOnResume,_J as useStateWatcherSuspense,$Z as useStateWatcher,HJ as useClientXferState,qJ as useClientState,CJ as useClient,RV as shouldEmitItemProgress,E0 as setApld,wV as revFromHead,bZ as revFromEntity,u$ as openIDBStore,NV as openEntDB,b$ as openDiplomaticClient,XV as nullStateManager,nZ as nullEntDB,FV as isTerminalApplyFailure,lZ as isPendingApply,hZ as isApldState,S0 as idleProgress,_0 as htob,C$ as hostHTTPTransport,Jw as genWebClient,SZ as genSingletonEID,j$ as entStateManager,r as eidCodec,X$ as defaultPeekProgressEvery,J0 as crypto,a as btoh,L as btob64,I0 as b64tob,I$ as apldFromStored,N$ as WorkerClient,C0 as TypedEventEmitter,x0 as SyncClient,_ as Status,Z$ as StateManager,ZZ as SingletonStateManager,QZ as MemoryStore,uV as IDBStore,ZV as HTTPTransport,MV as EntIDB,_$ as EntDBMemory,B as Encoder,x as Decoder,R0 as Clock,J$ as CachedEntDB,z0 as APLD_PENDING,G0 as APLD_ERROR,j0 as APLD_APPLIED};
1
+ function rV($){let V=$.length,Q=0,Z=0;while(Z<V){let J=$.charCodeAt(Z++);if((J&4294967168)===0){Q++;continue}else if((J&4294965248)===0)Q+=2;else{if(J>=55296&&J<=56319){if(Z<V){let W=$.charCodeAt(Z);if((W&64512)===56320)++Z,J=((J&1023)<<10)+(W&1023)+65536}}if((J&4294901760)===0)Q+=3;else Q+=4}}return Q}function JZ($,V,Q){let Z=$.length,J=Q,W=0;while(W<Z){let Y=$.charCodeAt(W++);if((Y&4294967168)===0){V[J++]=Y;continue}else if((Y&4294965248)===0)V[J++]=Y>>6&31|192;else{if(Y>=55296&&Y<=56319){if(W<Z){let X=$.charCodeAt(W);if((X&64512)===56320)++W,Y=((Y&1023)<<10)+(X&1023)+65536}}if((Y&4294901760)===0)V[J++]=Y>>12&15|224,V[J++]=Y>>6&63|128;else V[J++]=Y>>18&7|240,V[J++]=Y>>12&63|128,V[J++]=Y>>6&63|128}V[J++]=Y&63|128}}var WZ=new TextEncoder,YZ=50;function XZ($,V,Q){WZ.encodeInto($,V.subarray(Q))}function cV($,V,Q){if($.length>YZ)XZ($,V,Q);else JZ($,V,Q)}var IZ=4096;function p$($,V,Q){let Z=V,J=Z+Q,W=[],Y="";while(Z<J){let X=$[Z++];if((X&128)===0)W.push(X);else if((X&224)===192){let I=$[Z++]&63;W.push((X&31)<<6|I)}else if((X&240)===224){let I=$[Z++]&63,K=$[Z++]&63;W.push((X&31)<<12|I<<6|K)}else if((X&248)===240){let I=$[Z++]&63,K=$[Z++]&63,G=$[Z++]&63,N=(X&7)<<18|I<<12|K<<6|G;if(N>65535)N-=65536,W.push(N>>>10&1023|55296),N=56320|N&1023;W.push(N)}else W.push(X);if(W.length>=IZ)Y+=String.fromCharCode(...W),W.length=0}if(W.length>0)Y+=String.fromCharCode(...W);return Y}var KZ=new TextDecoder,GZ=200;function MZ($,V,Q){let Z=$.subarray(V,V+Q);return KZ.decode(Z)}function dV($,V,Q){if(Q>GZ)return MZ($,V,Q);else return p$($,V,Q)}class b0{type;data;constructor($,V){this.type=$,this.data=V}}class e extends Error{constructor($){super($);let V=Object.create(e.prototype);Object.setPrototypeOf(this,V),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}}var n0=4294967295;function oV($,V,Q){let Z=Q/4294967296,J=Q;$.setUint32(V,Z),$.setUint32(V+4,J)}function w$($,V,Q){let Z=Math.floor(Q/4294967296),J=Q;$.setUint32(V,Z),$.setUint32(V+4,J)}function R$($,V){let Q=$.getInt32(V),Z=$.getUint32(V+4);return Q*4294967296+Z}function aV($,V){let Q=$.getUint32(V),Z=$.getUint32(V+4);return Q*4294967296+Z}var NZ=-1,wZ=4294967295,RZ=17179869183;function zZ({sec:$,nsec:V}){if($>=0&&V>=0&&$<=RZ)if(V===0&&$<=wZ){let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,$),Q}else{let Q=$/4294967296,Z=$&4294967295,J=new Uint8Array(8),W=new DataView(J.buffer);return W.setUint32(0,V<<2|Q&3),W.setUint32(4,Z),J}else{let Q=new Uint8Array(12),Z=new DataView(Q.buffer);return Z.setUint32(0,V),w$(Z,4,$),Q}}function FZ($){let V=$.getTime(),Q=Math.floor(V/1000),Z=(V-Q*1000)*1e6,J=Math.floor(Z/1e9);return{sec:Q+J,nsec:Z-J*1e9}}function UZ($){if($ instanceof Date){let V=FZ($);return zZ(V)}else return null}function OZ($){let V=new DataView($.buffer,$.byteOffset,$.byteLength);switch($.byteLength){case 4:{let Q=V.getUint32(0),Z=0;return{sec:Q,nsec:0}}case 8:{let Q=V.getUint32(0),Z=V.getUint32(4),J=(Q&3)*4294967296+Z,W=Q>>>2;return{sec:J,nsec:W}}case 12:{let Q=R$(V,4),Z=V.getUint32(0);return{sec:Q,nsec:Z}}default:throw new e(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${$.length}`)}}function qZ($){let V=OZ($);return new Date(V.sec*1000+V.nsec/1e6)}var sV={type:NZ,encode:UZ,decode:qZ};class p0{static defaultCodec=new p0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(sV)}register({type:$,encode:V,decode:Q}){if($>=0)this.encoders[$]=V,this.decoders[$]=Q;else{let Z=-1-$;this.builtInEncoders[Z]=V,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 W=-1-Q;return new b0(W,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 b0(Q,J)}}if($ instanceof b0)return $;return null}decode($,V,Q){let Z=V<0?this.builtInDecoders[-1-V]:this.decoders[V];if(Z)return Z($,V,Q);else return new b0(V,$)}}function HZ($){return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer}function t0($){if($ instanceof Uint8Array)return $;else if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);else if(HZ($))return new Uint8Array($);else return Uint8Array.from($)}var PZ=100,CZ=2048;class z${extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??p0.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.maxDepth=$?.maxDepth??PZ,this.initialBufferSize=$?.initialBufferSize??CZ,this.sortKeys=$?.sortKeys??!1,this.forceFloat32=$?.forceFloat32??!1,this.ignoreUndefined=$?.ignoreUndefined??!1,this.forceIntegerToFloat=$?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new z$({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($){if(this.entered)return this.clone().encodeSharedRef($);try{return this.entered=!0,this.reinitializeState(),this.doEncode($,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode($){if(this.entered)return this.clone().encode($);try{return this.entered=!0,this.reinitializeState(),this.doEncode($,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode($,V){if(V>this.maxDepth)throw Error(`Too deep objects in depth ${V}`);if($==null)this.encodeNil();else if(typeof $==="boolean")this.encodeBoolean($);else if(typeof $==="number")if(!this.forceIntegerToFloat)this.encodeNumber($);else this.encodeNumberAsFloat($);else if(typeof $==="string")this.encodeString($);else if(this.useBigInt64&&typeof $==="bigint")this.encodeBigInt64($);else this.encodeObject($,V)}ensureBufferSizeToWrite($){let V=this.pos+$;if(this.view.byteLength<V)this.resizeBuffer(V*2)}resizeBuffer($){let V=new ArrayBuffer($),Q=new Uint8Array(V),Z=new DataView(V);Q.set(this.bytes),this.view=Z,this.bytes=Q}encodeNil(){this.writeU8(192)}encodeBoolean($){if($===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber($){if(!this.forceIntegerToFloat&&Number.isSafeInteger($))if($>=0)if($<128)this.writeU8($);else if($<256)this.writeU8(204),this.writeU8($);else if($<65536)this.writeU8(205),this.writeU16($);else if($<4294967296)this.writeU8(206),this.writeU32($);else if(!this.useBigInt64)this.writeU8(207),this.writeU64($);else this.encodeNumberAsFloat($);else if($>=-32)this.writeU8(224|$+32);else if($>=-128)this.writeU8(208),this.writeI8($);else if($>=-32768)this.writeU8(209),this.writeI16($);else if($>=-2147483648)this.writeU8(210),this.writeI32($);else if(!this.useBigInt64)this.writeU8(211),this.writeI64($);else this.encodeNumberAsFloat($);else this.encodeNumberAsFloat($)}encodeNumberAsFloat($){if(this.forceFloat32)this.writeU8(202),this.writeF32($);else this.writeU8(203),this.writeF64($)}encodeBigInt64($){if($>=BigInt(0))this.writeU8(207),this.writeBigUint64($);else this.writeU8(211),this.writeBigInt64($)}writeStringHeader($){if($<32)this.writeU8(160+$);else if($<256)this.writeU8(217),this.writeU8($);else if($<65536)this.writeU8(218),this.writeU16($);else if($<4294967296)this.writeU8(219),this.writeU32($);else throw Error(`Too long string: ${$} bytes in UTF-8`)}encodeString($){let Q=rV($);this.ensureBufferSizeToWrite(5+Q),this.writeStringHeader(Q),cV($,this.bytes,this.pos),this.pos+=Q}encodeObject($,V){let Q=this.extensionCodec.tryToEncode($,this.context);if(Q!=null)this.encodeExtension(Q);else if(Array.isArray($))this.encodeArray($,V);else if(ArrayBuffer.isView($))this.encodeBinary($);else if(typeof $==="object")this.encodeMap($,V);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply($)}`)}encodeBinary($){let V=$.byteLength;if(V<256)this.writeU8(196),this.writeU8(V);else if(V<65536)this.writeU8(197),this.writeU16(V);else if(V<4294967296)this.writeU8(198),this.writeU32(V);else throw Error(`Too large binary: ${V}`);let Q=t0($);this.writeU8a(Q)}encodeArray($,V){let Q=$.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 $)this.doEncode(Z,V+1)}countWithoutUndefined($,V){let Q=0;for(let Z of V)if($[Z]!==void 0)Q++;return Q}encodeMap($,V){let Q=Object.keys($);if(this.sortKeys)Q.sort();let Z=this.ignoreUndefined?this.countWithoutUndefined($,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 W=$[J];if(!(this.ignoreUndefined&&W===void 0))this.encodeString(J),this.doEncode(W,V+1)}}encodeExtension($){if(typeof $.data==="function"){let Q=$.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($.type),this.writeU8a(Q);return}let V=$.data.length;if(V===1)this.writeU8(212);else if(V===2)this.writeU8(213);else if(V===4)this.writeU8(214);else if(V===8)this.writeU8(215);else if(V===16)this.writeU8(216);else if(V<256)this.writeU8(199),this.writeU8(V);else if(V<65536)this.writeU8(200),this.writeU16(V);else if(V<4294967296)this.writeU8(201),this.writeU32(V);else throw Error(`Too large extension object: ${V}`);this.writeI8($.type),this.writeU8a($.data)}writeU8($){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,$),this.pos++}writeU8a($){let V=$.length;this.ensureBufferSizeToWrite(V),this.bytes.set($,this.pos),this.pos+=V}writeI8($){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,$),this.pos++}writeU16($){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,$),this.pos+=2}writeI16($){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,$),this.pos+=2}writeU32($){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,$),this.pos+=4}writeI32($){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,$),this.pos+=4}writeF32($){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,$),this.pos+=4}writeF64($){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,$),this.pos+=8}writeU64($){this.ensureBufferSizeToWrite(8),oV(this.view,this.pos,$),this.pos+=8}writeI64($){this.ensureBufferSizeToWrite(8),w$(this.view,this.pos,$),this.pos+=8}writeBigUint64($){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,$),this.pos+=8}writeBigInt64($){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,$),this.pos+=8}}function m0($,V){return new z$(V).encodeSharedRef($)}function F$($){return`${$<0?"-":""}0x${Math.abs($).toString(16).padStart(2,"0")}`}var TZ=16,DZ=16;class h${hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor($=TZ,V=DZ){this.maxKeyLength=$,this.maxLengthPerKey=V,this.caches=[];for(let Q=0;Q<this.maxKeyLength;Q++)this.caches.push([])}canBeCached($){return $>0&&$<=this.maxKeyLength}find($,V,Q){let Z=this.caches[Q-1];$:for(let J of Z){let W=J.bytes;for(let Y=0;Y<Q;Y++)if(W[Y]!==$[V+Y])continue $;return J.str}return null}store($,V){let Q=this.caches[$.length-1],Z={bytes:$,str:V};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=p$($,V,Q),W=Uint8Array.prototype.slice.call($,V,V+Q);return this.store(W,J),J}}var l$="array",$$="map_key",eV="map_value",AZ=($)=>{if(typeof $==="string"||typeof $==="number")return $;throw new e("The type of key must be string or number but "+typeof $)};class $Q{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState($){let V=this.getUninitializedStateFromPool();V.type=l$,V.position=0,V.size=$,V.array=Array($)}pushMapState($){let V=this.getUninitializedStateFromPool();V.type=$$,V.readCount=0,V.size=$,V.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let $={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push($)}return this.stack[this.stackHeadPosition]}release($){if(this.stack[this.stackHeadPosition]!==$)throw Error("Invalid stack state. Released state is not on top of the stack.");if($.type===l$){let Q=$;Q.size=0,Q.array=void 0,Q.position=0,Q.type=void 0}if($.type===$$||$.type===eV){let Q=$;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,r$=new DataView(new ArrayBuffer(0)),_Z=new Uint8Array(r$.buffer);try{r$.getInt8(0)}catch($){if(!($ 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 tV=RangeError("Insufficient data"),jZ=new h$;class U${extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=r$;bytes=_Z;headByte=e0;stack=new $Q;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??p0.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.rawStrings=$?.rawStrings??!1,this.maxStrLength=$?.maxStrLength??n0,this.maxBinLength=$?.maxBinLength??n0,this.maxArrayLength=$?.maxArrayLength??n0,this.maxMapLength=$?.maxMapLength??n0,this.maxExtLength=$?.maxExtLength??n0,this.keyDecoder=$?.keyDecoder!==void 0?$.keyDecoder:jZ,this.mapKeyConverter=$?.mapKeyConverter??AZ}clone(){return new U$({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($){let V=t0($);this.bytes=V,this.view=new DataView(V.buffer,V.byteOffset,V.byteLength),this.pos=0}appendBuffer($){if(this.headByte===e0&&!this.hasRemaining(1))this.setBuffer($);else{let V=this.bytes.subarray(this.pos),Q=t0($),Z=new Uint8Array(V.length+Q.length);Z.set(V),Z.set(Q,V.length),this.setBuffer(Z)}}hasRemaining($){return this.view.byteLength-this.pos>=$}createExtraByteError($){let{view:V,pos:Q}=this;return RangeError(`Extra ${V.byteLength-Q} of ${V.byteLength} byte(s) found at buffer[${$}]`)}decode($){if(this.entered)return this.clone().decode($);try{this.entered=!0,this.reinitializeState(),this.setBuffer($);let V=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return V}finally{this.entered=!1}}*decodeMulti($){if(this.entered){yield*this.clone().decodeMulti($);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer($);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync($){if(this.entered)return this.clone().decodeAsync($);try{this.entered=!0;let V=!1,Q;for await(let Y of $){if(V)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(Y);try{Q=this.doDecodeSync(),V=!0}catch(X){if(!(X instanceof RangeError))throw X}this.totalPos+=this.pos}if(V){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Q}let{headByte:Z,pos:J,totalPos:W}=this;throw RangeError(`Insufficient data in parsing ${F$(Z)} at ${W} (${J} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream($){return this.decodeMultiAsync($,!0)}decodeStream($){return this.decodeMultiAsync($,!1)}async*decodeMultiAsync($,V){if(this.entered){yield*this.clone().decodeMultiAsync($,V);return}try{this.entered=!0;let Q=V,Z=-1;for await(let J of $){if(V&&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(W){if(!(W instanceof RangeError))throw W}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){$:while(!0){let $=this.readHeadByte(),V;if($>=224)V=$-256;else if($<192)if($<128)V=$;else if($<144){let Z=$-128;if(Z!==0){this.pushMapState(Z),this.complete();continue $}else V={}}else if($<160){let Z=$-144;if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else V=[]}else{let Z=$-160;V=this.decodeString(Z,0)}else if($===192)V=null;else if($===194)V=!1;else if($===195)V=!0;else if($===202)V=this.readF32();else if($===203)V=this.readF64();else if($===204)V=this.readU8();else if($===205)V=this.readU16();else if($===206)V=this.readU32();else if($===207)if(this.useBigInt64)V=this.readU64AsBigInt();else V=this.readU64();else if($===208)V=this.readI8();else if($===209)V=this.readI16();else if($===210)V=this.readI32();else if($===211)if(this.useBigInt64)V=this.readI64AsBigInt();else V=this.readI64();else if($===217){let Z=this.lookU8();V=this.decodeString(Z,1)}else if($===218){let Z=this.lookU16();V=this.decodeString(Z,2)}else if($===219){let Z=this.lookU32();V=this.decodeString(Z,4)}else if($===220){let Z=this.readU16();if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else V=[]}else if($===221){let Z=this.readU32();if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else V=[]}else if($===222){let Z=this.readU16();if(Z!==0){this.pushMapState(Z),this.complete();continue $}else V={}}else if($===223){let Z=this.readU32();if(Z!==0){this.pushMapState(Z),this.complete();continue $}else V={}}else if($===196){let Z=this.lookU8();V=this.decodeBinary(Z,1)}else if($===197){let Z=this.lookU16();V=this.decodeBinary(Z,2)}else if($===198){let Z=this.lookU32();V=this.decodeBinary(Z,4)}else if($===212)V=this.decodeExtension(1,0);else if($===213)V=this.decodeExtension(2,0);else if($===214)V=this.decodeExtension(4,0);else if($===215)V=this.decodeExtension(8,0);else if($===216)V=this.decodeExtension(16,0);else if($===199){let Z=this.lookU8();V=this.decodeExtension(Z,1)}else if($===200){let Z=this.lookU16();V=this.decodeExtension(Z,2)}else if($===201){let Z=this.lookU32();V=this.decodeExtension(Z,4)}else throw new e(`Unrecognized type byte: ${F$($)}`);this.complete();let Q=this.stack;while(Q.length>0){let Z=Q.top();if(Z.type===l$)if(Z.array[Z.position]=V,Z.position++,Z.position===Z.size)V=Z.array,Q.release(Z);else continue $;else if(Z.type===$$){if(V==="__proto__")throw new e("The key __proto__ is not allowed");Z.key=this.mapKeyConverter(V),Z.type=eV;continue $}else if(Z.map[Z.key]=V,Z.readCount++,Z.readCount===Z.size)V=Z.map,Q.release(Z);else{Z.key=null,Z.type=$$;continue $}}return V}}readHeadByte(){if(this.headByte===e0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=e0}readArraySize(){let $=this.readHeadByte();switch($){case 220:return this.readU16();case 221:return this.readU32();default:if($<160)return $-144;else throw new e(`Unrecognized array type byte: ${F$($)}`)}}pushMapState($){if($>this.maxMapLength)throw new e(`Max length exceeded: map length (${$}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState($)}pushArrayState($){if($>this.maxArrayLength)throw new e(`Max length exceeded: array length (${$}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState($)}decodeString($,V){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String($,V);return this.decodeBinary($,V)}decodeUtf8String($,V){if($>this.maxStrLength)throw new e(`Max length exceeded: UTF-8 byte length (${$}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+V+$)throw tV;let Q=this.pos+V,Z;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached($))Z=this.keyDecoder.decode(this.bytes,Q,$);else Z=dV(this.bytes,Q,$);return this.pos+=V+$,Z}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===$$;return!1}decodeBinary($,V){if($>this.maxBinLength)throw new e(`Max length exceeded: bin length (${$}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining($+V))throw tV;let Q=this.pos+V,Z=this.bytes.subarray(Q,Q+$);return this.pos+=V+$,Z}decodeExtension($,V){if($>this.maxExtLength)throw new e(`Max length exceeded: ext length (${$}) > maxExtLength (${this.maxExtLength})`);let Q=this.view.getInt8(this.pos+V),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 $=this.view.getUint8(this.pos);return this.pos++,$}readI8(){let $=this.view.getInt8(this.pos);return this.pos++,$}readU16(){let $=this.view.getUint16(this.pos);return this.pos+=2,$}readI16(){let $=this.view.getInt16(this.pos);return this.pos+=2,$}readU32(){let $=this.view.getUint32(this.pos);return this.pos+=4,$}readI32(){let $=this.view.getInt32(this.pos);return this.pos+=4,$}readU64(){let $=aV(this.view,this.pos);return this.pos+=8,$}readI64(){let $=R$(this.view,this.pos);return this.pos+=8,$}readU64AsBigInt(){let $=this.view.getBigUint64(this.pos);return this.pos+=8,$}readI64AsBigInt(){let $=this.view.getBigInt64(this.pos);return this.pos+=8,$}readF32(){let $=this.view.getFloat32(this.pos);return this.pos+=4,$}readF64(){let $=this.view.getFloat64(this.pos);return this.pos+=8,$}}function c$($,V){return new U$(V).decode($)}class C0{listeners=new Map;addEventListener($,V){let Q=this.listeners.get($);if(!Q)Q=new Set,this.listeners.set($,Q);return Q.add(V),()=>{this.removeEventListener($,V)}}removeEventListener($,V){let Q=this.listeners.get($);if(Q){if(Q.delete(V),Q.size===0)this.listeners.delete($)}}emit($,V){let Q=this.listeners.get($);if(Q){let Z=Array.from(Q);for(let J of Z)J(V)}}emitAll($){let V=Array.from(this.listeners.keys());for(let Q of V)this.emit(Q,$)}}class K0{getter;static eventName="update";emitter;constructor($){this.getter=$;this.emitter=new C0}get=()=>this.getter();async emit(){let $=await this.getter();queueMicrotask(()=>this.emitter.emit(K0.eventName,$))}listen($){return this.emitter.addEventListener(K0.eventName,$),()=>{this.emitter.removeEventListener(K0.eventName,$)}}}var T0=64;var VQ=32,D0=8;var O$=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 U($){return[$,0]}function M($){return[void 0,$]}function LZ($){if($<0)console.info("N",$),console.trace();if(typeof $!=="bigint")$=BigInt($);if($<0n)return M(10);let V=[];while($>0n){let Q=Number($&0x7fn);if($>>=7n,$>0n)V.push(Q|128);else V.push(Q)}if(V.length===0)return U(new Uint8Array([0]));if(V.length>8)return M(26);return U(new Uint8Array(V))}function mZ($,V=0){let Q=0n,Z=0,J=V;while(!0){if(J>=$.length)return M(14);let W=$[J++];if(W===void 0)return M(14);if(Q|=BigInt(W&127)<<BigInt(Z),(W&128)===0){if(J-V>8)return M(26);return U({value:Q>0x1fffffffffffffn?Q:Number(Q),bytesRead:J-V})}if(Z+=7,Z>=56)return M(26)}}class x{data;pos=0;constructor($){this.data=$}static async fromResponse($){let V=await $.arrayBuffer(),Q=new Uint8Array(V);return new x(Q)}readBigInt(){if(this.pos+8>this.data.length)return M(7);let $=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,U($)}readDate(){let[$,V]=this.readVarInt();if(V!==0)return M(V);return U(new Date($))}readVarInt(){let[$,V]=mZ(this.data,this.pos);if(V!==0)return M(V);this.pos+=$.bytesRead;let Q=$.value;return U(typeof Q==="bigint"?Number(Q):Q)}readVarString(){let[$,V]=this.readVarInt();if(V!==0)return M(V);let[Q,Z]=this.readBytes($);if(Z!==0)return M(Z);let J=new TextDecoder().decode(Q);return U(J)}readBytes($){if($<0)return M(10);if(this.pos+$>this.data.length)return M(23);let V=this.data.slice(this.pos,this.pos+$);return this.pos+=$,U(V)}readVarBytes(){let[$,V]=this.readVarInt();if(V!==0)return M(V);return this.readBytes($)}readStruct($){return $.decode(this)}readStructs($){let V=[];while(!this.done()){let[Q,Z]=this.readStruct($);if(Z!==0)return M(Z);V.push(Q)}return U(V)}readBytesSeq($){let V=[];while(!this.done()){let[Q,Z]=this.readBytes($);if(Z!==0)return M(Z);V.push(Q)}return U(V)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class B{parts=[];writeBigInt($){let V=new Uint8Array(8);new DataView(V.buffer).setBigUint64(0,$,!1),this.parts.push(V)}writeDate($){let V=$.getTime();return this.writeVarInt(V)}writeVarInt($){let[V,Q]=LZ($);if(Q!==0)return Q;return this.parts.push(V),0}writeVarString($){let V=new TextEncoder().encode($),Q=this.writeVarInt(V.length);if(Q!==0)return Q;return this.writeBytes(V),0}prependBytes($){this.parts.unshift($)}writeBytes($){this.parts.push($)}writeVarBytes($){let V=this.writeVarInt($.length);if(V!==0)return V;return this.writeBytes($),0}writeStruct($,V){return $.encode(this,V)}writeStructs($,V){for(let Q of V){let Z=this.writeStruct($,Q);if(Z!==0)return Z}return 0}writeBytesSeq($){for(let V of $)this.writeBytes(V)}result(){let $=this.parts.reduce((Z,J)=>Z+J.length,0),V=new Uint8Array($),Q=0;for(let Z of this.parts)V.set(Z,Q),Q+=Z.length;return V}*scan(){for(let $ of this.parts)yield $}}async function d$($,V,Q){let Z=new B,J=Z.writeDate(V);if(J!==0)return M(J);let W=Z.result(),Y=await Q.signEd25519(W,$.privateKey);return U({pubKey:$.publicKey,sig:Y,timestamp:V})}async function A0($,V,Q){let Z=Q.now().getTime(),J=$.timestamp.getTime();if(Math.abs(Z-J)>QQ)return 4;let Y=new B;Y.writeDate($.timestamp);let X=Y.result();if(!await V.checkSigEd25519($.sig,X,$.pubKey))return 3;return 0}var r={encode($,V){let Q=$.writeVarBytes(V.id);if(Q!==0)return Q;let Z=$.writeDate(V.ts);if(Z!==0)return Z;return 0},decode($){let[V,Q]=$.readVarBytes();if(Q!==0)return M(Q);let[Z,J]=$.readDate();if(J!==0)return M(J);return U({id:V,ts:Z})}};function h0($){let V=new B,Q=V.writeStruct(r,$);if(Q!==0)return M(Q);let Z=V.result();return U(Z)}async function SZ($){return h0({id:$,ts:new Date(0)})}var X0={encode($,V){let Q=$.writeVarBytes(V.eid);if(Q!==0)return Q;let Z=$.writeVarInt(V.off);if(Z!==0)return Z;let J=$.writeVarInt(V.ctr);if(J!==0)return J;let W=$.writeVarInt(V.len);if(W!==0)return W;if(V.hsh)$.writeBytes(V.hsh);return 0},decode($){let[V,Q]=$.readVarBytes();if(Q!==0)return M(Q);let Z=new x(V),[,J]=r.decode(Z);if(J!==0)return M(J);let[W,Y]=$.readVarInt();if(Y!==0)return M(Y);let[X,I]=$.readVarInt();if(I!==0)return M(I);let[K,G]=$.readVarInt();if(G!==0)return M(G);let N;if(K>0){let[w,z]=$.readBytes(O$);if(z!==0)return M(z);N=w}return U({eid:V,off:W,ctr:X,len:K,hsh:N})}};function a($){return Array.from($).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}function _0($){if($.length%2!==0)throw Error("Invalid hex string");let V=new Uint8Array($.length/2);for(let Q=0;Q<$.length;Q+=2)V[Q/2]=Number.parseInt($.substr(Q,2),16);return V}function s($,V){if($===V)return!0;if($.byteLength!==V.byteLength)return!1;return $.every((Q,Z)=>Q===V[Z])}var L;if(typeof Uint8Array.prototype.toBase64==="function")L=($)=>$.toBase64();else L=($)=>btoa(String.fromCharCode(...$));var I0;if(typeof Uint8Array.fromBase64==="function")I0=($)=>Uint8Array.fromBase64($);else I0=($)=>Uint8Array.from(atob($),(V)=>V.charCodeAt(0));function V$($,V){let Q=new Uint8Array($.length+V.length);return Q.set($,0),Q.set(V,$.length),Q}function JQ($,V,Q){return Q.checkSigEd25519($.sig,$.headCph,V)}async function o$($,V,Q){let Z=V$(V.privateKey,$);return(await Q.blake3(Z)).slice(0,D0)}async function WQ($,V,Q,Z){let J;if($.bod&&$.len>0)J=await Q.blake3($.bod);let W=new B,Y=X0.encode(W,{...$,hsh:J});if(Y!==0)return M(Y);let X=W.result(),I=await o$(X,V,Q),K=await Z.deriveFromKDM(I),G=await Q.encryptXSalsa20Poly1305Combined(X,K),N=$.bod?await Q.encryptXSalsa20Poly1305Combined($.bod,K):new Uint8Array(0),w=await Q.signEd25519(G,V.privateKey);return U({sig:w,kdm:I,headCph:G,bodyCph:N})}async function a$($,V,Q,Z,J){let W=new x($),[Y,X]=X0.decode(W);if(X!==0)return M(14);let I;try{I=V&&V.length>0?await Z.decryptXSalsa20Poly1305Combined(V,Q):void 0}catch{return M(20)}let K=Y.hsh&&I===void 0,G=Y.hsh===void 0&&I!==void 0;if(K||G)return M(19);if(Y.hsh&&I){let w=await Z.blake3(I);if(!s(w,Y.hsh))return M(19)}let N=J??await Z.blake3($);return U({msgHead:Y,bod:I,headHash:N})}class R0{now(){return new Date}}function YQ($,V,Q,Z){let J=V.getTime()-$.getTime(),W=Q.getTime()-Z.getTime();return(J+W)/2}var Q$={encode($,V){if($.writeVarInt(V.quota),V.quota>0){if(V.usage===void 0)return 9;$.writeVarInt(V.usage)}return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return M(Q);let Z;if(V>0){let[J,W]=$.readVarInt();if(W!==0)return M(W);Z=J}return U({quota:V,usage:Z})}};var s$={encode($,V){$.writeBytes(new Uint8Array([V.status]));let Q=$.writeDate(V.timeRcvd);if(Q!==0)return Q;let Z=$.writeDate(V.timeSent);if(Z!==0)return Z;let J=$.writeVarInt(V.subscription.term);if(J!==0)return J;let W=$.writeVarInt(V.subscription.elapsed);if(W!==0)return W;let Y=$.writeStruct(Q$,V.subscription.stat);if(Y!==0)return Y;let X=$.writeStruct(Q$,V.subscription.dyn);if(X!==0)return X;return 0},decode($){let[V,Q]=$.readBytes(1);if(Q!==0)return M(Q);let Z=V[0],[J,W]=$.readDate();if(W!==0)return M(W);let[Y,X]=$.readDate();if(X!==0)return M(X);let[I,K]=$.readVarInt();if(K!==0)return M(K);let[G,N]=$.readVarInt();if(N!==0)return M(N);let[w,z]=$.readStruct(Q$);if(z!==0)return M(z);let[F,R]=$.readStruct(Q$);if(R!==0)return M(R);return U({status:Z,timeRcvd:J,timeSent:Y,subscription:{term:I,elapsed:G,stat:w,dyn:F}})}};async function t$($,V,Q){let{crypto:Z,enclave:J}=$,W=await J.derive(V,Q);return await Z.deriveEd25519KeyPair(W)}var e$={encode($,V){let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;let Z=$.writeVarInt(V.seq);if(Z!==0)return Z;return 0},decode($){let[V,Q]=$.readVarBytes();if(Q!==0)return M(Q);let[Z,J]=$.readVarInt();if(J!==0)return M(J);return U({headCph:V,seq:Z})}};var Z0={encode($,V){$.writeBytes(V.pubKey),$.writeBytes(V.sig);let Q=$.writeDate(V.timestamp);if(Q!==0)return Q;return 0},decode($){let[V,Q]=$.readBytes(VQ);if(Q!==0)return M(Q);let[Z,J]=$.readBytes(T0);if(J!==0)return M(J);let[W,Y]=$.readDate();if(Y!==0)return M(Y);return U({pubKey:V,sig:Z,timestamp:W})}};var XQ={async encodeReq($,V,Q,Z,J){let W=J.writeStruct(Z0,Q);if(W!==0)return W;for(let Y of Z)J.writeVarInt(Y);return 0},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W}=$,[Y,X]=V.readStruct(Z0);if(X!==0)return X;let I=await A0(Y,J,Z);if(I!==0)return I;let{pubKey:K}=Y,[G,N]=await W.hasUser(K);if(N!==0)return N;if(!G)return 5;let[w,z]=V.readVarInt();if(z!==0)return z;if(!V.done())return 8;let[F,R]=await W.listHeads(K,w);if(R!==0)return R;return Q.writeStructs(e$,F)},decodeResp($){return $.readStructs(e$)}};var $V={encode($,V){$.writeVarInt(V.seq);let Q=$.writeVarBytes(V.bodyCph);if(Q!==0)return Q;return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return M(Q);let[Z,J]=$.readVarBytes();if(J!==0)return M(J);return U({seq:V,bodyCph:Z})}};var IQ={async encodeReq($,V,Q,Z,J){let W=J.writeStruct(Z0,Q);if(W!==0)return W;for(let Y of Z){let X=J.writeVarInt(Y);if(X!==0)return X}return 0},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W}=$,[Y,X]=V.readStruct(Z0);if(X!==0)return X;let I=await A0(Y,J,Z);if(I!==0)return I;let{pubKey:K}=Y,[G,N]=await W.hasUser(K);if(N!==0)return N;if(!G)return 5;let w=[];while(!V.done()){let[R,O]=V.readVarInt();if(O!==0)return O;w.push(R)}console.info(`PULL: ${w.length} bags`);let[z,F]=await W.getBodies(K,w);if(F!==0)return F;if(!z)return 17;for(let{seq:R,bodyCph:O}of z){let H={seq:R,bodyCph:O},P=Q.writeStruct($V,H);if(P!==0)return P}return 0},decodeResp($){return $.readStructs($V)}};var VV={encode($,V){$.writeBytes(V.sig),$.writeBytes(V.kdm);let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;let Z=$.writeVarBytes(V.bodyCph);if(Z!==0)return Z;return 0},decode($){let[V,Q]=$.readBytes(T0);if(Q!==0)return M(Q);let[Z,J]=$.readBytes(D0);if(J!==0)return M(J);let[W,Y]=$.readVarBytes();if(Y!==0)return M(Y);let[X,I]=$.readVarBytes();if(I!==0)return M(I);return U({sig:V,kdm:Z,headCph:W,bodyCph:X})}};var q$={encode($,V){let Q=$.writeVarInt(V.seq);if(Q!==0)return Q;let Z=$.writeVarBytes(V.headCph);if(Z!==0)return Z;let J=V.bodyCph?V.bodyCph.length:0,W=$.writeVarInt(J);if(W!==0)return W;if(J>0){if(!V.bodyCph)return 10;$.writeBytes(V.bodyCph)}return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return M(Q);let[Z,J]=$.readVarBytes();if(J!==0)return M(J);let[W,Y]=$.readVarInt();if(Y!==0)return M(Y);let X;if(W>0){let[I,K]=$.readBytes(W);if(K!==0)return M(K);X=I}return U({seq:V,headCph:Z,bodyCph:X})}};var H$={encode($,V){$.writeBytes(V.sig),$.writeBytes(V.kdm);let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;return 0},decode($){let[V,Q]=$.readBytes(T0);if(Q!==0)return M(Q);let[Z,J]=$.readBytes(D0);if(J!==0)return M(J);let[W,Y]=$.readVarBytes();if(Y!==0)return M(Y);return U({sig:V,kdm:Z,headCph:W})}};var P$={encode($,V){if($.writeVarInt(V.idx),$.writeBytes(new Uint8Array([V.status])),V.status===0)$.writeVarInt(V.seq);return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return M(Q);let[Z,J]=$.readBytes(1);if(J!==0)return M(J);let W=Z[0];if(W!==0)return U({idx:V,status:W});let[Y,X]=$.readVarInt();if(X!==0)return M(X);return U({idx:V,status:W,seq:Y})}};var KQ={async encodeReq($,V,Q,Z,J){let W=J.writeStruct(Z0,Q);if(W!==0)return W;let Y=J.writeStructs(VV,Z);if(Y!==0)return Y;return 0},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W,notifier:Y}=$,[X,I]=V.readStruct(Z0);if(I!==0)return I;let K=await A0(X,J,Z);if(K!==0)return K;let{pubKey:G}=X,[N,w]=await W.hasUser(G);if(w!==0)return w;if(!N)return 5;let[z,F]=V.readStructs(VV);if(F!==0)return F;console.info(`PUSH: ${z.length} bags`);let R=[],O=[];for(let q=0;q<z.length;q++){let A=z[q];if(!await JQ(A,G,J)){let f={idx:q,status:3},E=Q.writeStruct(P$,f);if(E!==0)return E;continue}R.push(q),O.push(A)}let[H,P]=await W.setBags(G,O);if(P!==0)return P;if(!H||H.length!==O.length)return 17;let D=[];for(let q=0;q<O.length;q++){let A=O[q],m=R[q],f=H[q],E=new B,S=E.writeStruct(H$,A);if(S!==0)return S;let k=E.result(),C={seq:f,headCph:k};if(z.length===1&&A.bodyCph.length<=ZQ)C.bodyCph=A.bodyCph;D.push(C);let g={idx:m,status:0,seq:f},i=Q.writeStruct(P$,g);if(i!==0)return i}if(D.length>0){let q=new B,A=q.writeStructs(q$,D);if(A!==0)return A;let m=q.result();await Promise.resolve(Y.push(G,m))}return 0},decodeResp($){return $.readStructs(P$)}};var GQ={async encodeReq($,V,Q,Z,J){return J.writeStruct(Z0,Q)},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W}=$,[Y,X]=V.readStruct(Z0);if(X!==0)return X;let I=await A0(Y,J,Z);if(I!==0)return I;let{pubKey:K}=Y;if(!V.done())return 8;let[G,N]=await W.addUser(K);if(N!==0)return N;return 0},decodeResp($){return U(void 0)}};class QV{url;websocket;constructor($){this.url=$}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 W=new B;W.writeStruct(Z0,$);let Y=W.result(),X=a(Y);return J.searchParams.set("t",X),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=(I)=>{let K=new Uint8Array(I.data);V(K)},this.websocket.onerror=(I)=>{console.log(`ERROR: ${JSON.stringify(I)}`),this.websocket=void 0,Q()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var c={user:{path:"/user",endpoint:GQ,name:0},push:{path:"/push",endpoint:KQ,name:2},peek:{path:"/peek",endpoint:XQ,name:1},pull:{path:"/pull",endpoint:IQ,name:3}},EZ={0:c.user,2:c.push,1:c.peek,3:c.pull},xX={[c.user.path]:c.user,[c.push.path]:c.push,[c.peek.path]:c.peek,[c.pull.path]:c.pull};class ZV{url;listener;constructor($){this.url=$;this.listener=new QV($)}async call($,V){let{path:Q}=EZ[$],Z=new URL(Q,this.url);try{return await xZ(Z,V)}catch{return M(25)}}}var C$=($)=>{return new ZV($.handle)};async function xZ($,V){let Q=await fetch($,{method:"POST",body:V.result().slice()});if(!Q.ok)return M(24);let Z=await x.fromResponse(Q);return U(Z)}class T${enclave;crypto;host;clock;transport;updateHostMeta;constructor($,V,Q,Z,J,W){this.enclave=$;this.crypto=V;this.host=Q;this.clock=Z;this.transport=J;this.updateHostMeta=W}async call($,V){let{clock:Q,crypto:Z,transport:J}=this,{endpoint:W,name:Y}=$,X=await this.keys(),I=Q.now(),[K,G]=await d$(X,I,Z);if(G!==0)return M(G);let N=new B,w=await W.encodeReq(this,X,K,V,N);if(w!==0)return M(w);let z=Q.now(),[F,R]=await J.call(Y,N),O=Q.now();if(R!==0)return M(R);let[H,P]=F.readStruct(s$);if(P!==0)return M(P);if(H.status!==0)return M(H.status);let q={clockOffset:YQ(z,H.timeRcvd,H.timeSent,O),subscription:H.subscription},A=await this.updateHostMeta(q);if(A!==0)return M(A);return W.decodeResp(F)}keys=()=>{let{host:$}=this;return t$(this,$.label,$.idx)};seal=async($)=>{let{crypto:V,enclave:Q}=this,Z=await this.keys();return WQ($,Z,V,Q)};register=()=>this.call(c.user,[]);peek=($)=>this.call(c.peek,[$]);push=($)=>this.call(c.push,$);pull=($)=>this.call(c.pull,$);listen=async($,V,Q)=>{let{clock:Z,crypto:J,host:W,transport:Y}=this,{listener:X}=Y,I=await t$(this,W.label,W.idx),K=Z.now(),[G,N]=await d$(I,K,J);if(N!==0)return N;return await X.connect(G,$,V,Q)};isConnected(){let $=this.transport?.listener;if($&&typeof $.connected==="function")return $.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var JV={encode($,V){let Q=$.writeVarString(V.lbl);if(Q!==0)return Q;let Z=$.writeVarInt(V.idx);if(Z!==0)return Z;let J=$.writeVarInt(V.num);if(J!==0)return J;return $.writeBytes(V.hsh),$.writeBytes(V.sig),0},decode($){let[V,Q]=$.readVarString();if(Q!==0)return M(Q);let[Z,J]=$.readVarInt();if(J!==0)return M(J);let[W,Y]=$.readVarInt();if(Y!==0)return M(Y);let[X,I]=$.readBytes(O$);if(I!==0)return M(I);let[K,G]=$.readBytes(T0);if(G!==0)return M(G);return U({lbl:V,idx:Z,num:W,hsh:X,sig:K})}};var WV={encode($,V){let Q=$.writeStruct(JV,V.head);if(Q!==0)return Q;let Z=$.writeVarBytes(V.indexEnc);if(Z!==0)return Z;let J=$.writeVarBytes(V.bodyEnc);if(J!==0)return J;return 0},decode($){let[V,Q]=$.readStruct(JV);if(Q!==0)return M(Q);let[Z,J]=$.readVarBytes();if(J!==0)return M(J);let[W,Y]=$.readVarBytes();if(Y!==0)return M(Y);return U({head:V,indexEnc:Z,bodyEnc:W})}};var YV={encode($,V){$.writeBytes(V.kdm);let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;let Z=$.writeVarInt(V.lenBody);if(Z!==0)return Z;if(V.lenBody>0&&V.offBody!==void 0){let J=$.writeVarInt(V.offBody);if(J!==0)return J}return 0},decode($){let[V,Q]=$.readBytes(D0);if(Q!==0)return M(Q);let[Z,J]=$.readVarBytes();if(J!==0)return M(J);let[W,Y]=$.readVarInt();if(Y!==0)return M(Y);let X;if(W>0){let[I,K]=$.readVarInt();if(K!==0)return M(K);X=I}return U({kdm:V,headCph:Z,lenBody:W,offBody:X})}};async function MQ($,V,Q,Z,J){let W=await J.derive($,V),Y=await Z.deriveEd25519KeyPair(W),X=new B,I=new B,K=0,G=0;for(let P of Q){let D=new B,q=D.writeStruct(X0,P.head);if(q!==0)return M(q);let A=D.result(),m=await o$(A,Y,Z),f=await J.deriveFromKDM(m),E=await Z.encryptXSalsa20Poly1305Combined(A,f),S=P.body?await Z.encryptXSalsa20Poly1305Combined(P.body,f):new Uint8Array(0),k=P.head.len>0&&P.head.hsh!==void 0?S.length:0,C={kdm:m,headCph:E,lenBody:k,offBody:k>0?G:void 0},g=X.writeStruct(YV,C);if(g!==0)return M(g);if(P.body)I.writeBytes(S),G+=S.length;K++}let N=I.result(),w=X.result(),z=await Z.blake3(w),F=await Z.signEd25519(z,Y.privateKey),R={lbl:$,idx:V,num:K,hsh:z,sig:F},O=new B;O.writeStruct(WV,{head:R,indexEnc:w,bodyEnc:N});let H=O.result();return U(H)}async function NQ($,V,Q){let[Z,J]=WV.decode(new x($));if(J!==0)return M(J);let{head:W,indexEnc:Y,bodyEnc:X}=Z,I=await Q.derive(W.lbl,W.idx),K=await V.deriveEd25519KeyPair(I);if(!await V.checkSigEd25519(W.sig,W.hsh,K.publicKey))return M(3);let N=await V.blake3(Y);if(!s(N,W.hsh))return M(19);let w=new x(Y),z=[];for(let R=0;R<W.num;R++){let[O,H]=w.readStruct(YV);if(H!==0)return M(H);z.push(O)}if(z.length!==W.num)return M(14);let F=[];for(let R of z){let O=await Q.deriveFromKDM(R.kdm),H=await V.decryptXSalsa20Poly1305Combined(R.headCph,O),[P,D]=X0.decode(new x(H));if(D!==0)return M(D);let q;if(R.lenBody>0&&R.offBody!==void 0){if(P.hsh===void 0)return M(14);let A=X.slice(R.offBody,R.offBody+R.lenBody);q=await V.decryptXSalsa20Poly1305Combined(A,O);let m=await V.blake3(q);if(!s(m,P.hsh))return M(19)}F.push({head:P,body:q})}return U(F)}async function wQ({now:$,bod:V,crypto:Q}){let Z=await Q.genRandomBytes(8),J=new B,W=J.writeStruct(r,{id:Z,ts:$});if(W!==0)return M(W);let Y=J.result();return D$({now:$,eid:Y,ctr:0,bod:V,crypto:Q})}async function D$({now:$,eid:V,ctr:Q,bod:Z,crypto:J}){let W=new x(V),[Y,X]=r.decode(W);if(X!==0)return M(X);let I=$.getTime()-Y.ts.getTime(),K,G=Z?.length??0;if(Z&&G>0)K=await J.blake3(Z);return U({eid:V,off:I,ctr:Q,len:G,hsh:K})}var CI=Symbol("EntityID");function RQ($){return"type"in $}var TI=Symbol("MasterSeed"),DI=Symbol("DerivationSeed"),AI=Symbol("PublicKey"),_I=Symbol("PrivateKey"),jI=Symbol("HostSpecificKeyPair"),LI=Symbol("Hash");function fZ($){if(!$)return!1;if(typeof $!=="object")return!1;if("body"in $===!1)return!1;if("type"in $===!1)return!1;return!0}function BZ($){if(!$.bod||$.bod.length===0){let Z={off:$.off,ctr:$.ctr,eid:$.eid};return U(Z)}let V=c$($.bod);if(fZ(V)===!1)return console.warn("msg body invalid",V),M(14);let Q={off:$.off,ctr:$.ctr,eid:$.eid,gid:V.gid,pid:V.pid,type:V.type,body:V.body};return U(Q)}class Z${applier;emitter=new C0;clearer;onDirtyEids;cacheDriven;peerIngest;constructor($,V,Q,Z){this.applier=$;this.clearer=V,this.onDirtyEids=Q,this.cacheDriven=Z?.cacheDriven??!1,this.peerIngest=Z?.peerIngest}apply=async($)=>{let V=[],Q=[];for(let X of $){let[I,K]=BZ(X);if(Q.push(K),K!==0)continue;V.push(I)}let{stats:Z,types:J,eids:W}=await this.applier(V),Y=[];for(let X=0;X<$.length;X++){let I=Q[X],K=Z[X];if(I!==0){Y.push(I);continue}if(K!==0){Y.push(K);continue}Y.push(0)}if(!this.cacheDriven)for(let X of J)this.emitter.emit(X,null);if(W.length>0)this.onDirtyEids?.(W);return Y};clear=async()=>{let $=await this.clearer();if($!==0)return $;return this.emitter.emitAll(null),$};notify=($)=>{for(let V of $)this.emitter.emit(V,null)};refresh=async($)=>{if(this.peerIngest){await this.peerIngest($);return}};on=($,V)=>{this.emitter.addEventListener($,V)};off=($,V)=>{this.emitter.removeEventListener($,V)}}var XV={apply:async function($){return $.map(()=>0)},clear:async function(){return 0},notify:function($){},refresh:async function($){},on:function($,V){},off:function($,V){}};var y="entities",A$="entity_type_created_at",IV="entity_type_updated_at",KV="entity_type_group_id",GV="entity_type_parent_id";function kZ($){let V={bod:$.body,crd:$.createdAt,...$.ctr!==0?{ctr:$.ctr}:{},eid:L($.eid),gid:$.gid,pid:$.pid?L($.pid):void 0,typ:$.type,upd:$.updatedAt};if(V.gid===void 0)delete V.gid;if(V.pid===void 0)delete V.pid;if(V.ctr===void 0)delete V.ctr;return V}function l0($){return{body:$.bod,createdAt:$.crd,updatedAt:$.upd,ctr:$.ctr??0,type:$.typ,eid:I0($.eid),gid:$.gid,pid:$.pid?I0($.pid):void 0}}class MV{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(y))Z.createObjectStore(y,{keyPath:"eid",autoIncrement:!1});let W=J.objectStore(y);if(!W.indexNames.contains(A$))W.createIndex(A$,["typ","crd"],{unique:!1});if(!W.indexNames.contains(IV))W.createIndex(IV,["typ","upd"],{unique:!1});if(!W.indexNames.contains(KV))W.createIndex(KV,["typ","gid"],{unique:!1});if(!W.indexNames.contains(GV))W.createIndex(GV,["typ","pid"],{unique:!1})},Q.onsuccess=()=>$(Q.result),Q.onerror=()=>V(Q.error)})}apply=async($)=>{let V=new Set,Q=[];if(!this.db)return{stats:$.map(()=>16),types:V,eids:Q};let Z=this.db.transaction(y,"readwrite"),J=Z.objectStore(y);return new Promise((W)=>{let Y=Array($.length).fill(0);if($.length<1){W({stats:[],types:V,eids:Q});return}Z.oncomplete=()=>{W({stats:Y,types:V,eids:Q})},Z.onerror=()=>{for(let I=0;I<Y.length;I++)if(Y[I]===void 0)Y[I]=18;W({stats:Y,types:V,eids:Q})};let X=new Map;for(let I=0;I<$.length;I++){let K=$[I],G=L(K.eid),N={op:K,index:I},w=X.get(G);if(w)w.push(N);else X.set(G,[N])}for(let[I,K]of X){if(K.length<1)continue;let G=J.get(I);G.onsuccess=()=>{let N=G.result,w=N?l0(N):void 0,z=!1;for(let{op:F,index:R}of K){let[O,H]=r0(w,F);if(H!==0){Y[R]=H;continue}if(z=!0,O)V.add(O.type);else if(w)V.add(w.type);w=O}if(z)Q.push(K[0].op.eid);if(w){let F=kZ(w),R=J.put(F);R.onerror=(O)=>{O.preventDefault();for(let{index:H}of K)Y[H]=18}}else{let F=J.delete(I);F.onerror=()=>{for(let{index:R}of K)Y[R]=18}}},G.onerror=()=>{for(let{index:N}of K)Y[N]=18}}})};async clear(){if(!this.db)return 16;let $=this.db.transaction(y,"readwrite"),V=$.objectStore(y);return new Promise((Q)=>{$.oncomplete=()=>Q(0),$.onerror=()=>Q(18),V.clear()})}async getEnt($){if(!this.db)return M(16);let V=L($),Z=this.db.transaction(y,"readonly").objectStore(y);return new Promise((J)=>{let W=Z.get(V);W.onsuccess=()=>{let Y=W.result;if(!Y)J(U(void 0));else{let X=l0(Y);J(U(X))}},W.onerror=()=>J(M(18))})}async getAllOfTypeUpdatedBetween($,V,Q){if(!this.db)return M(16);let J=this.db.transaction(y,"readonly").objectStore(y).index(IV);return new Promise((W)=>{let Y=J.getAll(IDBKeyRange.bound([$,V],[$,Q]));Y.onsuccess=()=>{let X=Y.result;W(U(X.map(l0)))},Y.onerror=()=>W(M(18))})}async getGroupMembers($,V){if(!this.db)return M(16);let Z=this.db.transaction(y,"readonly").objectStore(y).index(KV);return new Promise((J)=>{let W=Z.getAll(IDBKeyRange.only([$,V]));W.onsuccess=()=>{let Y=W.result;J(U(Y.map(l0)))},W.onerror=()=>J(M(18))})}async getAllOfType($){if(!this.db)return M(16);let Q=this.db.transaction(y,"readonly").objectStore(y).index(A$);return new Promise((Z)=>{let J=Q.getAll(IDBKeyRange.bound([$],[$,[]]));J.onsuccess=()=>{let W=J.result;Z(U(W.map(l0)))},J.onerror=()=>Z(M(18))})}async getAllEntities($){if(!this.db)return M(16);if("pid"in $){let V=L($.pid),Z=this.db.transaction(y,"readonly").objectStore(y).index(GV);return new Promise((J)=>{let W=Z.getAll(IDBKeyRange.only([$.type,V]));W.onsuccess=()=>{let X=W.result.map(l0);J(U(X))},W.onerror=()=>J(M(18))})}else if("gid"in $)return await this.getGroupMembers($.type,$.gid);else if("updatedBetween"in $)return await this.getAllOfTypeUpdatedBetween($.type,$.updatedBetween.start,$.updatedBetween.end);return await this.getAllOfType($.type)}async getEntities($){let[V,Q]=await this.getAllEntities($);if(Q!==0)return M(Q);return U(V)}async countEntities({type:$}){if(!this.db)return M(16);let Q=this.db.transaction(y,"readonly").objectStore(y).index(A$);return new Promise((Z)=>{let J=IDBKeyRange.bound([$],[$,[]]),W=Q.count(J);W.onsuccess=()=>Z(U(W.result)),W.onerror=()=>Z(M(18))})}}async function zQ(){let $=new MV;return await $.init(),$}class _${ents=new Map;useIndex;byType=new Map;byTypePid=new Map;byTypeGid=new Map;constructor($=[],V){this.useIndex=V?.indexes!==!1;for(let Q of $)this.put(Q)}put($){let V=L($.eid),Q=this.ents.get(V);if(Q)this.unindex(V,Q);this.ents.set(V,$),this.index(V,$)}del($){let V=this.ents.get($);if(!V)return;this.unindex($,V),this.ents.delete($)}index($,V){if(!this.useIndex)return;let Q=this.byType.get(V.type);if(!Q)Q=new Map,this.byType.set(V.type,Q);if(Q.set($,V),V.pid){let Z=L(V.pid),J=this.byTypePid.get(V.type);if(!J)J=new Map,this.byTypePid.set(V.type,J);let W=J.get(Z);if(!W)W=new Map,J.set(Z,W);W.set($,V)}if(typeof V.gid==="string"){let Z=this.byTypeGid.get(V.type);if(!Z)Z=new Map,this.byTypeGid.set(V.type,Z);let J=Z.get(V.gid);if(!J)J=new Map,Z.set(V.gid,J);J.set($,V)}}unindex($,V){if(!this.useIndex)return;let Q=this.byType.get(V.type);if(Q){if(Q.delete($),Q.size===0)this.byType.delete(V.type)}if(V.pid){let Z=L(V.pid),J=this.byTypePid.get(V.type),W=J?.get(Z);if(W){if(W.delete($),W.size===0)J?.delete(Z)}if(J&&J.size===0)this.byTypePid.delete(V.type)}if(typeof V.gid==="string"){let Z=this.byTypeGid.get(V.type),J=Z?.get(V.gid);if(J){if(J.delete($),J.size===0)Z?.delete(V.gid)}if(Z&&Z.size===0)this.byTypeGid.delete(V.type)}}clearIndexes(){this.byType.clear(),this.byTypePid.clear(),this.byTypeGid.clear()}bucketList($){if(!$||$.size===0)return[];let V=[];for(let Q of $.values())V.push(Q);return V}async apply($){let V=new Set,Q=[],Z=[];for(let J of $){let W=L(J.eid),Y=this.ents.get(W),[X,I]=r0(Y,J);if(I!==0){Z.push(I);continue}if(X)V.add(X.type);else if(Y)V.add(Y.type);if(X)this.put(X);else this.del(W);Q.push(J.eid),Z.push(0)}return{stats:Z,types:V,eids:Q}}async clear(){return this.ents.clear(),this.clearIndexes(),0}async getEnt($){let V=L($),Q=this.ents.get(V);return U(Q)}async getAllEntities({type:$,gid:V,pid:Q,updatedBetween:Z}){if(this.useIndex){if(Q!==void 0){let W=L(Q);return U(this.bucketList(this.byTypePid.get($)?.get(W)))}if(V!==void 0)return U(this.bucketList(this.byTypeGid.get($)?.get(V)));if(Z!==void 0){let W=[],Y=this.byType.get($);if(Y){for(let X of Y.values())if(X.updatedAt>=Z.start&&X.updatedAt<=Z.end)W.push(X)}return U(W)}return U(this.bucketList(this.byType.get($)))}let J=[];if(Q!==void 0){for(let W of this.ents.values())if(W.type===$&&W.pid&&s(W.pid,Q))J.push(W)}else if(V!==void 0){for(let W of this.ents.values())if(W.type===$&&(typeof W.gid==="string"&&W.gid===V))J.push(W)}else if(Z!==void 0){for(let W of this.ents.values())if(W.type===$&&W.updatedAt>=Z.start&&W.updatedAt<=Z.end)J.push(W)}else for(let W of this.ents.values())if(W.type===$)J.push(W);return U(J)}async getEntities($){let[V,Q]=await this.getAllEntities($);if(Q!==0)return M(Q);return U(V)}async countEntities({type:$}){if(this.useIndex)return U(this.byType.get($)?.size??0);let V=0;for(let Q of this.ents.values())if(Q.type===$)V+=1;return U(V)}}async function NV($){let V=await zQ();if($?.cache===!1)return V;return new J$(V,void 0,{indexes:$?.indexes})}class J${mem;durable;warmed=new Set;listeners=new Set;chain=Promise.resolve();constructor($,V,Q){if(this.durable=$,this.mem=new _$(V??[],{indexes:Q?.indexes}),V)for(let Z of V)this.warmed.add(Z.type)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}emit($){if($.size<1)return;for(let V of this.listeners)V($)}run($){let V=this.chain.then($,$);return this.chain=V.then(()=>{return},()=>{return}),V}apply($){return this.run(async()=>{let V=yZ(this.mem,$);this.emit(V.types);let Q=await this.durable.apply($),{changed:Z,status:J}=await this.pullEids($.map((W)=>W.eid));this.emit(Z);for(let W of Q.types)this.warmed.add(W);if(J!==0)return{stats:$.map(()=>J),types:Q.types,eids:Q.eids};return Q})}clear(){return this.run(async()=>{let $=await this.durable.clear();if($!==0)return $;let V=this.mem.ents.size>0;return await this.mem.clear(),this.warmed.clear(),0})}ingestFromDurable($){return this.run(async()=>{let{changed:V,status:Q}=await this.pullEids($);return this.emit(V),Q})}async pullEids($){let V=new Set,Q=new Set;for(let Z of $){let J=L(Z);if(Q.has(J))continue;Q.add(J);let W=this.mem.ents.get(J),[Y,X]=await this.durable.getEnt(Z);if(X!==0)return{changed:V,status:X};if(Y){if(this.mem.put(Y),this.warmed.add(Y.type),!W||!gZ(W,Y)){if(V.add(Y.type),W&&W.type!==Y.type)V.add(W.type)}}else if(W)this.mem.del(J),V.add(W.type)}return{changed:V,status:0}}async warmType($){if(this.warmed.has($))return 0;let[V,Q]=await this.durable.getEntities({type:$});if(Q!==0)return Q;if(V)for(let Z of V){let J=L(Z.eid),W=this.mem.ents.get(J);if(!W||uZ(Z,W))this.mem.put(Z)}return this.warmed.add($),0}async getEnt($){let V=L($);if(this.mem.ents.has(V))return this.mem.getEnt($);return this.run(async()=>{if(this.mem.ents.has(V))return this.mem.getEnt($);let[Q,Z]=await this.durable.getEnt($);if(Z!==0)return M(Z);if(Q)this.mem.put(Q),this.warmed.add(Q.type);return U(Q)})}async getEntities($){if(!this.warmed.has($.type)){let V=await this.run(()=>this.warmType($.type));if(V!==0)return M(V)}return this.mem.getEntities($)}async countEntities({type:$}){if(!this.warmed.has($)){let V=await this.run(()=>this.warmType($));if(V!==0)return M(V)}return this.mem.countEntities({type:$})}}function gZ($,V){if($.ctr!==V.ctr)return!1;if($.updatedAt.getTime()!==V.updatedAt.getTime())return!1;if($.createdAt.getTime()!==V.createdAt.getTime())return!1;if($.type!==V.type)return!1;if($.gid!==V.gid)return!1;if(!s($.eid,V.eid))return!1;if(!vZ($.pid,V.pid))return!1;return iZ($.body,V.body)}function vZ($,V){if($===void 0&&V===void 0)return!0;if($===void 0||V===void 0)return!1;return s($,V)}function iZ($,V){if(Object.is($,V))return!0;if($ instanceof Uint8Array&&V instanceof Uint8Array)return s($,V);if($ instanceof Date&&V instanceof Date)return $.getTime()===V.getTime();try{return s(m0($),m0(V))}catch{return!1}}function uZ($,V){let Q=$.updatedAt.getTime(),Z=V.updatedAt.getTime();if(Q!==Z)return Q>Z;return $.ctr>V.ctr}function yZ($,V){let Q=new Set,Z=[];for(let J of V){let W=L(J.eid),Y=$.ents.get(W),[X,I]=r0(Y,J);if(I!==0){Z.push(I);continue}if(X)Q.add(X.type);else if(Y)Q.add(Y.type);if(X)$.put(X);else $.del(W);Z.push(0)}return{stats:Z,types:Q}}function j$($){if($ instanceof J$){let V=new Z$((Q)=>$.apply(Q),()=>$.clear(),void 0,{cacheDriven:!0,peerIngest:async(Q)=>{await $.ingestFromDurable(Q)}});return $.subscribe((Q)=>V.notify(Q)),V}return new Z$((V)=>$.apply(V),()=>$.clear())}function bZ($){return{eid:$.eid,ctr:$.ctr,updatedAt:$.updatedAt}}function wV($){let V=new x($.eid),[Q,Z]=V.readStruct(r);if(Z!==0)return M(Z);return U({eid:$.eid,ctr:$.ctr,updatedAt:new Date(Q.ts.getTime()+$.off)})}function r0($,V){let Q=new x(V.eid),[Z,J]=Q.readStruct(r);if(J!==0)return M(J);let W=new Date(Z.ts.getTime()+V.off);if($!==void 0&&W<=$.updatedAt)return M(15);if(RQ(V))return U({eid:V.eid,gid:V.gid,pid:V.pid,type:V.type,createdAt:Z.ts,updatedAt:W,ctr:V.ctr,body:V.body});else return U(void 0)}var nZ={getEnt:async()=>M(21),getEntities:async($)=>M(21),countEntities:async()=>M(21),apply:async($)=>({stats:$.map(()=>21),types:new Set,eids:[]}),clear:async()=>21};class L${inflight=null;again=!1;run($){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain($),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain($){try{this.again=!1;let V=await $();while(this.again)this.again=!1,V=await $();return V}finally{this.inflight=null}}}var m$=100;class W${timer=null;delayMs;work;tail=new L$;constructor($,V){this.delayMs=$<0?0:$,this.work=V}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($){let V=new x($.eid),[Q,Z]=r.decode(V);if(Z!==0)return;return Q.ts.getTime()+$.off}function pZ($,V){let Q=FQ($),Z=FQ(V);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 V.ctr-$.ctr}function Y$($,V){return $.slice().sort((Q,Z)=>pZ(V(Q),V(Z)))}var S0={phase:"idle"},X$=50;function RV($,V,Q){if($<=0||V<=0)return!1;if($===1||$===V)return!0;return $%Q===0}function S$($,V){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob($,V);return}let Q=URL.createObjectURL($),Z=document.createElement("a");Z.href=Q,Z.download=V,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(Q)}function UQ($,V,Q){let Z=[],J=[],W=0;for(let Y of $){let X=V(Y);if(J.length>0&&W+X>Q)Z.push(J),J=[],W=0;if(J.push(Y),W+=X,W>=Q)Z.push(J),J=[],W=0}if(J.length>0)Z.push(J);return Z}async function OQ($,V,Q){let Z=$.length;if(Z<1)return[];let J=Array(Z),W=0,Y=Math.min(Math.max(1,V),Z),X=async()=>{while(!0){let K=W;if(W+=1,K>=Z)return;J[K]=await Q($[K],K)}},I=[];for(let K=0;K<Y;K++)I.push(X());return await Promise.all(I),J}async function zV($,V,Q,Z){let J=new x($.headCph),[W,Y]=J.readStruct(H$);if(Y!==0)return M(Y);let{sig:X,kdm:I,headCph:K}=W;if(!await Z.checkSigEd25519(X,K,V.publicKey))return M(3);let N=await Q.deriveFromKDM(I),w;try{w=await Z.decryptXSalsa20Poly1305Combined(K,N)}catch{return M(20)}return U({kdm:I,headEnc:w})}var z0="f",j0="t",G0="e";function hZ($){return $===z0||$===j0||$===G0}function I$($){if($===!0||$===j0)return j0;if($===G0)return G0;return z0}function lZ($){return I$($.apld)===z0}function FV($){return $!==0&&$!==15&&$!==18&&$!==17}function E0($,V,Q){if($.apld=V,V===G0&&Q!==void 0)$.err=Q;else delete $.err}async function L0($,V,Q){let Z=I$(V.apld),J=V.body,W=J?.length??0,Y;if(J&&W>0)Y=await Q.blake3(J);let X={eid:V.eid,off:V.off??0,ctr:V.ctr??0,len:W,hsh:Y},I={hash:$,head:X,apld:Z};if(J!==void 0)I.body=J;if(Z===G0&&V.err!==void 0)I.err=V.err;return I}var UV=1048576,OV=1048576,rZ=64;function cZ($){return $.sig.length+$.kdm.length+$.headCph.length+$.bodyCph.length}async function dZ($,V,Q,Z,J){if(Z.length<1)return 0;let[W,Y]=await $.push(Z);if(Y!==0)return Y;if(!W)return 27;for(let I of W){if(I.status!==0){console.error("push err",I);continue}let K=J[I.idx];if(!K){console.error("no hash",I);continue}await V.uploads.deq(Q,[K])}let X=await V.hosts.get(Q);if(X){let I=X.lastSeq,K=I,G=[];for(let N of W)if(N.status===0)G.push(N.seq);G.sort((N,w)=>N-w);for(let N of G)if(N===I+1)I=N;if(I>K)await V.hosts.touch(Q,I)}return 0}async function qQ($,V){if(V.length<1)return U([]);let Q=new Map,Z=[];for(let X of V)Q.set(X.seq,X),Z.push(X.seq);let[J,W]=await $.pull(Z);if(W!==0)return M(W);if(!J)return M(27);let Y=[];for(let{seq:X,bodyCph:I}of J){let K=Q.get(X);if(!K)continue;Y.push({dl:K,bodyCph:I})}return U(Y)}async function oZ($,V,Q,Z){if(Z.length<1)return U({parts:[],hashes:[]});let J=[],W=[],Y=[],X=new Map;for(let{dl:K,bodyCph:G}of Z){let{head:N,kdm:w,seq:z,host:F}=K,[R,O]=await HQ(K,Q);if(O!==0||!R){let S=X.get(F)??[];S.push(z),X.set(F,S);continue}let{headEnc:H,headEncHash:P}=R,D=await V.deriveFromKDM(w),[q,A]=await a$(H,G,D,Q,P);if(A!==0||!q){let S=X.get(F)??[];S.push(z),X.set(F,S);continue}let m={head:N,body:q.bod},f=q.headHash;Y.push({key:f,data:AQ(m)}),J.push(m),W.push(f);let E=X.get(F)??[];E.push(z),X.set(F,E)}let I=await $.messages.add(Y);for(let[K,G]of X)await $.downloads.deq(K,G);for(let K=0;K<I.length;K++){let G=I[K];if(G!==0&&G!==15)console.error("ERR storing",_[G],"for message",K)}return U({parts:J,hashes:W})}async function HQ($,V){let Q=$.headEnc;if(!Q){let J=new B,W=J.writeStruct(X0,$.head);if(W!==0)return M(W);Q=J.result()}if($.headEncHash)return U({headEnc:Q,headEncHash:$.headEncHash});let Z=await V.blake3(Q);return U({headEnc:Q,headEncHash:Z})}async function PQ($,V,Q){let Z=new Set;for(let Y of V)Z.add(L(Y));if(Z.size<1)return;let J=Array.from(await $.downloads.list());if(J.length<1)return;let W=new Map;for(let Y of J){let X;if(Y.headEncHash)X=L(Y.headEncHash);else{let[K,G]=await HQ(Y,Q);if(G!==0||!K)continue;X=L(K.headEncHash)}if(!Z.has(X))continue;let I=W.get(Y.host)??[];I.push(Y.seq),W.set(Y.host,I)}for(let[Y,X]of W)await $.downloads.deq(Y,X)}async function CQ({conn:$,store:V,enclave:Q,host:Z,crypto:J,onProgress:W,peekProgressEvery:Y,peekConcurrency:X}){let I=await $.keys(),K=[],[G,N]=await $.peek(Z.lastSeq);if(N!==0)return N;let w=G.length,z=Y??X$,F=X??rZ;if(W&&w>0)W({phase:"peek",host:Z.label,done:0,total:w});let R=0,O=await OQ(G,F,async(H)=>{let[P,D]=await zV(H,I,Q,J),q;if(D!==0||!P)q={ok:!1,seq:H.seq,stat:D};else{let A=await J.blake3(P.headEnc);q={ok:!0,seq:H.seq,kdm:P.kdm,headEnc:P.headEnc,headEncHash:A}}if(R+=1,W&&RV(R,w,z))W({phase:"peek",host:Z.label,done:R,total:w});return q});for(let H of O){if(!H.ok){console.error("peek: decrypting item head",H.stat);continue}if(await V.messages.has(H.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await V.uploads.deq(Z.label,[H.headEncHash]),await V.downloads.deq(Z.label,[H.seq]);continue}let D=new x(H.headEnc),[q,A]=D.readStruct(X0);if(A!==0){console.error("peek: reading item head",A);continue}K.push({kdm:H.kdm,head:q,seq:H.seq,host:Z.label,headEnc:H.headEnc,headEncHash:H.headEncHash})}if(await V.downloads.enq(K),G.length>0){let H=Math.max(...G.map((P)=>P.seq));await V.hosts.touch(Z.label,H)}if(W)W({phase:"peek",host:Z.label,done:w,total:w});return 0}async function TQ({conn:$,store:V,host:Q,maxPushBytes:Z,onProgress:J}){let W=Z??UV,Y=await V.uploads.list(Q.label),X=Y.length,I=0;if(J&&X>0)J({phase:"push",host:Q.label,done:0,total:X});let K=[],G=[],N=0,w=async()=>{if(K.length<1)return 0;let z=K.length,F=await dZ($,V,Q.label,K,G);if(K=[],G=[],N=0,F===0){if(I+=z,J)J({phase:"push",host:Q.label,done:I,total:X})}return F};for(let z of Y){let F=await V.messages.get(z);if(!F){I+=1;continue}let R={...F.head,bod:F.body},[O,H]=await $.seal(R);if(H!==0)return H;if(!O)return 12;let P=cZ(O);if(K.length>0&&N+P>W){let D=await w();if(D!==0)return D}if(K.push(O),G.push(z),N+=P,N>=W){let D=await w();if(D!==0)return D}}return w()}async function DQ({conn:$,store:V,enclave:Q,host:Z,crypto:J,maxPullBytes:W,onProgress:Y},X){let I=W??OV,K=await V.downloads.list(),G=Array.from(K).filter((O)=>O.host===Z.label);if(G.length<1)return 15;let N=Y$(G,(O)=>O.head),w=UQ(N,(O)=>O.head.len,I),z=N.length,F=0;if(Y)Y({phase:"pull",host:Z.label,done:0,total:z});let R=qQ($,w[0]);for(let O=0;O<w.length;O++){let[H,P]=await R;if(P!==0||!H)return P;if(F+=w[O].length,Y)Y({phase:"pull",host:Z.label,done:F,total:z});let D=w[O+1];if(D)R=qQ($,D);if(Y)Y({phase:"open",host:Z.label,done:F,total:z});let q=Y$(H,(m)=>m.dl.head),[,A]=await oZ(V,Q,J,q);if(A!==0)return A;if(X){if(Y)Y({phase:"exec",host:Z.label,done:F,total:z});await X()}}return 0}function AQ({head:$,body:V}){let Q={eid:$.eid,body:V,apld:z0};if($.off!==0)Q.off=$.off;if($.ctr!==0)Q.ctr=$.ctr;return Q}async function _Q($,{conn:V,store:Q,enclave:Z,host:J,crypto:W,onProgress:Y},X){let I=J.label,K=await V.keys(),G=new x($),[N,w]=G.readStructs(q$);if(w!==0){console.error("Failed decoding notif",_[w]);return}let z=!1,R=(await Q.hosts.get(I))?.lastSeq,O=[],H=!1;for(let q of N){let[A,m]=await zV({seq:q.seq,headCph:q.headCph},K,Z,W);if(m!==0){console.error("Failed decrypting notif",_[m]);continue}let f=await W.blake3(A.headEnc);if(await Q.messages.has(f))continue;let E=new x(A.headEnc),[S,k]=E.readStruct(X0);if(k!==0){console.error("Failed to parse head",_[k]);continue}if(!q.bodyCph&&S.len>0)H=!0,await Q.downloads.enq([{seq:q.seq,host:I,kdm:A.kdm,head:S,headEnc:A.headEnc,headEncHash:f}]);else O.push({...A,head:S,bodyCph:q.bodyCph,headEncHash:f});if(R===void 0||q.seq!==R+1)console.log("out of seq",q.seq,R),z=!0;else R=q.seq}if(R!==void 0)await Q.hosts.touch(J.label,R);let P=[];for(let q of O){let A=await Z.deriveFromKDM(q.kdm),[m,f]=await a$(q.headEnc,q.bodyCph,A,W);if(f!==0){console.error("Failed to open body",_[f]);continue}P.push({key:q.headEncHash,data:AQ({head:q.head,body:m.bod})})}let D=await Q.messages.add(P);for(let q=0;q<D.length;q++){let A=D[q];if(A!==0&&A!==15)console.error("ERR storing",_[A],"for message",q)}if(Y&&P.length>0)Y({phase:"open",host:J.label,done:P.length,total:P.length});if(z||H||P.length>0)X()}class x0{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new L$;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=X$;lastProgress=S0;scheduledSync;constructor($,V,Q,Z,J,W=!0,Y=UV,X=OV,I){this.clock=$;this.state=V;this.store=Q;this.transport=Z;this.crypto=J;this.forceSkewHandlingByDefault=W;this.onScheduleSync=I;this.maxPushBytes=Y,this.maxPullBytes=X,this.clientState=new K0(()=>this.getClientState()),this.xferState=new K0(()=>this.getXferState()),this.scheduledSync=new W$(m$,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(K){console.error("Debounced sync failed:",K)}})}emitProgress=($)=>{this.lastProgress=$,this.xferState.emit()};async setSeed($){await this.store.seed.save($),this.clientState.emit()}async getClientState(){let{store:$,connections:V}=this,Q=await $.seed.load(),Z=await $.hosts.list(),J=!1;for(let W of V.values())if(W.isConnected()){J=!0;break}return{hasSeed:Q!==void 0,hasHost:Array.from(Z).length>0,connected:J}}async getXferState(){let{uploads:$,downloads:V}=this.store,Q=await $.count();return{numDownloads:await V.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:W,body:Y}of $){let X=new B;X.writeStruct(X0,W);let I=X.result(),K=await this.crypto.blake3(I),G={eid:W.eid,body:Y,apld:z0};if(W.off!==0)G.off=W.off;if(W.ctr!==0)G.ctr=W.ctr;Q.push(K),Z.push({key:K,data:G})}await this.store.messages.add(Z),await PQ(this.store,Q,this.crypto);let J=await this.doApplyHashes(Q);if(V.enqueueUpload){let W=[];for(let Y=0;Y<Q.length;Y++){let X=J[Y];if(X===0||X===15)W.push(Q[Y])}if(W.length>0){let Y=await this.store.hosts.list();for(let X of Y)await this.store.uploads.enq(X.label,W);this.xferState.emit()}}if(V.triggerUpload)this.scheduleSync();return J}enqueueApplyJob($){let V=this.applyChain.then($,$);return this.applyChain=V.then(()=>{return},()=>{return}),V}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let $=await this.store.messages.list(z0);if($.length<1)return[];let V=Y$($,(Q)=>Q.head);return this.applyStored(V)}applyHashes=($)=>{return this.enqueueApplyJob(()=>this.doApplyHashes($))};async doApplyHashes($){let V=[];for(let J of $){let W=await this.store.messages.get(J);if(W)V.push(W)}let Q=await this.applyStored(V),Z=new Map;for(let J=0;J<V.length;J++)Z.set(L(V[J].hash),Q[J]??12);return $.map((J)=>Z.get(L(J))??13)}async applyStored($){if($.length<1)return[];let V=$.map((W)=>({...W.head,bod:W.body})),Q=await this.state.apply(V),Z=[],J=[];for(let W=0;W<$.length;W++){let Y=Q[W];if(Y===0||Y===15)Z.push($[W].hash);else if(Y!==void 0&&FV(Y))J.push({key:$[W].hash,err:Y})}if(Z.length>0)await this.store.messages.markApplied(Z);if(J.length>0)await this.store.messages.markFailed(J);return Q}async insertRaw($){let{clock:V,crypto:Q}=this,[Z,J]=await wQ({now:V.now(),bod:$,crypto:Q});if(J!==0)return M(J);let Y=(await this.apply([{head:Z,body:$}]))[0];if(Y!==0&&Y!==15)return M(Y??12);return U(Z)}async makeUpdate($,V){let{clock:Q,crypto:Z}=this,J=Q.now();if($.updatedAt.getTime()>J.getTime())return M(4);let W=$.ctr+1,[Y,X]=await D$({now:J,eid:$.eid,ctr:W,bod:V,crypto:Z});if(X!==0)return M(X);return U({head:Y,body:V})}async updateWithSkew($,V,Q){if(Q===!1)return M(4);let{clock:Z,crypto:J}=this,W=Z.now(),Y=new x($.eid),[X,I]=Y.readStruct(r);if(I!==0)return M(I);let K=$.updatedAt.getTime()-X.ts.getTime(),G={eid:$.eid,off:K+1,ctr:$.ctr+1,len:0},w=(await this.apply([{head:G,body:void 0}]))[0];if(w!==0&&w!==15)return M(w??12);if(V===void 0)return U(G);let[z,F]=h0({id:X.id,ts:W});if(F!==0)return M(F);let[R,O]=await D$({now:W,eid:z,ctr:0,bod:V,crypto:J});if(O!==0)return M(O);let P=(await this.apply([{head:R,body:V}]))[0];if(P!==0&&P!==15)return M(P??12);return U(R)}async updateRaw($,V,Q=this.forceSkewHandlingByDefault){if($.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 Y=(await this.doApply([Z]))[0];if(Y!==0&&Y!==15)return M(Y??12);return U(Z.head)})}async insert($){let{body:V,type:Q,gid:Z,pid:J}=$,Y=m0({body:V,type:Q,gid:Z,pid:J});return this.insertRaw(Y)}async update($){let{prior:V,body:Q,type:Z,gid:J,pid:W,force:Y}=$,I=m0({body:Q,type:Z,gid:J,pid:W});return this.updateRaw(V,I,Y??this.forceSkewHandlingByDefault)}async delete($){let V=$.force??!0;if("prior"in $)return this.updateRaw($.prior,void 0,V);let[Q,Z]=await this.revFromArchive($.eid);if(Z!==0)return M(Z);return this.updateRaw(Q,void 0,V)}async revFromArchive($){let V=await this.store.messages.last($);if(V)return wV(V.head);let Q=new x($),[Z,J]=Q.readStruct(r);if(J!==0)return M(J);return U({eid:$,ctr:-1,updatedAt:Z.ts})}async genEID($){let{clock:V,crypto:Q}=this,Z=V.now();if($!==void 0)return h0({id:$,ts:Z});let J=await Q.genRandomBytes(8);return h0({id:J,ts:Z})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:$,crypto:V,store:Q}=this,Z=await Q.seed.load();if(!Z)return 22;await this.drainApplyQueue();for(let[J,W]of $){let Y=await Q.hosts.get(J);if(!Y)continue;let X={conn:W,store:Q,enclave:Z,host:Y,crypto:V,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},I=await CQ(X);if(I!==0)return console.error(`Failed to peek: ${I}`),I;this.xferState.emit();let K=await TQ(X);if(K!==0)return console.error(`Failed to push: ${K}`),K;this.xferState.emit();let G=await DQ(X,async()=>{await this.drainApplyQueue()});if(G!==0&&G!==15)return console.error(`Failed to pull: ${G}`),G;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=S0,this.clientState.emit(),this.xferState.emit()}import=async($,V)=>{let{crypto:Q,store:Z}=this,J=V?.onProgress,W=await Z.seed.load();if(!W)return 22;console.time("import: decoding file...");let Y=await $.bytes(),[X,I]=await NQ(Y,Q,W);if(I!==0)return I;console.timeEnd("import: decoding file...");let K=0;while(K<X.length){let G=0,N=0,w=K;for(let R=K;R<X.length&&N<100&&G<102400;R++)G+=X[R].head.len,N++,w=R+1;let z=X.slice(K,w);console.time(`import: applying [${K}, ${w}]`);let F=await this.apply(z,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${K}, ${w}]`);for(let R=0;R<z.length;R++){let O=F[R];if(O!==0&&O!==15)console.warn(`failed to import msg ${K+R}: ${_[O]}`)}if(J)queueMicrotask(()=>J(w,X.length,0));this.emitProgress({phase:"import",done:w,total:X.length}),K=w}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:$,store:V}=this,Q=await V.seed.load();if(!Q)return M(22);let Z=await V.messages.list();return MQ("export",0,Z,$,Q)}async export($){let[V,Q]=await this.exportBytes();if(Q!==0)return Q;if(!V)return 12;let Z=new Blob([V.slice()]);return S$(Z,$),0}async link($,V=!0){if(await this.store.hosts.add($),this.clientState.emit(),V){let Q=await this.store.hosts.get($.label);if(Q)await this.connectToHost(Q)}}async unlink($){await this.store.hosts.del($),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:W,store:Y,transport:X}=this,I=J.get($.label);if(I){if(I.isConnected())return;try{I.closeListener()}catch{}J.delete($.label)}let K=await Y.seed.load();if(!K)return;console.info(`Connecting to ${$.handle} (${$.label})`);let G=new T$(K,W,$,Z,X($),(N)=>Y.hosts.set($.label,N));if(await G.register(),V)await G.listen(async(N)=>{let w={conn:G,store:Y,enclave:K,host:$,crypto:W,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return _Q(N,w,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(J.set($.label,G),this.clientState.emit(),Q)this.scheduleSync()};async connect($=!0,V=!0){let{connectToHost:Q,scheduleSync:Z,store:J}=this;if(!await J.seed.load())return;await this.drainApplyQueue();let Y=await J.hosts.list();for(let X of Y)await Q(X,$,!1);if(V)Z()}disconnect=async()=>{for(let $ of this.connections.values())try{$.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var f0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function E$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function qV($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function l($,...V){if(!qV($))throw Error("Uint8Array expected");if(V.length>0&&!V.includes($.length))throw Error("Uint8Array expected of length "+V+", got length="+$.length)}function HV($,V=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(V&&$.finished)throw Error("Hash#digest() has already been called")}function jQ($,V){l($);let Q=V.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function PV($){if(typeof $!=="boolean")throw Error(`boolean expected, not ${$}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var F0=($)=>new Uint32Array($.buffer,$.byteOffset,Math.floor($.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($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function x$($){if(typeof $==="string")$=sZ($);else if(qV($))$=f$($);else throw Error("Uint8Array expected, got "+typeof $);return $}function LQ($,V){if(V==null||typeof V!=="object")throw Error("options must be defined");return Object.assign($,V)}function mQ($,V){if($.length!==V.length)return!1;let Q=0;for(let Z=0;Z<$.length;Z++)Q|=$[Z]^V[Z];return Q===0}var SQ=($,V)=>{function Q(Z,...J){if(l(Z),$.nonceLength!==void 0){let G=J[0];if(!G)throw Error("nonce / iv required");if($.varSizeNonce)l(G);else l(G,$.nonceLength)}let W=$.tagLength;if(W&&J[1]!==void 0)l(J[1]);let Y=V(Z,...J),X=(G,N)=>{if(N!==void 0){if(G!==2)throw Error("cipher output not supported");l(N)}},I=!1;return{encrypt(G,N){if(I)throw Error("cannot encrypt() twice with same key + nonce");return I=!0,l(G),X(Y.encrypt.length,N),Y.encrypt(G,N)},decrypt(G,N){if(l(G),W&&G.length<W)throw Error("invalid ciphertext length: smaller than tagLength="+W);return X(Y.decrypt.length,N),Y.decrypt(G,N)}}}return Object.assign(Q,$),Q};function CV($,V,Q=!0){if(V===void 0)return new Uint8Array($);if(V.length!==$)throw Error("invalid output length, expected "+$+", got: "+V.length);if(Q&&!tZ(V))throw Error("invalid output, must be aligned");return V}function tZ($){return $.byteOffset%4===0}function f$($){return Uint8Array.from($)}function M0(...$){for(let V=0;V<$.length;V++)$[V].fill(0)}function B$($=32){if(f0&&typeof f0.getRandomValues==="function")return f0.getRandomValues(new Uint8Array($));if(f0&&typeof f0.randomBytes==="function")return f0.randomBytes($);throw Error("crypto.getRandomValues must be defined")}var xQ=($)=>Uint8Array.from($.split("").map((V)=>V.charCodeAt(0))),eZ=xQ("expand 16-byte k"),$J=xQ("expand 32-byte k"),VJ=F0(eZ),QJ=F0($J);function T($,V){return $<<V|$>>>32-V}function TV($){return $.byteOffset%4===0}var k$=64,ZJ=16,fQ=4294967295,EQ=new Uint32Array;function JJ($,V,Q,Z,J,W,Y,X){let I=J.length,K=new Uint8Array(k$),G=F0(K),N=TV(J)&&TV(W),w=N?F0(J):EQ,z=N?F0(W):EQ;for(let F=0;F<I;Y++){if($(V,Q,Z,G,Y,X),Y>=fQ)throw Error("arx: counter overflow");let R=Math.min(k$,I-F);if(N&&R===k$){let O=F/4;if(F%4!==0)throw Error("arx: invalid block position");for(let H=0,P;H<ZJ;H++)P=O+H,z[P]=w[P]^G[H];F+=k$;continue}for(let O=0,H;O<R;O++)H=F+O,W[H]=J[H]^K[O];F+=R}}function BQ($,V){let{allowShortKeys:Q,extendNonceFn:Z,counterLength:J,counterRight:W,rounds:Y}=LQ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},V);if(typeof $!=="function")throw Error("core must be a function");return E$(J),E$(Y),PV(W),PV(Q),(X,I,K,G,N=0)=>{l(X),l(I),l(K);let w=K.length;if(G===void 0)G=new Uint8Array(w);if(l(G),E$(N),N<0||N>=fQ)throw Error("arx: counter overflow");if(G.length<w)throw Error(`arx: output (${G.length}) is shorter than data (${w})`);let z=[],F=X.length,R,O;if(F===32)z.push(R=f$(X)),O=QJ;else if(F===16&&Q)R=new Uint8Array(32),R.set(X),R.set(X,16),O=VJ,z.push(R);else throw Error(`arx: invalid 32-byte key, got length=${F}`);if(!TV(I))z.push(I=f$(I));let H=F0(R);if(Z){if(I.length!==24)throw Error("arx: extended nonce must be 24 bytes");Z(O,H,F0(I.subarray(0,16)),H),I=I.subarray(16)}let P=16-J;if(P!==I.length)throw Error(`arx: nonce must be ${P} or 16 bytes`);if(P!==12){let q=new Uint8Array(12);q.set(I,W?0:12-I.length),I=q,z.push(I)}let D=F0(I);return JJ($,O,H,D,K,G,N,Y),M0(...z),G}}var d=($,V)=>$[V++]&255|($[V++]&255)<<8;class kQ{constructor($){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,$=x$($),l($,32);let V=d($,0),Q=d($,2),Z=d($,4),J=d($,6),W=d($,8),Y=d($,10),X=d($,12),I=d($,14);this.r[0]=V&8191,this.r[1]=(V>>>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|W<<12)&255,this.r[5]=W>>>1&8190,this.r[6]=(W>>>14|Y<<2)&8191,this.r[7]=(Y>>>11|X<<5)&8065,this.r[8]=(X>>>8|I<<8)&8191,this.r[9]=I>>>5&127;for(let K=0;K<8;K++)this.pad[K]=d($,16+2*K)}process($,V,Q=!1){let Z=Q?0:2048,{h:J,r:W}=this,Y=W[0],X=W[1],I=W[2],K=W[3],G=W[4],N=W[5],w=W[6],z=W[7],F=W[8],R=W[9],O=d($,V+0),H=d($,V+2),P=d($,V+4),D=d($,V+6),q=d($,V+8),A=d($,V+10),m=d($,V+12),f=d($,V+14),E=J[0]+(O&8191),S=J[1]+((O>>>13|H<<3)&8191),k=J[2]+((H>>>10|P<<6)&8191),C=J[3]+((P>>>7|D<<9)&8191),g=J[4]+((D>>>4|q<<12)&8191),i=J[5]+(q>>>1&8191),b=J[6]+((q>>>14|A<<2)&8191),n=J[7]+((A>>>11|m<<5)&8191),p=J[8]+((m>>>8|f<<8)&8191),h=J[9]+(f>>>5|Z),j=0,o=j+E*Y+S*(5*R)+k*(5*F)+C*(5*z)+g*(5*w);j=o>>>13,o&=8191,o+=i*(5*N)+b*(5*G)+n*(5*K)+p*(5*I)+h*(5*X),j+=o>>>13,o&=8191;let t=j+E*X+S*Y+k*(5*R)+C*(5*F)+g*(5*z);j=t>>>13,t&=8191,t+=i*(5*w)+b*(5*N)+n*(5*G)+p*(5*K)+h*(5*I),j+=t>>>13,t&=8191;let Q0=j+E*I+S*X+k*Y+C*(5*R)+g*(5*F);j=Q0>>>13,Q0&=8191,Q0+=i*(5*z)+b*(5*w)+n*(5*N)+p*(5*G)+h*(5*K),j+=Q0>>>13,Q0&=8191;let v=j+E*K+S*I+k*X+C*Y+g*(5*R);j=v>>>13,v&=8191,v+=i*(5*F)+b*(5*z)+n*(5*w)+p*(5*N)+h*(5*G),j+=v>>>13,v&=8191;let w0=j+E*G+S*K+k*I+C*X+g*Y;j=w0>>>13,w0&=8191,w0+=i*(5*R)+b*(5*F)+n*(5*z)+p*(5*w)+h*(5*N),j+=w0>>>13,w0&=8191;let g0=j+E*N+S*G+k*K+C*I+g*X;j=g0>>>13,g0&=8191,g0+=i*Y+b*(5*R)+n*(5*F)+p*(5*z)+h*(5*w),j+=g0>>>13,g0&=8191;let v0=j+E*w+S*N+k*G+C*K+g*I;j=v0>>>13,v0&=8191,v0+=i*X+b*Y+n*(5*R)+p*(5*F)+h*(5*z),j+=v0>>>13,v0&=8191;let i0=j+E*z+S*w+k*N+C*G+g*K;j=i0>>>13,i0&=8191,i0+=i*I+b*X+n*Y+p*(5*R)+h*(5*F),j+=i0>>>13,i0&=8191;let u0=j+E*F+S*z+k*w+C*N+g*G;j=u0>>>13,u0&=8191,u0+=i*K+b*I+n*X+p*Y+h*(5*R),j+=u0>>>13,u0&=8191;let y0=j+E*R+S*F+k*z+C*w+g*N;j=y0>>>13,y0&=8191,y0+=i*G+b*K+n*I+p*X+h*Y,j+=y0>>>13,y0&=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]=v,J[4]=w0,J[5]=g0,J[6]=v0,J[7]=i0,J[8]=u0,J[9]=y0}finalize(){let{h:$,pad:V}=this,Q=new Uint16Array(10),Z=$[1]>>>13;$[1]&=8191;for(let Y=2;Y<10;Y++)$[Y]+=Z,Z=$[Y]>>>13,$[Y]&=8191;$[0]+=Z*5,Z=$[0]>>>13,$[0]&=8191,$[1]+=Z,Z=$[1]>>>13,$[1]&=8191,$[2]+=Z,Q[0]=$[0]+5,Z=Q[0]>>>13,Q[0]&=8191;for(let Y=1;Y<10;Y++)Q[Y]=$[Y]+Z,Z=Q[Y]>>>13,Q[Y]&=8191;Q[9]-=8192;let J=(Z^1)-1;for(let Y=0;Y<10;Y++)Q[Y]&=J;J=~J;for(let Y=0;Y<10;Y++)$[Y]=$[Y]&J|Q[Y];$[0]=($[0]|$[1]<<13)&65535,$[1]=($[1]>>>3|$[2]<<10)&65535,$[2]=($[2]>>>6|$[3]<<7)&65535,$[3]=($[3]>>>9|$[4]<<4)&65535,$[4]=($[4]>>>12|$[5]<<1|$[6]<<14)&65535,$[5]=($[6]>>>2|$[7]<<11)&65535,$[6]=($[7]>>>5|$[8]<<8)&65535,$[7]=($[8]>>>8|$[9]<<5)&65535;let W=$[0]+V[0];$[0]=W&65535;for(let Y=1;Y<8;Y++)W=($[Y]+V[Y]|0)+(W>>>16)|0,$[Y]=W&65535;M0(Q)}update($){HV(this);let{buffer:V,blockLen:Q}=this;$=x$($);let Z=$.length;for(let J=0;J<Z;){let W=Math.min(Q-this.pos,Z-J);if(W===Q){for(;Q<=Z-J;J+=Q)this.process($,J);continue}if(V.set($.subarray(J,J+W),this.pos),this.pos+=W,J+=W,this.pos===Q)this.process(V,0,!1),this.pos=0}return this}destroy(){M0(this.h,this.r,this.buffer,this.pad)}digestInto($){HV(this),jQ($,this),this.finished=!0;let{buffer:V,h:Q}=this,{pos:Z}=this;if(Z){V[Z++]=1;for(;Z<16;Z++)V[Z]=0;this.process(V,0,!0)}this.finalize();let J=0;for(let W=0;W<8;W++)$[J++]=Q[W]>>>0,$[J++]=Q[W]>>>8;return $}digest(){let{buffer:$,outputLen:V}=this;this.digestInto($);let Q=$.slice(0,V);return this.destroy(),Q}}function WJ($){let V=(Z,J)=>$(J).update(x$(Z)).digest(),Q=$(new Uint8Array(32));return V.outputLen=Q.outputLen,V.blockLen=Q.blockLen,V.create=(Z)=>$(Z),V}var DV=WJ(($)=>new kQ($));function YJ($,V,Q,Z,J,W=20){let Y=$[0],X=V[0],I=V[1],K=V[2],G=V[3],N=$[1],w=Q[0],z=Q[1],F=J,R=0,O=$[2],H=V[4],P=V[5],D=V[6],q=V[7],A=$[3],m=Y,f=X,E=I,S=K,k=G,C=N,g=w,i=z,b=F,n=R,p=O,h=H,j=P,o=D,t=q,Q0=A;for(let w0=0;w0<W;w0+=2)k^=T(m+j|0,7),b^=T(k+m|0,9),j^=T(b+k|0,13),m^=T(j+b|0,18),n^=T(C+f|0,7),o^=T(n+C|0,9),f^=T(o+n|0,13),C^=T(f+o|0,18),t^=T(p+g|0,7),E^=T(t+p|0,9),g^=T(E+t|0,13),p^=T(g+E|0,18),S^=T(Q0+h|0,7),i^=T(S+Q0|0,9),h^=T(i+S|0,13),Q0^=T(h+i|0,18),f^=T(m+S|0,7),E^=T(f+m|0,9),S^=T(E+f|0,13),m^=T(S+E|0,18),g^=T(C+k|0,7),i^=T(g+C|0,9),k^=T(i+g|0,13),C^=T(k+i|0,18),h^=T(p+n|0,7),b^=T(h+p|0,9),n^=T(b+h|0,13),p^=T(n+b|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 v=0;Z[v++]=Y+m|0,Z[v++]=X+f|0,Z[v++]=I+E|0,Z[v++]=K+S|0,Z[v++]=G+k|0,Z[v++]=N+C|0,Z[v++]=w+g|0,Z[v++]=z+i|0,Z[v++]=F+b|0,Z[v++]=R+n|0,Z[v++]=O+p|0,Z[v++]=H+h|0,Z[v++]=P+j|0,Z[v++]=D+o|0,Z[v++]=q+t|0,Z[v++]=A+Q0|0}function XJ($,V,Q,Z){let J=$[0],W=V[0],Y=V[1],X=V[2],I=V[3],K=$[1],G=Q[0],N=Q[1],w=Q[2],z=Q[3],F=$[2],R=V[4],O=V[5],H=V[6],P=V[7],D=$[3];for(let A=0;A<20;A+=2)I^=T(J+O|0,7),w^=T(I+J|0,9),O^=T(w+I|0,13),J^=T(O+w|0,18),z^=T(K+W|0,7),H^=T(z+K|0,9),W^=T(H+z|0,13),K^=T(W+H|0,18),P^=T(F+G|0,7),Y^=T(P+F|0,9),G^=T(Y+P|0,13),F^=T(G+Y|0,18),X^=T(D+R|0,7),N^=T(X+D|0,9),R^=T(N+X|0,13),D^=T(R+N|0,18),W^=T(J+X|0,7),Y^=T(W+J|0,9),X^=T(Y+W|0,13),J^=T(X+Y|0,18),G^=T(K+I|0,7),N^=T(G+K|0,9),I^=T(N+G|0,13),K^=T(I+N|0,18),R^=T(F+z|0,7),w^=T(R+F|0,9),z^=T(w+R|0,13),F^=T(z+w|0,18),O^=T(D+P|0,7),H^=T(O+D|0,9),P^=T(H+O|0,13),D^=T(P+H|0,18);let q=0;Z[q++]=J,Z[q++]=K,Z[q++]=F,Z[q++]=D,Z[q++]=G,Z[q++]=N,Z[q++]=w,Z[q++]=z}var AV=BQ(YJ,{counterRight:!0,extendNonceFn:XJ}),_V=SQ({blockSize:64,nonceLength:24,tagLength:16},($,V)=>{return{encrypt(Q,Z){Z=CV(Q.length+32,Z,!1);let J=Z.subarray(0,32),W=Z.subarray(32);Z.set(Q,32),M0(J),AV($,V,Z,Z);let Y=DV(W,J);return Z.set(Y,16),M0(Z.subarray(0,16),Y),Z.subarray(16)},decrypt(Q,Z){l(Q),Z=CV(Q.length+32,Z,!1);let J=Z.subarray(0,32),W=Z.subarray(32,48),Y=Z.subarray(48);Z.set(Q,32),M0(J);let X=AV($,V,J,J),I=DV(Y,X);if(!mQ(W,I))throw Error("invalid tag");return AV($,V,Z.subarray(16),Z.subarray(16)),M0(J,W,I),Y}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function IJ($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function K$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function B0($,...V){if(!IJ($))throw Error("Uint8Array expected");if(V.length>0&&!V.includes($.length))throw Error("Uint8Array expected of length "+V+", got length="+$.length)}function G$($,V=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(V&&$.finished)throw Error("Hash#digest() has already been called")}function g$($,V){B0($);let Q=V.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function gQ($){return new Uint8Array($.buffer,$.byteOffset,$.byteLength)}function c0($){return new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4))}function d0(...$){for(let V=0;V<$.length;V++)$[V].fill(0)}function M$($,V){return $<<32-V|$>>>V}var vQ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function iQ($){return $<<24&4278190080|$<<8&16711680|$>>>8&65280|$>>>24&255}var uQ=vQ?($)=>$:($)=>iQ($);function KJ($){for(let V=0;V<$.length;V++)$[V]=iQ($[V]);return $}var $0=vQ?($)=>$:KJ;function GJ($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function o0($){if(typeof $==="string")$=GJ($);return B0($),$}class jV{}function yQ($){let V=(Z,J)=>$(J).update(o0(Z)).digest(),Q=$({});return V.outputLen=Q.outputLen,V.blockLen=Q.blockLen,V.create=(Z)=>$(Z),V}var bQ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var v$=BigInt(4294967295),nQ=BigInt(32);function LV($,V=!1){if(V)return{h:Number($&v$),l:Number($>>nQ&v$)};return{h:Number($>>nQ&v$)|0,l:Number($&v$)|0}}function U0($,V,Q,Z,J){return $=$+V+J|0,Z=M$(Z^$,16),Q=Q+Z|0,V=M$(V^Q,12),{a:$,b:V,c:Q,d:Z}}function O0($,V,Q,Z,J){return $=$+V+J|0,Z=M$(Z^$,8),Q=Q+Z|0,V=M$(V^Q,7),{a:$,b:V,c:Q,d:Z}}class mV extends jV{constructor($,V){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,K$($),K$(V),this.blockLen=$,this.outputLen=V,this.buffer=new Uint8Array($),this.buffer32=c0(this.buffer)}update($){G$(this),$=o0($),B0($);let{blockLen:V,buffer:Q,buffer32:Z}=this,J=$.length,W=$.byteOffset,Y=$.buffer;for(let X=0;X<J;){if(this.pos===V)$0(Z),this.compress(Z,0,!1),$0(Z),this.pos=0;let I=Math.min(V-this.pos,J-X),K=W+X;if(I===V&&!(K%4)&&X+I<J){let G=new Uint32Array(Y,K,Math.floor((J-X)/4));$0(G);for(let N=0;X+V<J;N+=Z.length,X+=V)this.length+=V,this.compress(G,N,!1);$0(G);continue}Q.set($.subarray(X,X+I),this.pos),this.pos+=I,this.length+=I,X+=I}return this}digestInto($){G$(this),g$($,this);let{pos:V,buffer32:Q}=this;this.finished=!0,d0(this.buffer.subarray(V)),$0(Q),this.compress(Q,0,!0),$0(Q);let Z=c0($);this.get().forEach((J,W)=>Z[W]=uQ(J))}digest(){let{buffer:$,outputLen:V}=this;this.digestInto($);let Q=$.slice(0,V);return this.destroy(),Q}_cloneInto($){let{buffer:V,length:Q,finished:Z,destroyed:J,outputLen:W,pos:Y}=this;return $||($=new this.constructor({dkLen:W})),$.set(...this.get()),$.buffer.set(V),$.destroyed=J,$.finished=Z,$.length=Q,$.pos=Y,$.outputLen=W,$}clone(){return this._cloneInto()}}function SV($,V,Q,Z,J,W,Y,X,I,K,G,N,w,z,F,R,O,H,P,D){let q=0;for(let A=0;A<Z;A++)({a:J,b:I,c:w,d:O}=U0(J,I,w,O,Q[V+$[q++]])),{a:J,b:I,c:w,d:O}=O0(J,I,w,O,Q[V+$[q++]]),{a:W,b:K,c:z,d:H}=U0(W,K,z,H,Q[V+$[q++]]),{a:W,b:K,c:z,d:H}=O0(W,K,z,H,Q[V+$[q++]]),{a:Y,b:G,c:F,d:P}=U0(Y,G,F,P,Q[V+$[q++]]),{a:Y,b:G,c:F,d:P}=O0(Y,G,F,P,Q[V+$[q++]]),{a:X,b:N,c:R,d:D}=U0(X,N,R,D,Q[V+$[q++]]),{a:X,b:N,c:R,d:D}=O0(X,N,R,D,Q[V+$[q++]]),{a:J,b:K,c:F,d:D}=U0(J,K,F,D,Q[V+$[q++]]),{a:J,b:K,c:F,d:D}=O0(J,K,F,D,Q[V+$[q++]]),{a:W,b:G,c:R,d:O}=U0(W,G,R,O,Q[V+$[q++]]),{a:W,b:G,c:R,d:O}=O0(W,G,R,O,Q[V+$[q++]]),{a:Y,b:N,c:w,d:H}=U0(Y,N,w,H,Q[V+$[q++]]),{a:Y,b:N,c:w,d:H}=O0(Y,N,w,H,Q[V+$[q++]]),{a:X,b:I,c:z,d:P}=U0(X,I,z,P,Q[V+$[q++]]),{a:X,b:I,c:z,d:P}=O0(X,I,z,P,Q[V+$[q++]]);return{v0:J,v1:W,v2:Y,v3:X,v4:I,v5:K,v6:G,v7:N,v8:w,v9:z,v10:F,v11:R,v12:O,v13:H,v14:P,v15:D}}var N0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},q0=bQ.slice(),pQ=(()=>{let $=Array.from({length:16},(Z,J)=>J),V=(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=$;Z<7;Z++,J=V(J))Q.push(...J);return Uint8Array.from(Q)})();class EV extends mV{constructor($={},V=0){super(64,$.dkLen===void 0?32:$.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}=$,J=Z!==void 0;if(Q!==void 0){if(J)throw Error('Only "key" or "context" can be specified at same time');let W=o0(Q).slice();B0(W,32),this.IV=c0(W),$0(this.IV),this.flags=V|N0.KEYED_HASH}else if(J){let W=o0(Z),Y=new EV({dkLen:32},N0.DERIVE_KEY_CONTEXT).update(W).digest();this.IV=c0(Y),$0(this.IV),this.flags=V|N0.DERIVE_KEY_MATERIAL}else this.IV=q0.slice(),this.flags=V;this.state=this.IV.slice(),this.bufferOut=gQ(this.bufferOut32)}get(){return[]}set(){}b2Compress($,V,Q,Z=0){let{state:J,pos:W}=this,{h:Y,l:X}=LV(BigInt($),!0),{v0:I,v1:K,v2:G,v3:N,v4:w,v5:z,v6:F,v7:R,v8:O,v9:H,v10:P,v11:D,v12:q,v13:A,v14:m,v15:f}=SV(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],Y,X,W,V);J[0]=I^O,J[1]=K^H,J[2]=G^P,J[3]=N^D,J[4]=w^q,J[5]=z^A,J[6]=F^m,J[7]=R^f}compress($,V=0,Q=!1){let Z=this.flags;if(!this.chunkPos)Z|=N0.CHUNK_START;if(this.chunkPos===15||Q)Z|=N0.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 W,Y=this.chunksDone+1;Q||!(Y&1);Y>>=1){if(!(W=this.stack.pop()))break;this.buffer32.set(W,0),this.buffer32.set(J,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|N0.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($){$=super._cloneInto($);let{IV:V,flags:Q,state:Z,chunkPos:J,posOut:W,chunkOut:Y,stack:X,chunksDone:I}=this;return $.state.set(Z.slice()),$.stack=X.map((K)=>Uint32Array.from(K)),$.IV.set(V),$.flags=Q,$.chunkPos=J,$.chunksDone=I,$.posOut=W,$.chunkOut=Y,$.enableXOF=this.enableXOF,$.bufferOut32.set(this.bufferOut32),$}destroy(){this.destroyed=!0,d0(this.state,this.buffer32,this.IV,this.bufferOut32),d0(...this.stack)}b2CompressOut(){let{state:$,pos:V,flags:Q,buffer32:Z,bufferOut32:J}=this,{h:W,l:Y}=LV(BigInt(this.chunkOut++));$0(Z);let{v0:X,v1:I,v2:K,v3:G,v4:N,v5:w,v6:z,v7:F,v8:R,v9:O,v10:H,v11:P,v12:D,v13:q,v14:A,v15:m}=SV(pQ,0,Z,7,$[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],q0[0],q0[1],q0[2],q0[3],Y,W,V,Q);J[0]=X^R,J[1]=I^O,J[2]=K^H,J[3]=G^P,J[4]=N^D,J[5]=w^q,J[6]=z^A,J[7]=F^m,J[8]=$[0]^R,J[9]=$[1]^O,J[10]=$[2]^H,J[11]=$[3]^P,J[12]=$[4]^D,J[13]=$[5]^q,J[14]=$[6]^A,J[15]=$[7]^m,$0(Z),$0(J),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,d0(this.buffer.subarray(this.pos));let $=this.flags|N0.ROOT;if(this.stack.length)$|=N0.PARENT,$0(this.buffer32),this.compress(this.buffer32,0,!0),$0(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else $|=(!this.chunkPos?N0.CHUNK_START:0)|N0.CHUNK_END;this.flags=$,this.b2CompressOut()}writeInto($){G$(this,!1),B0($),this.finish();let{blockLen:V,bufferOut:Q}=this;for(let Z=0,J=$.length;Z<J;){if(this.posOut>=V)this.b2CompressOut();let W=Math.min(V-this.posOut,J-Z);$.set(Q.subarray(this.posOut,this.posOut+W),Z),this.posOut+=W,Z+=W}return $}xofInto($){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto($)}xof($){return K$($),this.xofInto(new Uint8Array($))}digestInto($){if(g$($,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto($),this.destroy(),$}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var hQ=yQ(($)=>new EV($));var xV=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function lQ($){let V=new Uint8Array(xV.length+32);return V.set(xV),V.set($.subarray(0,32),xV.length),V}function rQ($){return typeof $==="string"?new TextEncoder().encode($):$}function a0($){let V=new ArrayBuffer($.byteLength);return new Uint8Array(V).set($),V}class fV{verifyKeys=new Map;signKeys=new Map;async genRandomBytes($){return B$($)}async gen256BitSecureRandomSeed(){return B$(32)}async encryptXSalsa20Poly1305Combined($,V){let Q=B$(24),J=_V(V,Q).encrypt($);return new Uint8Array([...Q,...J])}async decryptXSalsa20Poly1305Combined($,V){let Q=$.slice(0,24),Z=$.slice(24);return _V(V,Q).decrypt(Z)}async deriveEd25519KeyPair($){let V=$,Q=lQ(V),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 W=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:J.x},{name:"Ed25519"},!0,["verify"]),Y=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",W)),X=new Uint8Array(64);return X.set(V,0),X.set(Y,32),this.signKeys.set(a(V),Z),this.verifyKeys.set(a(Y),W),{keyType:"ed25519",privateKey:X,publicKey:Y}}async importSignKey($){let V=$.subarray(0,32),Q=a(V),Z=this.signKeys.get(Q);if(Z)return Z;let J=lQ(V),W=await globalThis.crypto.subtle.importKey("pkcs8",a0(J),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Q,W),W}async importVerifyKey($){let V=a($),Q=this.verifyKeys.get(V);if(Q)return Q;let Z=await globalThis.crypto.subtle.importKey("raw",a0($),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set(V,Z),Z}async signEd25519($,V){let Q=rQ($),Z=await this.importSignKey(V),J=await globalThis.crypto.subtle.sign({name:"Ed25519"},Z,a0(Q));return new Uint8Array(J)}async checkSigEd25519($,V,Q){let Z=rQ(V);try{let J=await this.importVerifyKey(Q);return await globalThis.crypto.subtle.verify({name:"Ed25519"},J,a0($),a0(Z))}catch{return!1}}async blake3($){return hQ($)}}var MJ=new fV,J0=MJ;import{useEffect as n$,useState as yV}from"react";class BV{db;constructor($){this.db=$}async enq($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(W0,"readwrite"),Z=Q.objectStore(W0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let Y of V){let X=`${Y.host}:${Y.seq}`;Z.put(Y,X)}})}async deq($,V){let Q=[...V];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((W,Y)=>{Z.oncomplete=()=>W(),Z.onerror=()=>Y(Z.error);for(let X of Q){let I=`${$}:${X}`;J.delete(I)}})}async list(){let V=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Q,Z)=>{let J=V.getAll();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async count(){let V=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Q,Z)=>{let J=V.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let $=this.db.transaction(W0,"readwrite"),V=$.objectStore(W0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}function cQ($){return{label:$.label,handle:new URL($.handle),idx:$.idx,lastSeq:$.lastSeq||0,clockOffset:$.clockOffset,subscription:$.subscription}}class kV{db;constructor($){this.db=$}async add($){return this.put($)}async put($){let V={...$,handle:$.handle.toString(),lastSeq:$.lastSeq??0},Q=this.db.transaction(V0,"readwrite"),Z=Q.objectStore(V0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error),Z.put(V)})}async touch($,V){let Q=this.db.transaction(V0,"readwrite"),Z=Q.objectStore(V0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);let Y=Z.get($);Y.onsuccess=()=>{let X=Y.result;if(!X)return;let I=X.lastSeq||0;if(V<=I)return;Z.put({...X,lastSeq:V})}})}async get($){let Q=this.db.transaction(V0,"readonly").objectStore(V0);return new Promise((Z,J)=>{let W=Q.get($);W.onsuccess=()=>{let Y=W.result;if(!Y)Z(void 0);else Z(cQ(Y))},W.onerror=()=>J(W.error)})}async set($,V){let Q=await this.get($);if(!Q)return 13;try{return await this.put({...Q,...V}),0}catch{return 18}}async del($){let V=this.db.transaction(V0,"readwrite"),Q=V.objectStore(V0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),Q.delete($)})}async list(){let V=this.db.transaction(V0,"readonly").objectStore(V0);return new Promise((Q,Z)=>{let J=V.getAll();J.onsuccess=()=>{let W=J.result;Q(W.map(cQ))},J.onerror=()=>Z(J.error)})}async wipe(){let $=this.db.transaction(V0,"readwrite"),V=$.objectStore(V0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}class gV{crypto;db;constructor($,V){this.crypto=V;this.db=$}async add($){let V=this.db.transaction(u,"readwrite"),Q=V.objectStore(u);return new Promise((Z)=>{if($.length===0){Z([]);return}let J=Array($.length).fill(0);V.oncomplete=()=>Z(J),V.onerror=()=>{for(let W=0;W<J.length;W++)J[W]=18;Z(J)};for(let W=0;W<$.length;W++){let{key:Y,data:X}=$[W],I=L(Y),K=Q.put(X,I);K.onerror=(G)=>{G.preventDefault(),J[W]=18}}})}async del($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let Y of V){let X=L(Y);Z.delete(X)}})}async get($){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let W=L($),Y=Q.get(W);Y.onsuccess=async()=>{let X=Y.result;if(X)Z(await L0($,X,this.crypto));else Z(void 0)},Y.onerror=()=>J(Y.error)})}async has($){return await this.get($)!==void 0}async list($){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let W=[],Y=$===void 0?Q.openCursor():Q.index(i$).openCursor(IDBKeyRange.only($));Y.onsuccess=(X)=>{let I=X.target.result;if(I){let K=$===void 0?I.key:I.primaryKey,G=I.value;W.push({hash:I0(K),data:G}),I.continue()}else Promise.all(W.map(({hash:K,data:G})=>L0(K,G,this.crypto))).then(Z).catch(J)},Y.onerror=()=>J(Y.error)})}async last($){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let W,Y=Q.openCursor();Y.onsuccess=async(X)=>{let I=X.target.result;if(I){let{key:K,value:G}=I;if(s($,G.eid)){if(!W||(G.ctr??0)>(W.data.ctr??0)||(G.ctr??0)===(W.data.ctr??0)&&(G.off??0)>(W.data.off??0))W={key:K,data:G}}I.continue()}else if(W){let K=I0(W.key);Z(await L0(K,W.data,this.crypto))}else Z(void 0)},Y.onerror=()=>J(Y.error)})}async markApplied($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let Y of V){let X=L(Y),I=Z.get(X);I.onsuccess=()=>{let K=I.result;if(!K)return;E0(K,j0),Z.put(K,X)},I.onerror=(K)=>{K.preventDefault()}}})}async markFailed($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let{key:Y,err:X}of V){let I=L(Y),K=Z.get(I);K.onsuccess=()=>{let G=K.result;if(!G)return;E0(G,G0,X),Z.put(G,I)},K.onerror=(G)=>{G.preventDefault()}}})}async wipe(){let $=this.db.transaction(u,"readwrite"),V=$.objectStore(u);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}class s0{seed;crypto;constructor($,V){this.seed=$,this.crypto=V}async deriveFromKDM($){let V=V$(this.seed,$);return await this.crypto.blake3(V)}async derive($,V=0){let Q=new TextEncoder().encode($),Z=new Uint8Array(8);new DataView(Z.buffer).setBigUint64(0,BigInt(V),!1);let J=V$(Q,Z);return await this.deriveFromKDM(J)}}class vV{enclave;db;constructor($){this.db=$}async save($){let V=a($),Q=this.db.transaction(H0,"readwrite"),Z=Q.objectStore(H0);return new Promise((J,W)=>{Q.oncomplete=()=>{this.enclave=new s0($,J0),J(this.enclave)},Q.onerror=()=>W(Q.error),Z.put(V,"seed")})}async load(){if(this.enclave)return this.enclave;let V=this.db.transaction(H0,"readonly").objectStore(H0);return new Promise((Q,Z)=>{let J=V.get("seed");J.onsuccess=()=>{let W=J.result;if(!W)Q(void 0);else{let Y=_0(W);this.enclave=new s0(Y,J0),Q(this.enclave)}},J.onerror=()=>Z(J.error)})}async wipe(){this.enclave=void 0;let $=this.db.transaction(H0,"readwrite"),V=$.objectStore(H0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.delete("seed")})}}class iV{db;constructor($){this.db=$}async enq($,V){let Q=[...V];if(Q.length===0)return;let Z=this.db.transaction(Y0,"readwrite"),J=Z.objectStore(Y0);return new Promise((W,Y)=>{Z.oncomplete=()=>W(),Z.onerror=()=>Y(Z.error);for(let X of Q){let I=a(X);J.put({host:$,hash:I})}})}async deq($,V){let Q=[...V];if(Q.length===0)return;let Z=this.db.transaction(Y0,"readwrite"),J=Z.objectStore(Y0);return new Promise((W,Y)=>{Z.oncomplete=()=>W(),Z.onerror=()=>Y(Z.error);for(let X of Q){let I=a(X);J.delete([$,I])}})}async list($){let Q=this.db.transaction(Y0,"readonly").objectStore(Y0);return new Promise((Z,J)=>{let W=Q.getAll();W.onsuccess=()=>{let X=W.result.filter((I)=>I.host===$).map((I)=>I.hash);Z(X.map((I)=>_0(I)))},W.onerror=()=>J(W.error)})}async count(){let V=this.db.transaction(Y0,"readonly").objectStore(Y0);return new Promise((Q,Z)=>{let J=V.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let $=this.db.transaction(Y0,"readwrite"),V=$.objectStore(Y0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}var H0="seedMeta",V0="hosts",Y0="uploadQueue",W0="downloadQueue",u="messages",i$="apld",NJ=3;class uV{seed;hosts;uploads;downloads;messages;db;constructor($,V){this.db=$,this.seed=new vV($),this.hosts=new kV($),this.uploads=new iV($),this.downloads=new BV($),this.messages=new gV($,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 wJ(){return new Promise(($,V)=>{let Q=indexedDB.open("diplomatic-store-db",NJ);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!Z.objectStoreNames.contains(H0))Z.createObjectStore(H0);if(!Z.objectStoreNames.contains(V0))Z.createObjectStore(V0,{keyPath:"label"});if(!Z.objectStoreNames.contains(Y0))Z.createObjectStore(Y0,{keyPath:["host","hash"]});if(!Z.objectStoreNames.contains(W0))Z.createObjectStore(W0);let W;if(!Z.objectStoreNames.contains(u))W=Z.createObjectStore(u);else{if(!J)throw Error("missing upgrade transaction for messages store");W=J.objectStore(u)}if(!W.indexNames.contains(i$))W.createIndex(i$,"apld",{unique:!1})},Q.onsuccess=()=>$(Q.result),Q.onerror=()=>V(Q.error)})}async function u$($){let V=await wJ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new uV(V,$)}function dQ($){if(!$||typeof $!=="object")return!1;if(!("kind"in $))return!1;return typeof $.kind==="string"}function oQ($){if(typeof $!=="number")return;return $}function aQ($){if(!$||typeof $!=="object")return;if(!("hasSeed"in $)||!("hasHost"in $)||!("connected"in $))return;if(typeof $.hasSeed!=="boolean"||typeof $.hasHost!=="boolean"||typeof $.connected!=="boolean")return;return{hasSeed:$.hasSeed,hasHost:$.hasHost,connected:$.connected}}function RJ($){if(!$||typeof $!=="object")return;if(!("phase"in $))return;let V=zJ($.phase);if(V===void 0)return;let Q={phase:V};if("host"in $&&typeof $.host==="string")Q.host=$.host;if("done"in $&&typeof $.done==="number")Q.done=$.done;if("total"in $&&typeof $.total==="number")Q.total=$.total;if("bytesDone"in $&&typeof $.bytesDone==="number")Q.bytesDone=$.bytesDone;if("bytesTotal"in $&&typeof $.bytesTotal==="number")Q.bytesTotal=$.bytesTotal;return Q}function zJ($){if($==="peek"||$==="pull"||$==="open"||$==="exec"||$==="push"||$==="import"||$==="idle"||$==="apply")return $==="apply"?"exec":$;return}function sQ($){if(!$||typeof $!=="object")return;if(!("numUploads"in $)||!("numDownloads"in $))return;if(typeof $.numUploads!=="number"||typeof $.numDownloads!=="number")return;let V={phase:"idle"};if("progress"in $){let Q=RJ($.progress);if(Q===void 0)return;V=Q}return{numUploads:$.numUploads,numDownloads:$.numDownloads,progress:V}}var P0="[DIPLOMATIC]";class N${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:S0};clientState;xferState;constructor($,V,Q,Z,J){this.worker=$,this.state=V,this.clientState=new K0(async()=>this.cachedClientState),this.xferState=new K0(async()=>this.cachedXferState),this.scheduledSync=new W$(J,async()=>{try{await this.request({id:this.allocId(),op:"sync"})}catch(W){console.error(`${P0} worker sync after local write failed`,W)}}),this.local=new x0(Z,V,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((W,Y)=>{this.resolveReady=W,this.rejectReady=Y}),this.worker.onmessage=(W)=>{this.onMessage(W.data)},this.worker.onerror=(W)=>{console.error(`${P0} worker error`,W),this.failReady(Error(`${P0} worker failed to load`))},this.worker.onmessageerror=()=>{this.failReady(Error(`${P0} worker message error`))}}failReady($){let V=this.rejectReady;if(this.rejectReady=void 0,this.resolveReady=void 0,V)V($)}async flushScheduledSync(){await this.scheduledSync.flush()}static async connect($,V,Q){let Z=Q.clock??new R0,J=Q.syncDebounceMs??m$,W=new N$(Q.worker,$,V,Z,J),Y=Q.readyTimeoutMs??15000,X;try{let I=W.probeReady();if(await Promise.race([W.ready,I,new Promise((K,G)=>{X=setTimeout(()=>{G(Error(`${P0} worker ready timeout after ${Y}ms`))},Y)})]),X!==void 0)clearTimeout(X),X=void 0;I.catch(()=>{}),await W.hydrateStateFromStore(V),await W.pullRemoteState()}catch(I){throw W.terminate(),I}finally{if(X!==void 0)clearTimeout(X)}return W}async hydrateStateFromStore($){let V=await $.seed.load(),Q=await $.hosts.list();this.cachedClientState={hasSeed:V!==void 0,hasHost:Array.from(Q).length>0,connected:!1};let Z=await $.uploads.count(),J=await $.downloads.count();this.cachedXferState={numUploads:Z,numDownloads:J,progress:S0}}async pullRemoteState(){let $=await this.request({id:this.allocId(),op:"getClientState"}),V=aQ($);if(V!==void 0)this.cachedClientState=V;let Q=await this.request({id:this.allocId(),op:"getXferState"}),Z=sQ(Q);if(Z!==void 0)this.cachedXferState=Z}markReady(){let $=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,$)$()}probeReady(){return new Promise(($,V)=>{let Q=this.allocId();this.pending.set(Q,{resolve:(Z)=>{if(Z==="pong"){this.markReady(),$();return}V(Error(`${P0} worker probe ping failed`))},reject:V}),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[,$]of this.pending)$.reject(Error(`${P0} worker terminated`));this.pending.clear()}onMessage($){if(!dQ($))return;let V=$;switch(V.kind){case"ready":{this.markReady();return}case"clientState":{this.cachedClientState=V.state,this.clientState.emit();return}case"xferState":{this.cachedXferState=V.state,this.xferState.emit();return}case"dirty":{this.state.refresh(V.eids.map(FJ));return}case"wiped":{this.state.clear();return}case"reply":{let Q=this.pending.get(V.id);if(!Q)return;if(this.pending.delete(V.id),V.ok)Q.resolve(V.result);else Q.reject(new y$(V.status));return}default:return}}allocId(){let $=this.nextId;return this.nextId+=1,$}request($,V){return new Promise((Q,Z)=>{if(this.pending.set($.id,{resolve:Q,reject:Z}),V&&V.length>0)this.worker.postMessage($,V);else this.worker.postMessage($)})}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 y$)return Q.status;return 12}}serializeHost($){return{handle:$.handle.href,label:$.label,idx:$.idx??0}}async setSeed($){await this.ready,await this.local.setSeed($);let V=$.slice();await this.request({id:this.allocId(),op:"setSeed",seed:V},[V.buffer])}async link($,V=!0){await this.ready,await this.local.link($,!1),await this.request({id:this.allocId(),op:"link",host:this.serializeHost($),connect:V})}async unlink($){await this.ready,await this.local.unlink($),await this.request({id:this.allocId(),op:"unlink",label:$})}async hosts(){return await this.ready,this.local.hosts()}async connect($=!0,V=!0){await this.ready,await this.request({id:this.allocId(),op:"connect",listen:$,sync:V})}async disconnect(){await this.ready,await this.request({id:this.allocId(),op:"disconnect"})}async insertRaw($){return await this.ready,this.local.insertRaw($)}async updateRaw($,V,Q){return await this.ready,this.local.updateRaw($,V,Q)}async insert($){return await this.ready,this.local.insert($)}async update($){return await this.ready,this.local.update($)}async delete($){return await this.ready,this.local.delete($)}async genEID($){return await this.ready,this.local.genEID($)}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($){await this.ready;let V=new Uint8Array(await $.arrayBuffer());return this.requestStatus({id:this.allocId(),op:"import",bytes:V},[V.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 S$(Z,$),0}catch(Q){if(Q instanceof y$)return Q.status;return 12}}}class y$ extends Error{status;constructor($){super(`WorkerReplyError: ${_[$]}`);this.status=$;this.name="WorkerReplyError"}}function FJ($){return $}var k0="[DIPLOMATIC]";async function b$($){let V=$.clock??new R0;if($.worker!==void 0&&UJ($)!==void 0)throw Error(`${k0} worker path requires IndexedDB on both sides; do not pass store (got a custom store)`);if($.worker===void 0){console.info(`${k0} sync on main thread `+"(no worker — app did not request a worker)");let J=await tQ($.store);return OJ(V,$.state,J)}if(typeof Worker>"u")throw Error(`${k0} worker was provided but Worker API is unavailable`);let Q=await tQ(void 0);console.info(`${k0} attaching app-provided sync worker…`);let Z=await N$.connect($.state,Q,{worker:$.worker,readyTimeoutMs:$.readyTimeoutMs,clock:V,syncDebounceMs:$.syncDebounceMs});return await Z.ping(),console.info(`${k0} sync worker active (network + EntDB writes off main; local mutates on main; dirty signals only)`),{client:Z,mode:"worker",dispose:()=>{console.info(`${k0} terminating sync worker`),Z.terminate()}}}function UJ($){if("store"in $)return $.store;return}async function OJ($,V,Q){let Z=new x0($,V,Q,C$,J0);return{client:Z,mode:"main",dispose:()=>{Z.disconnect()}}}async function tQ($){if($!==void 0)return $;if(typeof indexedDB>"u")throw Error(`${k0} IndexedDB is unavailable; pass store explicitly (e.g. new MemoryStore(crypto))`);return u$(J0)}function qJ($){let[V,Q]=yV();return n$(()=>{async function Z(){let W=await $.clientState.get();Q(W)}let J=$.clientState.listen(Z);return Z(),()=>{J()}},[$]),V}function HJ($){let[V,Q]=yV();return n$(()=>{async function Z(){let W=await $.xferState.get();Q(W)}let J=$.xferState.listen(Z);return Z(),()=>{J()}},[$]),V}function PJ($){n$(()=>{async function V(){try{await $.connect(),await $.sync()}catch(W){console.error("reconnectAndSync failed",W)}}function Q(){V()}function Z(){if(typeof document<"u"&&document.visibilityState==="visible")V()}function J(){V()}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)}},[$])}function CJ($={}){let V=$.clock??new R0,{seed:Q,host:Z,readyTimeoutMs:J}=$,W=$.worker,Y="store"in $?$.store:void 0,[X,I]=yV({stateMgr:XV});return n$(()=>{let K=!1,G;return(async()=>{let N=await NV();if(K)return;let w=j$(N),z=W!==void 0?await b$({state:w,clock:V,worker:W,readyTimeoutMs:J}):await b$({state:w,clock:V,store:Y,readyTimeoutMs:J});if(K){z.dispose();return}G=z.dispose;let{client:F,mode:R}=z;if(Q)await F.setSeed(Q);if(Z)await F.link(Z);if(K){G();return}I({client:F,entDB:N,stateMgr:w,mode:R,error:void 0})})().catch((N)=>{let w=N instanceof Error?N:Error(String(N));if(console.error("[DIPLOMATIC] useClient init failed",w),!K)I((z)=>({...z,client:void 0,error:w}))}),()=>{K=!0,G?.()}},[V,Q,Z,W,Y,J]),X}import{use as TJ,useEffect as eQ,useRef as DJ,useState as AJ}from"react";function $Z($,V,Q){let[Z,J]=AJ();return eQ(()=>{async function W(){let Y=await Q();J(Y)}return W(),$.on(V,W),()=>{$.off(V,W)}},[$,V,Q]),Z}function _J($,V,Q){let Z=DJ(Q());return eQ(()=>{async function J(){Z.current=Q()}return $.on(V,J),()=>{$.off(V,J)}},[$,V,Q]),TJ(Z.current)}function VZ($,V){return`${$}:${V}`}class bV{queue=new Map;async enq($){for(let V of $){let Q=VZ(V.host,V.seq);this.queue.set(Q,V)}}async deq($,V){for(let Q of V){let Z=VZ($,Q);this.queue.delete(Z)}}async list(){let $=[];for(let V of this.queue.values())$.push(V);return $}async count(){return this.queue.size}async wipe(){this.queue.clear()}}class nV{hosts=new Map;async add($){let V={...$,lastSeq:0};this.hosts.set($.label,V)}async touch($,V){let Q=this.hosts.get($);if(!Q||V<=Q.lastSeq)return;this.hosts.set($,{...Q,lastSeq:V})}async get($){return this.hosts.get($)}async set($,V){let Q=this.hosts.get($);if(!Q)return 13;return this.hosts.set($,{...Q,...V}),0}async del($){this.hosts.delete($)}async list(){return this.hosts.values()}async wipe(){this.hosts.clear()}}class pV{crypto;messages=new Map;constructor($){this.crypto=$}async add($){let V=[];for(let{key:Q,data:Z}of $)this.messages.set(L(Q),Z),V.push(0);return V}async del($){for(let V of $)this.messages.delete(L(V))}async get($){let V=this.messages.get(L($));if(V)return await L0($,V,this.crypto);return}async has($){return this.messages.has(L($))}async list($){let V=[];for(let[Q,Z]of this.messages){if($!==void 0&&I$(Z.apld)!==$)continue;let J=I0(Q);V.push(await L0(J,Z,this.crypto))}return V}async last($){let V;for(let[Q,Z]of this.messages){if(s($,Z.eid)===!1)continue;let J=I0(Q);if(V===void 0)V={hash:J,data:Z};else if((Z.ctr??0)>(V.data.ctr??0)||(Z.ctr??0)===(V.data.ctr??0)&&(Z.off??0)>(V.data.off??0))V={hash:J,data:Z}}if(V)return await L0(V.hash,V.data,this.crypto);return}async markApplied($){for(let V of $){let Q=this.messages.get(L(V));if(!Q)continue;E0(Q,j0)}}async markFailed($){for(let{key:V,err:Q}of $){let Z=this.messages.get(L(V));if(!Z)continue;E0(Z,G0,Q)}}async wipe(){this.messages.clear()}}class hV{enclave;async save($){return this.enclave=new s0($,J0),this.enclave}async load(){return this.enclave}async wipe(){this.enclave=void 0}}class lV{queue=new Map;async enq($,V){let Q=this.queue.get($)||new Set;this.queue.set($,Q);for(let Z of V)Q.add(a(Z))}async deq($,V){let Q=this.queue.get($);if(Q)for(let Z of V)Q.delete(a(Z))}async list($){let V=this.queue.get($);if(!V)return[];let Q=[];for(let Z of V)Q.push(_0(Z));return Q}async count(){let $=0;for(let V of this.queue.values())$+=V.size;return $}async wipe(){this.queue.clear()}}class QZ{seed=new hV;hosts=new nV;uploads=new lV;downloads=new bV;messages;constructor($){this.messages=new pV($)}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($){this.singletonType=$}async apply($){for(let V of $){let Q=new x(V.eid),[Z,J]=Q.readStruct(r);if(J!==0)continue;let W=new B;W.writeVarString(this.singletonType);let Y=W.result();if(Z.id.length===Y.length&&Z.id.every((X,I)=>X===Y[I])){if(this.latest===void 0||V.off>this.latestOff)this.latestOff=V.off,this.latest=V.bod,this.emitter.emit(this.singletonType,null)}}return $.map(()=>0)}clear=async()=>{return this.latest=void 0,this.latestOff=-1,this.emitter.emit(this.singletonType,null),0};notify=($)=>{for(let V of $)if(V===this.singletonType)this.emitter.emit(this.singletonType,null)};refresh=async($)=>{this.notify([this.singletonType])};on=($,V)=>{this.emitter.addEventListener($,V)};off=($,V)=>{this.emitter.removeEventListener($,V)}}async function Jw($,V){let Q=await u$(J0),Z=new x0(new R0,$,Q,C$,J0);return{client:Z,setSeed:async(W)=>{let Y=_0(W);await Q.seed.save(Y),await Q.hosts.add({handle:V,label:"host",idx:0}),await Z.connect()}}}export{PJ as useSyncOnResume,_J as useStateWatcherSuspense,$Z as useStateWatcher,HJ as useClientXferState,qJ as useClientState,CJ as useClient,RV as shouldEmitItemProgress,E0 as setApld,wV as revFromHead,bZ as revFromEntity,u$ as openIDBStore,NV as openEntDB,b$ as openDiplomaticClient,XV as nullStateManager,nZ as nullEntDB,FV as isTerminalApplyFailure,lZ as isPendingApply,hZ as isApldState,S0 as idleProgress,_0 as htob,C$ as hostHTTPTransport,Jw as genWebClient,SZ as genSingletonEID,j$ as entStateManager,r as eidCodec,X$ as defaultPeekProgressEvery,J0 as crypto,a as btoh,L as btob64,I0 as b64tob,I$ as apldFromStored,N$ as WorkerClient,C0 as TypedEventEmitter,x0 as SyncClient,_ as Status,Z$ as StateManager,ZZ as SingletonStateManager,QZ as MemoryStore,uV as IDBStore,ZV as HTTPTransport,MV as EntIDB,_$ as EntDBMemory,B as Encoder,x as Decoder,R0 as Clock,J$ as CachedEntDB,z0 as APLD_PENDING,G0 as APLD_ERROR,j0 as APLD_APPLIED};
@@ -1 +1 @@
1
- var M0=64;var D$=32,F0=8;var t0=32;var _$=30000,j$=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 L$(V){if(!V||typeof V!=="object")return!1;if(!("op"in V)||!("id"in V))return!1;return typeof V.op==="string"&&typeof V.id==="number"}function E$(V){let $=V.length,Z=0,J=0;while(J<$){let Q=V.charCodeAt(J++);if((Q&4294967168)===0){Z++;continue}else if((Q&4294965248)===0)Z+=2;else{if(Q>=55296&&Q<=56319){if(J<$){let W=V.charCodeAt(J);if((W&64512)===56320)++J,Q=((Q&1023)<<10)+(W&1023)+65536}}if((Q&4294901760)===0)Z+=3;else Z+=4}}return Z}function bZ(V,$,Z){let J=V.length,Q=Z,W=0;while(W<J){let Y=V.charCodeAt(W++);if((Y&4294967168)===0){$[Q++]=Y;continue}else if((Y&4294965248)===0)$[Q++]=Y>>6&31|192;else{if(Y>=55296&&Y<=56319){if(W<J){let X=V.charCodeAt(W);if((X&64512)===56320)++W,Y=((Y&1023)<<10)+(X&1023)+65536}}if((Y&4294901760)===0)$[Q++]=Y>>12&15|224,$[Q++]=Y>>6&63|128;else $[Q++]=Y>>18&7|240,$[Q++]=Y>>12&63|128,$[Q++]=Y>>6&63|128}$[Q++]=Y&63|128}}var yZ=new TextEncoder,lZ=50;function nZ(V,$,Z){yZ.encodeInto(V,$.subarray(Z))}function x$(V,$,Z){if(V.length>lZ)nZ(V,$,Z);else bZ(V,$,Z)}var hZ=4096;function _V(V,$,Z){let J=$,Q=J+Z,W=[],Y="";while(J<Q){let X=V[J++];if((X&128)===0)W.push(X);else if((X&224)===192){let K=V[J++]&63;W.push((X&31)<<6|K)}else if((X&240)===224){let K=V[J++]&63,G=V[J++]&63;W.push((X&31)<<12|K<<6|G)}else if((X&248)===240){let K=V[J++]&63,G=V[J++]&63,N=V[J++]&63,R=(X&7)<<18|K<<12|G<<6|N;if(R>65535)R-=65536,W.push(R>>>10&1023|55296),R=56320|R&1023;W.push(R)}else W.push(X);if(W.length>=hZ)Y+=String.fromCharCode(...W),W.length=0}if(W.length>0)Y+=String.fromCharCode(...W);return Y}var pZ=new TextDecoder,cZ=200;function rZ(V,$,Z){let J=V.subarray($,$+Z);return pZ.decode(J)}function S$(V,$,Z){if(Z>cZ)return rZ(V,$,Z);else return _V(V,$,Z)}class E0{type;data;constructor(V,$){this.type=V,this.data=$}}class a extends Error{constructor(V){super(V);let $=Object.create(a.prototype);Object.setPrototypeOf(this,$),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:a.name})}}var x0=4294967295;function k$(V,$,Z){let J=Z/4294967296,Q=Z;V.setUint32($,J),V.setUint32($+4,Q)}function e0(V,$,Z){let J=Math.floor(Z/4294967296),Q=Z;V.setUint32($,J),V.setUint32($+4,Q)}function VV(V,$){let Z=V.getInt32($),J=V.getUint32($+4);return Z*4294967296+J}function m$(V,$){let Z=V.getUint32($),J=V.getUint32($+4);return Z*4294967296+J}var dZ=-1,oZ=4294967295,aZ=17179869183;function sZ({sec:V,nsec:$}){if(V>=0&&$>=0&&V<=aZ)if($===0&&V<=oZ){let Z=new Uint8Array(4);return new DataView(Z.buffer).setUint32(0,V),Z}else{let Z=V/4294967296,J=V&4294967295,Q=new Uint8Array(8),W=new DataView(Q.buffer);return W.setUint32(0,$<<2|Z&3),W.setUint32(4,J),Q}else{let Z=new Uint8Array(12),J=new DataView(Z.buffer);return J.setUint32(0,$),e0(J,4,V),Z}}function tZ(V){let $=V.getTime(),Z=Math.floor($/1000),J=($-Z*1000)*1e6,Q=Math.floor(J/1e9);return{sec:Z+Q,nsec:J-Q*1e9}}function eZ(V){if(V instanceof Date){let $=tZ(V);return sZ($)}else return null}function VJ(V){let $=new DataView(V.buffer,V.byteOffset,V.byteLength);switch(V.byteLength){case 4:{let Z=$.getUint32(0),J=0;return{sec:Z,nsec:0}}case 8:{let Z=$.getUint32(0),J=$.getUint32(4),Q=(Z&3)*4294967296+J,W=Z>>>2;return{sec:Q,nsec:W}}case 12:{let Z=VV($,4),J=$.getUint32(0);return{sec:Z,nsec:J}}default:throw new a(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${V.length}`)}}function $J(V){let $=VJ(V);return new Date($.sec*1000+$.nsec/1e6)}var f$={type:dZ,encode:eZ,decode:$J};class S0{static defaultCodec=new S0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(f$)}register({type:V,encode:$,decode:Z}){if(V>=0)this.encoders[V]=$,this.decoders[V]=Z;else{let J=-1-V;this.builtInEncoders[J]=$,this.builtInDecoders[J]=Z}}tryToEncode(V,$){for(let Z=0;Z<this.builtInEncoders.length;Z++){let J=this.builtInEncoders[Z];if(J!=null){let Q=J(V,$);if(Q!=null){let W=-1-Z;return new E0(W,Q)}}}for(let Z=0;Z<this.encoders.length;Z++){let J=this.encoders[Z];if(J!=null){let Q=J(V,$);if(Q!=null)return new E0(Z,Q)}}if(V instanceof E0)return V;return null}decode(V,$,Z){let J=$<0?this.builtInDecoders[-1-$]:this.decoders[$];if(J)return J(V,$,Z);else return new E0($,V)}}function ZJ(V){return V instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&V instanceof SharedArrayBuffer}function l0(V){if(V instanceof Uint8Array)return V;else if(ArrayBuffer.isView(V))return new Uint8Array(V.buffer,V.byteOffset,V.byteLength);else if(ZJ(V))return new Uint8Array(V);else return Uint8Array.from(V)}var JJ=100,QJ=2048;class $V{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??S0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.maxDepth=V?.maxDepth??JJ,this.initialBufferSize=V?.initialBufferSize??QJ,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 $V({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),Z=new Uint8Array($),J=new DataView($);Z.set(this.bytes),this.view=J,this.bytes=Z}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 Z=E$(V);this.ensureBufferSizeToWrite(5+Z),this.writeStringHeader(Z),x$(V,this.bytes,this.pos),this.pos+=Z}encodeObject(V,$){let Z=this.extensionCodec.tryToEncode(V,this.context);if(Z!=null)this.encodeExtension(Z);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 Z=l0(V);this.writeU8a(Z)}encodeArray(V,$){let Z=V.length;if(Z<16)this.writeU8(144+Z);else if(Z<65536)this.writeU8(220),this.writeU16(Z);else if(Z<4294967296)this.writeU8(221),this.writeU32(Z);else throw Error(`Too large array: ${Z}`);for(let J of V)this.doEncode(J,$+1)}countWithoutUndefined(V,$){let Z=0;for(let J of $)if(V[J]!==void 0)Z++;return Z}encodeMap(V,$){let Z=Object.keys(V);if(this.sortKeys)Z.sort();let J=this.ignoreUndefined?this.countWithoutUndefined(V,Z):Z.length;if(J<16)this.writeU8(128+J);else if(J<65536)this.writeU8(222),this.writeU16(J);else if(J<4294967296)this.writeU8(223),this.writeU32(J);else throw Error(`Too large map object: ${J}`);for(let Q of Z){let W=V[Q];if(!(this.ignoreUndefined&&W===void 0))this.encodeString(Q),this.doEncode(W,$+1)}}encodeExtension(V){if(typeof V.data==="function"){let Z=V.data(this.pos+6),J=Z.length;if(J>=4294967296)throw Error(`Too large extension object: ${J}`);this.writeU8(201),this.writeU32(J),this.writeI8(V.type),this.writeU8a(Z);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),k$(this.view,this.pos,V),this.pos+=8}writeI64(V){this.ensureBufferSizeToWrite(8),e0(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 O0(V,$){return new $V($).encodeSharedRef(V)}function ZV(V){return`${V<0?"-":""}0x${Math.abs(V).toString(16).padStart(2,"0")}`}var WJ=16,YJ=16;class jV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(V=WJ,$=YJ){this.maxKeyLength=V,this.maxLengthPerKey=$,this.caches=[];for(let Z=0;Z<this.maxKeyLength;Z++)this.caches.push([])}canBeCached(V){return V>0&&V<=this.maxKeyLength}find(V,$,Z){let J=this.caches[Z-1];V:for(let Q of J){let W=Q.bytes;for(let Y=0;Y<Z;Y++)if(W[Y]!==V[$+Y])continue V;return Q.str}return null}store(V,$){let Z=this.caches[V.length-1],J={bytes:V,str:$};if(Z.length>=this.maxLengthPerKey)Z[Math.random()*Z.length|0]=J;else Z.push(J)}decode(V,$,Z){let J=this.find(V,$,Z);if(J!=null)return this.hit++,J;this.miss++;let Q=_V(V,$,Z),W=Uint8Array.prototype.slice.call(V,$,$+Z);return this.store(W,Q),Q}}var LV="array",h0="map_key",g$="map_value",XJ=(V)=>{if(typeof V==="string"||typeof V==="number")return V;throw new a("The type of key must be string or number but "+typeof V)};class v${stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(V){let $=this.getUninitializedStateFromPool();$.type=LV,$.position=0,$.size=V,$.array=Array(V)}pushMapState(V){let $=this.getUninitializedStateFromPool();$.type=h0,$.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===LV){let Z=V;Z.size=0,Z.array=void 0,Z.position=0,Z.type=void 0}if(V.type===h0||V.type===g$){let Z=V;Z.size=0,Z.map=void 0,Z.readCount=0,Z.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var n0=-1,EV=new DataView(new ArrayBuffer(0)),KJ=new Uint8Array(EV.buffer);try{EV.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 B$=RangeError("Insufficient data"),GJ=new jV;class JV{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=EV;bytes=KJ;headByte=n0;stack=new v$;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??S0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.rawStrings=V?.rawStrings??!1,this.maxStrLength=V?.maxStrLength??x0,this.maxBinLength=V?.maxBinLength??x0,this.maxArrayLength=V?.maxArrayLength??x0,this.maxMapLength=V?.maxMapLength??x0,this.maxExtLength=V?.maxExtLength??x0,this.keyDecoder=V?.keyDecoder!==void 0?V.keyDecoder:GJ,this.mapKeyConverter=V?.mapKeyConverter??XJ}clone(){return new JV({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=n0,this.stack.reset()}setBuffer(V){let $=l0(V);this.bytes=$,this.view=new DataView($.buffer,$.byteOffset,$.byteLength),this.pos=0}appendBuffer(V){if(this.headByte===n0&&!this.hasRemaining(1))this.setBuffer(V);else{let $=this.bytes.subarray(this.pos),Z=l0(V),J=new Uint8Array($.length+Z.length);J.set($),J.set(Z,$.length),this.setBuffer(J)}}hasRemaining(V){return this.view.byteLength-this.pos>=V}createExtraByteError(V){let{view:$,pos:Z}=this;return RangeError(`Extra ${$.byteLength-Z} 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,Z;for await(let Y of V){if($)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(Y);try{Z=this.doDecodeSync(),$=!0}catch(X){if(!(X instanceof RangeError))throw X}this.totalPos+=this.pos}if($){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Z}let{headByte:J,pos:Q,totalPos:W}=this;throw RangeError(`Insufficient data in parsing ${ZV(J)} at ${W} (${Q} 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 Z=$,J=-1;for await(let Q of V){if($&&J===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(Q),Z)J=this.readArraySize(),Z=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--J===0)break}catch(W){if(!(W instanceof RangeError))throw W}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 J=V-128;if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V<160){let J=V-144;if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else{let J=V-160;$=this.decodeString(J,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 J=this.lookU8();$=this.decodeString(J,1)}else if(V===218){let J=this.lookU16();$=this.decodeString(J,2)}else if(V===219){let J=this.lookU32();$=this.decodeString(J,4)}else if(V===220){let J=this.readU16();if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else if(V===221){let J=this.readU32();if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else if(V===222){let J=this.readU16();if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V===223){let J=this.readU32();if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V===196){let J=this.lookU8();$=this.decodeBinary(J,1)}else if(V===197){let J=this.lookU16();$=this.decodeBinary(J,2)}else if(V===198){let J=this.lookU32();$=this.decodeBinary(J,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 J=this.lookU8();$=this.decodeExtension(J,1)}else if(V===200){let J=this.lookU16();$=this.decodeExtension(J,2)}else if(V===201){let J=this.lookU32();$=this.decodeExtension(J,4)}else throw new a(`Unrecognized type byte: ${ZV(V)}`);this.complete();let Z=this.stack;while(Z.length>0){let J=Z.top();if(J.type===LV)if(J.array[J.position]=$,J.position++,J.position===J.size)$=J.array,Z.release(J);else continue V;else if(J.type===h0){if($==="__proto__")throw new a("The key __proto__ is not allowed");J.key=this.mapKeyConverter($),J.type=g$;continue V}else if(J.map[J.key]=$,J.readCount++,J.readCount===J.size)$=J.map,Z.release(J);else{J.key=null,J.type=h0;continue V}}return $}}readHeadByte(){if(this.headByte===n0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=n0}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 a(`Unrecognized array type byte: ${ZV(V)}`)}}pushMapState(V){if(V>this.maxMapLength)throw new a(`Max length exceeded: map length (${V}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(V)}pushArrayState(V){if(V>this.maxArrayLength)throw new a(`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 a(`Max length exceeded: UTF-8 byte length (${V}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+$+V)throw B$;let Z=this.pos+$,J;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached(V))J=this.keyDecoder.decode(this.bytes,Z,V);else J=S$(this.bytes,Z,V);return this.pos+=$+V,J}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===h0;return!1}decodeBinary(V,$){if(V>this.maxBinLength)throw new a(`Max length exceeded: bin length (${V}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(V+$))throw B$;let Z=this.pos+$,J=this.bytes.subarray(Z,Z+V);return this.pos+=$+V,J}decodeExtension(V,$){if(V>this.maxExtLength)throw new a(`Max length exceeded: ext length (${V}) > maxExtLength (${this.maxExtLength})`);let Z=this.view.getInt8(this.pos+$),J=this.decodeBinary(V,$+1);return this.extensionCodec.decode(J,Z,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=m$(this.view,this.pos);return this.pos+=8,V}readI64(){let V=VV(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 xV(V,$){return new JV($).decode(V)}class p0{listeners=new Map;addEventListener(V,$){let Z=this.listeners.get(V);if(!Z)Z=new Set,this.listeners.set(V,Z);return Z.add($),()=>{this.removeEventListener(V,$)}}removeEventListener(V,$){let Z=this.listeners.get(V);if(Z){if(Z.delete($),Z.size===0)this.listeners.delete(V)}}emit(V,$){let Z=this.listeners.get(V);if(Z){let J=Array.from(Z);for(let Q of J)Q($)}}emitAll(V){let $=Array.from(this.listeners.keys());for(let Z of $)this.emit(Z,V)}}class P0{getter;static eventName="update";emitter;constructor(V){this.getter=V;this.emitter=new p0}get=()=>this.getter();async emit(){let V=await this.getter();queueMicrotask(()=>this.emitter.emit(P0.eventName,V))}listen(V){return this.emitter.addEventListener(P0.eventName,V),()=>{this.emitter.removeEventListener(P0.eventName,V)}}}function M(V){return[V,0]}function I(V){return[void 0,V]}function NJ(V){if(V<0)console.info("N",V),console.trace();if(typeof V!=="bigint")V=BigInt(V);if(V<0n)return I(10);let $=[];while(V>0n){let Z=Number(V&0x7fn);if(V>>=7n,V>0n)$.push(Z|128);else $.push(Z)}if($.length===0)return M(new Uint8Array([0]));if($.length>8)return I(26);return M(new Uint8Array($))}function IJ(V,$=0){let Z=0n,J=0,Q=$;while(!0){if(Q>=V.length)return I(14);let W=V[Q++];if(W===void 0)return I(14);if(Z|=BigInt(W&127)<<BigInt(J),(W&128)===0){if(Q-$>8)return I(26);return M({value:Z>0x1fffffffffffffn?Z:Number(Z),bytesRead:Q-$})}if(J+=7,J>=56)return I(26)}}class m{data;pos=0;constructor(V){this.data=V}static async fromResponse(V){let $=await V.arrayBuffer(),Z=new Uint8Array($);return new m(Z)}readBigInt(){if(this.pos+8>this.data.length)return I(7);let V=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,M(V)}readDate(){let[V,$]=this.readVarInt();if($!==0)return I($);return M(new Date(V))}readVarInt(){let[V,$]=IJ(this.data,this.pos);if($!==0)return I($);this.pos+=V.bytesRead;let Z=V.value;return M(typeof Z==="bigint"?Number(Z):Z)}readVarString(){let[V,$]=this.readVarInt();if($!==0)return I($);let[Z,J]=this.readBytes(V);if(J!==0)return I(J);let Q=new TextDecoder().decode(Z);return M(Q)}readBytes(V){if(V<0)return I(10);if(this.pos+V>this.data.length)return I(23);let $=this.data.slice(this.pos,this.pos+V);return this.pos+=V,M($)}readVarBytes(){let[V,$]=this.readVarInt();if($!==0)return I($);return this.readBytes(V)}readStruct(V){return V.decode(this)}readStructs(V){let $=[];while(!this.done()){let[Z,J]=this.readStruct(V);if(J!==0)return I(J);$.push(Z)}return M($)}readBytesSeq(V){let $=[];while(!this.done()){let[Z,J]=this.readBytes(V);if(J!==0)return I(J);$.push(Z)}return M($)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class f{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[$,Z]=NJ(V);if(Z!==0)return Z;return this.parts.push($),0}writeVarString(V){let $=new TextEncoder().encode(V),Z=this.writeVarInt($.length);if(Z!==0)return Z;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 Z of $){let J=this.writeStruct(V,Z);if(J!==0)return J}return 0}writeBytesSeq(V){for(let $ of V)this.writeBytes($)}result(){let V=this.parts.reduce((J,Q)=>J+Q.length,0),$=new Uint8Array(V),Z=0;for(let J of this.parts)$.set(J,Z),Z+=J.length;return $}*scan(){for(let V of this.parts)yield V}}async function SV(V,$,Z){let J=new f,Q=J.writeDate($);if(Q!==0)return I(Q);let W=J.result(),Y=await Z.signEd25519(W,V.privateKey);return M({pubKey:V.publicKey,sig:Y,timestamp:$})}async function U0(V,$,Z){let J=Z.now().getTime(),Q=V.timestamp.getTime();if(Math.abs(J-Q)>_$)return 4;let Y=new f;Y.writeDate(V.timestamp);let X=Y.result();if(!await $.checkSigEd25519(V.sig,X,V.pubKey))return 3;return 0}var V0={encode(V,$){let Z=V.writeVarBytes($.id);if(Z!==0)return Z;let J=V.writeDate($.ts);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return I(Z);let[J,Q]=V.readDate();if(Q!==0)return I(Q);return M({id:$,ts:J})}};function QV(V){let $=new f,Z=$.writeStruct(V0,V);if(Z!==0)return I(Z);let J=$.result();return M(J)}var W0={encode(V,$){let Z=V.writeVarBytes($.eid);if(Z!==0)return Z;let J=V.writeVarInt($.off);if(J!==0)return J;let Q=V.writeVarInt($.ctr);if(Q!==0)return Q;let W=V.writeVarInt($.len);if(W!==0)return W;if($.hsh)V.writeBytes($.hsh);return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return I(Z);let J=new m($),[,Q]=V0.decode(J);if(Q!==0)return I(Q);let[W,Y]=V.readVarInt();if(Y!==0)return I(Y);let[X,K]=V.readVarInt();if(K!==0)return I(K);let[G,N]=V.readVarInt();if(N!==0)return I(N);let R;if(G>0){let[z,q]=V.readBytes(t0);if(q!==0)return I(q);R=z}return M({eid:$,off:W,ctr:X,len:G,hsh:R})}};function Y0(V){return Array.from(V).map((Z)=>Z.toString(16).padStart(2,"0")).join("")}function WV(V){if(V.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(V.length/2);for(let Z=0;Z<V.length;Z+=2)$[Z/2]=Number.parseInt(V.substr(Z,2),16);return $}function $0(V,$){if(V===$)return!0;if(V.byteLength!==$.byteLength)return!1;return V.every((Z,J)=>Z===$[J])}var x;if(typeof Uint8Array.prototype.toBase64==="function")x=(V)=>V.toBase64();else x=(V)=>btoa(String.fromCharCode(...V));var q0;if(typeof Uint8Array.fromBase64==="function")q0=(V)=>Uint8Array.fromBase64(V);else q0=(V)=>Uint8Array.from(atob(V),($)=>$.charCodeAt(0));function c0(V,$){let Z=new Uint8Array(V.length+$.length);return Z.set(V,0),Z.set($,V.length),Z}function i$(V,$,Z){return Z.checkSigEd25519(V.sig,V.headCph,$)}async function kV(V,$,Z){let J=c0($.privateKey,V);return(await Z.blake3(J)).slice(0,F0)}async function u$(V,$,Z,J){let Q;if(V.bod&&V.len>0)Q=await Z.blake3(V.bod);let W=new f,Y=W0.encode(W,{...V,hsh:Q});if(Y!==0)return I(Y);let X=W.result(),K=await kV(X,$,Z),G=await J.deriveFromKDM(K),N=await Z.encryptXSalsa20Poly1305Combined(X,G),R=V.bod?await Z.encryptXSalsa20Poly1305Combined(V.bod,G):new Uint8Array(0),z=await Z.signEd25519(N,$.privateKey);return M({sig:z,kdm:K,headCph:N,bodyCph:R})}async function mV(V,$,Z,J,Q){let W=new m(V),[Y,X]=W0.decode(W);if(X!==0)return I(14);let K;try{K=$&&$.length>0?await J.decryptXSalsa20Poly1305Combined($,Z):void 0}catch{return I(20)}let G=Y.hsh&&K===void 0,N=Y.hsh===void 0&&K!==void 0;if(G||N)return I(19);if(Y.hsh&&K){let z=await J.blake3(K);if(!$0(z,Y.hsh))return I(19)}let R=Q??await J.blake3(V);return M({msgHead:Y,bod:K,headHash:R})}class fV{now(){return new Date}}function b$(V,$,Z,J){let Q=$.getTime()-V.getTime(),W=Z.getTime()-J.getTime();return(Q+W)/2}var r0={encode(V,$){if(V.writeVarInt($.quota),$.quota>0){if($.usage===void 0)return 9;V.writeVarInt($.usage)}return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return I(Z);let J;if($>0){let[Q,W]=V.readVarInt();if(W!==0)return I(W);J=Q}return M({quota:$,usage:J})}};var BV={encode(V,$){V.writeBytes(new Uint8Array([$.status]));let Z=V.writeDate($.timeRcvd);if(Z!==0)return Z;let J=V.writeDate($.timeSent);if(J!==0)return J;let Q=V.writeVarInt($.subscription.term);if(Q!==0)return Q;let W=V.writeVarInt($.subscription.elapsed);if(W!==0)return W;let Y=V.writeStruct(r0,$.subscription.stat);if(Y!==0)return Y;let X=V.writeStruct(r0,$.subscription.dyn);if(X!==0)return X;return 0},decode(V){let[$,Z]=V.readBytes(1);if(Z!==0)return I(Z);let J=$[0],[Q,W]=V.readDate();if(W!==0)return I(W);let[Y,X]=V.readDate();if(X!==0)return I(X);let[K,G]=V.readVarInt();if(G!==0)return I(G);let[N,R]=V.readVarInt();if(R!==0)return I(R);let[z,q]=V.readStruct(r0);if(q!==0)return I(q);let[F,w]=V.readStruct(r0);if(w!==0)return I(w);return M({status:J,timeRcvd:Q,timeSent:Y,subscription:{term:K,elapsed:N,stat:z,dyn:F}})}};async function gV(V,$,Z){let{crypto:J,enclave:Q}=V,W=await Q.derive($,Z);return await J.deriveEd25519KeyPair(W)}var vV={encode(V,$){let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarInt($.seq);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return I(Z);let[J,Q]=V.readVarInt();if(Q!==0)return I(Q);return M({headCph:$,seq:J})}};var Z0={encode(V,$){V.writeBytes($.pubKey),V.writeBytes($.sig);let Z=V.writeDate($.timestamp);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readBytes(D$);if(Z!==0)return I(Z);let[J,Q]=V.readBytes(M0);if(Q!==0)return I(Q);let[W,Y]=V.readDate();if(Y!==0)return I(Y);return M({pubKey:$,sig:J,timestamp:W})}};var y$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(Z0,Z);if(W!==0)return W;for(let Y of J)Q.writeVarInt(Y);return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(Z0);if(X!==0)return X;let K=await U0(Y,Q,J);if(K!==0)return K;let{pubKey:G}=Y,[N,R]=await W.hasUser(G);if(R!==0)return R;if(!N)return 5;let[z,q]=$.readVarInt();if(q!==0)return q;if(!$.done())return 8;let[F,w]=await W.listHeads(G,z);if(w!==0)return w;return Z.writeStructs(vV,F)},decodeResp(V){return V.readStructs(vV)}};var iV={encode(V,$){V.writeVarInt($.seq);let Z=V.writeVarBytes($.bodyCph);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return I(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return I(Q);return M({seq:$,bodyCph:J})}};var l$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(Z0,Z);if(W!==0)return W;for(let Y of J){let X=Q.writeVarInt(Y);if(X!==0)return X}return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(Z0);if(X!==0)return X;let K=await U0(Y,Q,J);if(K!==0)return K;let{pubKey:G}=Y,[N,R]=await W.hasUser(G);if(R!==0)return R;if(!N)return 5;let z=[];while(!$.done()){let[w,U]=$.readVarInt();if(U!==0)return U;z.push(w)}console.info(`PULL: ${z.length} bags`);let[q,F]=await W.getBodies(G,z);if(F!==0)return F;if(!q)return 17;for(let{seq:w,bodyCph:U}of q){let P={seq:w,bodyCph:U},H=Z.writeStruct(iV,P);if(H!==0)return H}return 0},decodeResp(V){return V.readStructs(iV)}};var uV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarBytes($.bodyCph);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readBytes(M0);if(Z!==0)return I(Z);let[J,Q]=V.readBytes(F0);if(Q!==0)return I(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return I(Y);let[X,K]=V.readVarBytes();if(K!==0)return I(K);return M({sig:$,kdm:J,headCph:W,bodyCph:X})}};var YV={encode(V,$){let Z=V.writeVarInt($.seq);if(Z!==0)return Z;let J=V.writeVarBytes($.headCph);if(J!==0)return J;let Q=$.bodyCph?$.bodyCph.length:0,W=V.writeVarInt(Q);if(W!==0)return W;if(Q>0){if(!$.bodyCph)return 10;V.writeBytes($.bodyCph)}return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return I(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return I(Q);let[W,Y]=V.readVarInt();if(Y!==0)return I(Y);let X;if(W>0){let[K,G]=V.readBytes(W);if(G!==0)return I(G);X=K}return M({seq:$,headCph:J,bodyCph:X})}};var XV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readBytes(M0);if(Z!==0)return I(Z);let[J,Q]=V.readBytes(F0);if(Q!==0)return I(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return I(Y);return M({sig:$,kdm:J,headCph:W})}};var KV={encode(V,$){if(V.writeVarInt($.idx),V.writeBytes(new Uint8Array([$.status])),$.status===0)V.writeVarInt($.seq);return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return I(Z);let[J,Q]=V.readBytes(1);if(Q!==0)return I(Q);let W=J[0];if(W!==0)return M({idx:$,status:W});let[Y,X]=V.readVarInt();if(X!==0)return I(X);return M({idx:$,status:W,seq:Y})}};var n$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(Z0,Z);if(W!==0)return W;let Y=Q.writeStructs(uV,J);if(Y!==0)return Y;return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W,notifier:Y}=V,[X,K]=$.readStruct(Z0);if(K!==0)return K;let G=await U0(X,Q,J);if(G!==0)return G;let{pubKey:N}=X,[R,z]=await W.hasUser(N);if(z!==0)return z;if(!R)return 5;let[q,F]=$.readStructs(uV);if(F!==0)return F;console.info(`PUSH: ${q.length} bags`);let w=[],U=[];for(let O=0;O<q.length;O++){let D=q[O];if(!await i$(D,N,Q)){let k={idx:O,status:3},S=Z.writeStruct(KV,k);if(S!==0)return S;continue}w.push(O),U.push(D)}let[P,H]=await W.setBags(N,U);if(H!==0)return H;if(!P||P.length!==U.length)return 17;let A=[];for(let O=0;O<U.length;O++){let D=U[O],L=w[O],k=P[O],S=new f,E=S.writeStruct(XV,D);if(E!==0)return E;let B=S.result(),C={seq:k,headCph:B};if(q.length===1&&D.bodyCph.length<=j$)C.bodyCph=D.bodyCph;A.push(C);let g={idx:L,status:0,seq:k},i=Z.writeStruct(KV,g);if(i!==0)return i}if(A.length>0){let O=new f,D=O.writeStructs(YV,A);if(D!==0)return D;let L=O.result();await Promise.resolve(Y.push(N,L))}return 0},decodeResp(V){return V.readStructs(KV)}};var h$={async encodeReq(V,$,Z,J,Q){return Q.writeStruct(Z0,Z)},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(Z0);if(X!==0)return X;let K=await U0(Y,Q,J);if(K!==0)return K;let{pubKey:G}=Y;if(!$.done())return 8;let[N,R]=await W.addUser(G);if(R!==0)return R;return 0},decodeResp(V){return M(void 0)}};class bV{url;websocket;constructor(V){this.url=V}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(V,$,Z=()=>{},J=()=>{}){let{url:Q}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let W=new f;W.writeStruct(Z0,V);let Y=W.result(),X=Y0(Y);return Q.searchParams.set("t",X),this.websocket=new WebSocket(Q),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),J()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Z()},this.websocket.onmessage=(K)=>{let G=new Uint8Array(K.data);$(G)},this.websocket.onerror=(K)=>{console.log(`ERROR: ${JSON.stringify(K)}`),this.websocket=void 0,Z()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var c={user:{path:"/user",endpoint:h$,name:0},push:{path:"/push",endpoint:n$,name:2},peek:{path:"/peek",endpoint:y$,name:1},pull:{path:"/pull",endpoint:l$,name:3}},RJ={0:c.user,2:c.push,1:c.peek,3:c.pull},VX={[c.user.path]:c.user,[c.push.path]:c.push,[c.peek.path]:c.peek,[c.pull.path]:c.pull};class p${url;listener;constructor(V){this.url=V;this.listener=new bV(V)}async call(V,$){let{path:Z}=RJ[V],J=new URL(Z,this.url);try{return await zJ(J,$)}catch{return I(25)}}}var c$=(V)=>{return new p$(V.handle)};async function zJ(V,$){let Z=await fetch(V,{method:"POST",body:$.result().slice()});if(!Z.ok)return I(24);let J=await m.fromResponse(Z);return M(J)}class GV{enclave;crypto;host;clock;transport;updateHostMeta;constructor(V,$,Z,J,Q,W){this.enclave=V;this.crypto=$;this.host=Z;this.clock=J;this.transport=Q;this.updateHostMeta=W}async call(V,$){let{clock:Z,crypto:J,transport:Q}=this,{endpoint:W,name:Y}=V,X=await this.keys(),K=Z.now(),[G,N]=await SV(X,K,J);if(N!==0)return I(N);let R=new f,z=await W.encodeReq(this,X,G,$,R);if(z!==0)return I(z);let q=Z.now(),[F,w]=await Q.call(Y,R),U=Z.now();if(w!==0)return I(w);let[P,H]=F.readStruct(BV);if(H!==0)return I(H);if(P.status!==0)return I(P.status);let O={clockOffset:b$(q,P.timeRcvd,P.timeSent,U),subscription:P.subscription},D=await this.updateHostMeta(O);if(D!==0)return I(D);return W.decodeResp(F)}keys=()=>{let{host:V}=this;return gV(this,V.label,V.idx)};seal=async(V)=>{let{crypto:$,enclave:Z}=this,J=await this.keys();return u$(V,J,$,Z)};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,$,Z)=>{let{clock:J,crypto:Q,host:W,transport:Y}=this,{listener:X}=Y,K=await gV(this,W.label,W.idx),G=J.now(),[N,R]=await SV(K,G,Q);if(R!==0)return R;return await X.connect(N,V,$,Z)};isConnected(){let V=this.transport?.listener;if(V&&typeof V.connected==="function")return V.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var yV={encode(V,$){let Z=V.writeVarString($.lbl);if(Z!==0)return Z;let J=V.writeVarInt($.idx);if(J!==0)return J;let Q=V.writeVarInt($.num);if(Q!==0)return Q;return V.writeBytes($.hsh),V.writeBytes($.sig),0},decode(V){let[$,Z]=V.readVarString();if(Z!==0)return I(Z);let[J,Q]=V.readVarInt();if(Q!==0)return I(Q);let[W,Y]=V.readVarInt();if(Y!==0)return I(Y);let[X,K]=V.readBytes(t0);if(K!==0)return I(K);let[G,N]=V.readBytes(M0);if(N!==0)return I(N);return M({lbl:$,idx:J,num:W,hsh:X,sig:G})}};var lV={encode(V,$){let Z=V.writeStruct(yV,$.head);if(Z!==0)return Z;let J=V.writeVarBytes($.indexEnc);if(J!==0)return J;let Q=V.writeVarBytes($.bodyEnc);if(Q!==0)return Q;return 0},decode(V){let[$,Z]=V.readStruct(yV);if(Z!==0)return I(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return I(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return I(Y);return M({head:$,indexEnc:J,bodyEnc:W})}};var nV={encode(V,$){V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarInt($.lenBody);if(J!==0)return J;if($.lenBody>0&&$.offBody!==void 0){let Q=V.writeVarInt($.offBody);if(Q!==0)return Q}return 0},decode(V){let[$,Z]=V.readBytes(F0);if(Z!==0)return I(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return I(Q);let[W,Y]=V.readVarInt();if(Y!==0)return I(Y);let X;if(W>0){let[K,G]=V.readVarInt();if(G!==0)return I(G);X=K}return M({kdm:$,headCph:J,lenBody:W,offBody:X})}};async function r$(V,$,Z,J,Q){let W=await Q.derive(V,$),Y=await J.deriveEd25519KeyPair(W),X=new f,K=new f,G=0,N=0;for(let H of Z){let A=new f,O=A.writeStruct(W0,H.head);if(O!==0)return I(O);let D=A.result(),L=await kV(D,Y,J),k=await Q.deriveFromKDM(L),S=await J.encryptXSalsa20Poly1305Combined(D,k),E=H.body?await J.encryptXSalsa20Poly1305Combined(H.body,k):new Uint8Array(0),B=H.head.len>0&&H.head.hsh!==void 0?E.length:0,C={kdm:L,headCph:S,lenBody:B,offBody:B>0?N:void 0},g=X.writeStruct(nV,C);if(g!==0)return I(g);if(H.body)K.writeBytes(E),N+=E.length;G++}let R=K.result(),z=X.result(),q=await J.blake3(z),F=await J.signEd25519(q,Y.privateKey),w={lbl:V,idx:$,num:G,hsh:q,sig:F},U=new f;U.writeStruct(lV,{head:w,indexEnc:z,bodyEnc:R});let P=U.result();return M(P)}async function d$(V,$,Z){let[J,Q]=lV.decode(new m(V));if(Q!==0)return I(Q);let{head:W,indexEnc:Y,bodyEnc:X}=J,K=await Z.derive(W.lbl,W.idx),G=await $.deriveEd25519KeyPair(K);if(!await $.checkSigEd25519(W.sig,W.hsh,G.publicKey))return I(3);let R=await $.blake3(Y);if(!$0(R,W.hsh))return I(19);let z=new m(Y),q=[];for(let w=0;w<W.num;w++){let[U,P]=z.readStruct(nV);if(P!==0)return I(P);q.push(U)}if(q.length!==W.num)return I(14);let F=[];for(let w of q){let U=await Z.deriveFromKDM(w.kdm),P=await $.decryptXSalsa20Poly1305Combined(w.headCph,U),[H,A]=W0.decode(new m(P));if(A!==0)return I(A);let O;if(w.lenBody>0&&w.offBody!==void 0){if(H.hsh===void 0)return I(14);let D=X.slice(w.offBody,w.offBody+w.lenBody);O=await $.decryptXSalsa20Poly1305Combined(D,U);let L=await $.blake3(O);if(!$0(L,H.hsh))return I(19)}F.push({head:H,body:O})}return M(F)}async function o$({now:V,bod:$,crypto:Z}){let J=await Z.genRandomBytes(8),Q=new f,W=Q.writeStruct(V0,{id:J,ts:V});if(W!==0)return I(W);let Y=Q.result();return NV({now:V,eid:Y,ctr:0,bod:$,crypto:Z})}async function NV({now:V,eid:$,ctr:Z,bod:J,crypto:Q}){let W=new m($),[Y,X]=V0.decode(W);if(X!==0)return I(X);let K=V.getTime()-Y.ts.getTime(),G,N=J?.length??0;if(J&&N>0)G=await Q.blake3(J);return M({eid:$,off:K,ctr:Z,len:N,hsh:G})}var hX=Symbol("EntityID");function a$(V){return"type"in V}var pX=Symbol("MasterSeed"),cX=Symbol("DerivationSeed"),rX=Symbol("PublicKey"),dX=Symbol("PrivateKey"),oX=Symbol("HostSpecificKeyPair"),aX=Symbol("Hash");function wJ(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 MJ(V){if(!V.bod||V.bod.length===0){let J={off:V.off,ctr:V.ctr,eid:V.eid};return M(J)}let $=xV(V.bod);if(wJ($)===!1)return console.warn("msg body invalid",$),I(14);let Z={off:V.off,ctr:V.ctr,eid:V.eid,gid:$.gid,pid:$.pid,type:$.type,body:$.body};return M(Z)}class IV{applier;emitter=new p0;clearer;onDirtyEids;cacheDriven;peerIngest;constructor(V,$,Z,J){this.applier=V;this.clearer=$,this.onDirtyEids=Z,this.cacheDriven=J?.cacheDriven??!1,this.peerIngest=J?.peerIngest}apply=async(V)=>{let $=[],Z=[];for(let X of V){let[K,G]=MJ(X);if(Z.push(G),G!==0)continue;$.push(K)}let{stats:J,types:Q,eids:W}=await this.applier($),Y=[];for(let X=0;X<V.length;X++){let K=Z[X],G=J[X];if(K!==0){Y.push(K);continue}if(G!==0){Y.push(G);continue}Y.push(0)}if(!this.cacheDriven)for(let X of Q)this.emitter.emit(X,null);if(W.length>0)this.onDirtyEids?.(W);return Y};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 b="entities",RV="entity_type_created_at",hV="entity_type_updated_at",pV="entity_type_group_id",cV="entity_type_parent_id";function FJ(V){let $={bod:V.body,crd:V.createdAt,...V.ctr!==0?{ctr:V.ctr}:{},eid:x(V.eid),gid:V.gid,pid:V.pid?x(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 k0(V){return{body:V.bod,createdAt:V.crd,updatedAt:V.upd,ctr:V.ctr??0,type:V.typ,eid:q0(V.eid),gid:V.gid,pid:V.pid?q0(V.pid):void 0}}class s${db;async init(){this.db=await new Promise((V,$)=>{let Z=indexedDB.open("db",11);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!Q)throw Error("Transaction is null during upgrade");if(!J.objectStoreNames.contains(b))J.createObjectStore(b,{keyPath:"eid",autoIncrement:!1});let W=Q.objectStore(b);if(!W.indexNames.contains(RV))W.createIndex(RV,["typ","crd"],{unique:!1});if(!W.indexNames.contains(hV))W.createIndex(hV,["typ","upd"],{unique:!1});if(!W.indexNames.contains(pV))W.createIndex(pV,["typ","gid"],{unique:!1});if(!W.indexNames.contains(cV))W.createIndex(cV,["typ","pid"],{unique:!1})},Z.onsuccess=()=>V(Z.result),Z.onerror=()=>$(Z.error)})}apply=async(V)=>{let $=new Set,Z=[];if(!this.db)return{stats:V.map(()=>16),types:$,eids:Z};let J=this.db.transaction(b,"readwrite"),Q=J.objectStore(b);return new Promise((W)=>{let Y=Array(V.length).fill(0);if(V.length<1){W({stats:[],types:$,eids:Z});return}J.oncomplete=()=>{W({stats:Y,types:$,eids:Z})},J.onerror=()=>{for(let K=0;K<Y.length;K++)if(Y[K]===void 0)Y[K]=18;W({stats:Y,types:$,eids:Z})};let X=new Map;for(let K=0;K<V.length;K++){let G=V[K],N=x(G.eid),R={op:G,index:K},z=X.get(N);if(z)z.push(R);else X.set(N,[R])}for(let[K,G]of X){if(G.length<1)continue;let N=Q.get(K);N.onsuccess=()=>{let R=N.result,z=R?k0(R):void 0,q=!1;for(let{op:F,index:w}of G){let[U,P]=m0(z,F);if(P!==0){Y[w]=P;continue}if(q=!0,U)$.add(U.type);else if(z)$.add(z.type);z=U}if(q)Z.push(G[0].op.eid);if(z){let F=FJ(z),w=Q.put(F);w.onerror=(U)=>{U.preventDefault();for(let{index:P}of G)Y[P]=18}}else{let F=Q.delete(K);F.onerror=()=>{for(let{index:w}of G)Y[w]=18}}},N.onerror=()=>{for(let{index:R}of G)Y[R]=18}}})};async clear(){if(!this.db)return 16;let V=this.db.transaction(b,"readwrite"),$=V.objectStore(b);return new Promise((Z)=>{V.oncomplete=()=>Z(0),V.onerror=()=>Z(18),$.clear()})}async getEnt(V){if(!this.db)return I(16);let $=x(V),J=this.db.transaction(b,"readonly").objectStore(b);return new Promise((Q)=>{let W=J.get($);W.onsuccess=()=>{let Y=W.result;if(!Y)Q(M(void 0));else{let X=k0(Y);Q(M(X))}},W.onerror=()=>Q(I(18))})}async getAllOfTypeUpdatedBetween(V,$,Z){if(!this.db)return I(16);let Q=this.db.transaction(b,"readonly").objectStore(b).index(hV);return new Promise((W)=>{let Y=Q.getAll(IDBKeyRange.bound([V,$],[V,Z]));Y.onsuccess=()=>{let X=Y.result;W(M(X.map(k0)))},Y.onerror=()=>W(I(18))})}async getGroupMembers(V,$){if(!this.db)return I(16);let J=this.db.transaction(b,"readonly").objectStore(b).index(pV);return new Promise((Q)=>{let W=J.getAll(IDBKeyRange.only([V,$]));W.onsuccess=()=>{let Y=W.result;Q(M(Y.map(k0)))},W.onerror=()=>Q(I(18))})}async getAllOfType(V){if(!this.db)return I(16);let Z=this.db.transaction(b,"readonly").objectStore(b).index(RV);return new Promise((J)=>{let Q=Z.getAll(IDBKeyRange.bound([V],[V,[]]));Q.onsuccess=()=>{let W=Q.result;J(M(W.map(k0)))},Q.onerror=()=>J(I(18))})}async getAllEntities(V){if(!this.db)return I(16);if("pid"in V){let $=x(V.pid),J=this.db.transaction(b,"readonly").objectStore(b).index(cV);return new Promise((Q)=>{let W=J.getAll(IDBKeyRange.only([V.type,$]));W.onsuccess=()=>{let X=W.result.map(k0);Q(M(X))},W.onerror=()=>Q(I(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[$,Z]=await this.getAllEntities(V);if(Z!==0)return I(Z);return M($)}async countEntities({type:V}){if(!this.db)return I(16);let Z=this.db.transaction(b,"readonly").objectStore(b).index(RV);return new Promise((J)=>{let Q=IDBKeyRange.bound([V],[V,[]]),W=Z.count(Q);W.onsuccess=()=>J(M(W.result)),W.onerror=()=>J(I(18))})}}async function t$(){let V=new s$;return await V.init(),V}class rV{ents=new Map;useIndex;byType=new Map;byTypePid=new Map;byTypeGid=new Map;constructor(V=[],$){this.useIndex=$?.indexes!==!1;for(let Z of V)this.put(Z)}put(V){let $=x(V.eid),Z=this.ents.get($);if(Z)this.unindex($,Z);this.ents.set($,V),this.index($,V)}del(V){let $=this.ents.get(V);if(!$)return;this.unindex(V,$),this.ents.delete(V)}index(V,$){if(!this.useIndex)return;let Z=this.byType.get($.type);if(!Z)Z=new Map,this.byType.set($.type,Z);if(Z.set(V,$),$.pid){let J=x($.pid),Q=this.byTypePid.get($.type);if(!Q)Q=new Map,this.byTypePid.set($.type,Q);let W=Q.get(J);if(!W)W=new Map,Q.set(J,W);W.set(V,$)}if(typeof $.gid==="string"){let J=this.byTypeGid.get($.type);if(!J)J=new Map,this.byTypeGid.set($.type,J);let Q=J.get($.gid);if(!Q)Q=new Map,J.set($.gid,Q);Q.set(V,$)}}unindex(V,$){if(!this.useIndex)return;let Z=this.byType.get($.type);if(Z){if(Z.delete(V),Z.size===0)this.byType.delete($.type)}if($.pid){let J=x($.pid),Q=this.byTypePid.get($.type),W=Q?.get(J);if(W){if(W.delete(V),W.size===0)Q?.delete(J)}if(Q&&Q.size===0)this.byTypePid.delete($.type)}if(typeof $.gid==="string"){let J=this.byTypeGid.get($.type),Q=J?.get($.gid);if(Q){if(Q.delete(V),Q.size===0)J?.delete($.gid)}if(J&&J.size===0)this.byTypeGid.delete($.type)}}clearIndexes(){this.byType.clear(),this.byTypePid.clear(),this.byTypeGid.clear()}bucketList(V){if(!V||V.size===0)return[];let $=[];for(let Z of V.values())$.push(Z);return $}async apply(V){let $=new Set,Z=[],J=[];for(let Q of V){let W=x(Q.eid),Y=this.ents.get(W),[X,K]=m0(Y,Q);if(K!==0){J.push(K);continue}if(X)$.add(X.type);else if(Y)$.add(Y.type);if(X)this.put(X);else this.del(W);Z.push(Q.eid),J.push(0)}return{stats:J,types:$,eids:Z}}async clear(){return this.ents.clear(),this.clearIndexes(),0}async getEnt(V){let $=x(V),Z=this.ents.get($);return M(Z)}async getAllEntities({type:V,gid:$,pid:Z,updatedBetween:J}){if(this.useIndex){if(Z!==void 0){let W=x(Z);return M(this.bucketList(this.byTypePid.get(V)?.get(W)))}if($!==void 0)return M(this.bucketList(this.byTypeGid.get(V)?.get($)));if(J!==void 0){let W=[],Y=this.byType.get(V);if(Y){for(let X of Y.values())if(X.updatedAt>=J.start&&X.updatedAt<=J.end)W.push(X)}return M(W)}return M(this.bucketList(this.byType.get(V)))}let Q=[];if(Z!==void 0){for(let W of this.ents.values())if(W.type===V&&W.pid&&$0(W.pid,Z))Q.push(W)}else if($!==void 0){for(let W of this.ents.values())if(W.type===V&&(typeof W.gid==="string"&&W.gid===$))Q.push(W)}else if(J!==void 0){for(let W of this.ents.values())if(W.type===V&&W.updatedAt>=J.start&&W.updatedAt<=J.end)Q.push(W)}else for(let W of this.ents.values())if(W.type===V)Q.push(W);return M(Q)}async getEntities(V){let[$,Z]=await this.getAllEntities(V);if(Z!==0)return I(Z);return M($)}async countEntities({type:V}){if(this.useIndex)return M(this.byType.get(V)?.size??0);let $=0;for(let Z of this.ents.values())if(Z.type===V)$+=1;return M($)}}async function e$(V){let $=await t$();if(V?.cache===!1)return $;return new dV($,void 0,{indexes:V?.indexes})}class dV{mem;durable;warmed=new Set;listeners=new Set;chain=Promise.resolve();constructor(V,$,Z){if(this.durable=V,this.mem=new rV($??[],{indexes:Z?.indexes}),$)for(let J of $)this.warmed.add(J.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 $=HJ(this.mem,V);this.emit($.types);let Z=await this.durable.apply(V),{changed:J,status:Q}=await this.pullEids(V.map((W)=>W.eid));this.emit(J);for(let W of Z.types)this.warmed.add(W);if(Q!==0)return{stats:V.map(()=>Q),types:Z.types,eids:Z.eids};return Z})}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:Z}=await this.pullEids(V);return this.emit($),Z})}async pullEids(V){let $=new Set,Z=new Set;for(let J of V){let Q=x(J);if(Z.has(Q))continue;Z.add(Q);let W=this.mem.ents.get(Q),[Y,X]=await this.durable.getEnt(J);if(X!==0)return{changed:$,status:X};if(Y){if(this.mem.put(Y),this.warmed.add(Y.type),!W||!UJ(W,Y)){if($.add(Y.type),W&&W.type!==Y.type)$.add(W.type)}}else if(W)this.mem.del(Q),$.add(W.type)}return{changed:$,status:0}}async warmType(V){if(this.warmed.has(V))return 0;let[$,Z]=await this.durable.getEntities({type:V});if(Z!==0)return Z;if($)for(let J of $){let Q=x(J.eid),W=this.mem.ents.get(Q);if(!W||PJ(J,W))this.mem.put(J)}return this.warmed.add(V),0}async getEnt(V){let $=x(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[Z,J]=await this.durable.getEnt(V);if(J!==0)return I(J);if(Z)this.mem.put(Z),this.warmed.add(Z.type);return M(Z)})}async getEntities(V){let $=await this.run(()=>this.warmType(V.type));if($!==0)return I($);return this.mem.getEntities(V)}async countEntities({type:V}){let $=await this.run(()=>this.warmType(V));if($!==0)return I($);return this.mem.countEntities({type:V})}}function UJ(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(!$0(V.eid,$.eid))return!1;if(!qJ(V.pid,$.pid))return!1;return OJ(V.body,$.body)}function qJ(V,$){if(V===void 0&&$===void 0)return!0;if(V===void 0||$===void 0)return!1;return $0(V,$)}function OJ(V,$){if(Object.is(V,$))return!0;if(V instanceof Uint8Array&&$ instanceof Uint8Array)return $0(V,$);if(V instanceof Date&&$ instanceof Date)return V.getTime()===$.getTime();try{return $0(O0(V),O0($))}catch{return!1}}function PJ(V,$){let Z=V.updatedAt.getTime(),J=$.updatedAt.getTime();if(Z!==J)return Z>J;return V.ctr>$.ctr}function HJ(V,$){let Z=new Set,J=[];for(let Q of $){let W=x(Q.eid),Y=V.ents.get(W),[X,K]=m0(Y,Q);if(K!==0){J.push(K);continue}if(X)Z.add(X.type);else if(Y)Z.add(Y.type);if(X)V.put(X);else V.del(W);J.push(0)}return{stats:J,types:Z}}function VZ(V){let $=new m(V.eid),[Z,J]=$.readStruct(V0);if(J!==0)return I(J);return M({eid:V.eid,ctr:V.ctr,updatedAt:new Date(Z.ts.getTime()+V.off)})}function m0(V,$){let Z=new m($.eid),[J,Q]=Z.readStruct(V0);if(Q!==0)return I(Q);let W=new Date(J.ts.getTime()+$.off);if(V!==void 0&&W<=V.updatedAt)return I(15);if(a$($))return M({eid:$.eid,gid:$.gid,pid:$.pid,type:$.type,createdAt:J.ts,updatedAt:W,ctr:$.ctr,body:$.body});else return M(void 0)}class zV{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 $Z=100;class oV{timer=null;delayMs;work;tail=new zV;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 ZZ(V){let $=new m(V.eid),[Z,J]=V0.decode($);if(J!==0)return;return Z.ts.getTime()+V.off}function CJ(V,$){let Z=ZZ(V),J=ZZ($);if(Z===void 0&&J===void 0)return 0;if(Z===void 0)return 1;if(J===void 0)return-1;if(J!==Z)return J-Z;return $.ctr-V.ctr}function d0(V,$){return V.slice().sort((Z,J)=>CJ($(Z),$(J)))}var aV={phase:"idle"},wV=50;function JZ(V,$,Z){if(V<=0||$<=0)return!1;if(V===1||V===$)return!0;return V%Z===0}function QZ(V,$){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(V,$);return}let Z=URL.createObjectURL(V),J=document.createElement("a");J.href=Z,J.download=$,document.body.appendChild(J),J.click(),document.body.removeChild(J),URL.revokeObjectURL(Z)}function WZ(V,$,Z){let J=[],Q=[],W=0;for(let Y of V){let X=$(Y);if(Q.length>0&&W+X>Z)J.push(Q),Q=[],W=0;if(Q.push(Y),W+=X,W>=Z)J.push(Q),Q=[],W=0}if(Q.length>0)J.push(Q);return J}async function YZ(V,$,Z){let J=V.length;if(J<1)return[];let Q=Array(J),W=0,Y=Math.min(Math.max(1,$),J),X=async()=>{while(!0){let G=W;if(W+=1,G>=J)return;Q[G]=await Z(V[G],G)}},K=[];for(let G=0;G<Y;G++)K.push(X());return await Promise.all(K),Q}async function sV(V,$,Z,J){let Q=new m(V.headCph),[W,Y]=Q.readStruct(XV);if(Y!==0)return I(Y);let{sig:X,kdm:K,headCph:G}=W;if(!await J.checkSigEd25519(X,G,$.publicKey))return I(3);let R=await Z.deriveFromKDM(K),z;try{z=await J.decryptXSalsa20Poly1305Combined(G,R)}catch{return I(20)}return M({kdm:K,headEnc:z})}var B0="f",MV="t",f0="e";function TJ(V){if(V===!0||V===MV)return MV;if(V===f0)return f0;return B0}function XZ(V){return V!==0&&V!==15&&V!==18&&V!==17}function tV(V,$,Z){if(V.apld=$,$===f0&&Z!==void 0)V.err=Z;else delete V.err}async function FV(V,$,Z){let J=TJ($.apld),Q=$.body,W=Q?.length??0,Y;if(Q&&W>0)Y=await Z.blake3(Q);let X={eid:$.eid,off:$.off??0,ctr:$.ctr??0,len:W,hsh:Y},K={hash:V,head:X,apld:J};if(Q!==void 0)K.body=Q;if(J===f0&&$.err!==void 0)K.err=$.err;return K}var eV=1048576,V$=1048576,AJ=64;function DJ(V){return V.sig.length+V.kdm.length+V.headCph.length+V.bodyCph.length}async function _J(V,$,Z,J,Q){if(J.length<1)return 0;let[W,Y]=await V.push(J);if(Y!==0)return Y;if(!W)return 27;for(let K of W){if(K.status!==0){console.error("push err",K);continue}let G=Q[K.idx];if(!G){console.error("no hash",K);continue}await $.uploads.deq(Z,[G])}let X=await $.hosts.get(Z);if(X){let K=X.lastSeq,G=K,N=[];for(let R of W)if(R.status===0)N.push(R.seq);N.sort((R,z)=>R-z);for(let R of N)if(R===K+1)K=R;if(K>G)await $.hosts.touch(Z,K)}return 0}async function KZ(V,$){if($.length<1)return M([]);let Z=new Map,J=[];for(let X of $)Z.set(X.seq,X),J.push(X.seq);let[Q,W]=await V.pull(J);if(W!==0)return I(W);if(!Q)return I(27);let Y=[];for(let{seq:X,bodyCph:K}of Q){let G=Z.get(X);if(!G)continue;Y.push({dl:G,bodyCph:K})}return M(Y)}async function jJ(V,$,Z,J){if(J.length<1)return M({parts:[],hashes:[]});let Q=[],W=[],Y=[],X=new Map;for(let{dl:G,bodyCph:N}of J){let{head:R,kdm:z,seq:q,host:F}=G,[w,U]=await GZ(G,Z);if(U!==0||!w){let E=X.get(F)??[];E.push(q),X.set(F,E);continue}let{headEnc:P,headEncHash:H}=w,A=await $.deriveFromKDM(z),[O,D]=await mV(P,N,A,Z,H);if(D!==0||!O){let E=X.get(F)??[];E.push(q),X.set(F,E);continue}let L={head:R,body:O.bod},k=O.headHash;Y.push({key:k,data:wZ(L)}),Q.push(L),W.push(k);let S=X.get(F)??[];S.push(q),X.set(F,S)}let K=await V.messages.add(Y);for(let[G,N]of X)await V.downloads.deq(G,N);for(let G=0;G<K.length;G++){let N=K[G];if(N!==0&&N!==15)console.error("ERR storing",_[N],"for message",G)}return M({parts:Q,hashes:W})}async function GZ(V,$){let Z=V.headEnc;if(!Z){let Q=new f,W=Q.writeStruct(W0,V.head);if(W!==0)return I(W);Z=Q.result()}if(V.headEncHash)return M({headEnc:Z,headEncHash:V.headEncHash});let J=await $.blake3(Z);return M({headEnc:Z,headEncHash:J})}async function NZ(V,$,Z){let J=new Set;for(let Y of $)J.add(x(Y));if(J.size<1)return;let Q=Array.from(await V.downloads.list());if(Q.length<1)return;let W=new Map;for(let Y of Q){let X;if(Y.headEncHash)X=x(Y.headEncHash);else{let[G,N]=await GZ(Y,Z);if(N!==0||!G)continue;X=x(G.headEncHash)}if(!J.has(X))continue;let K=W.get(Y.host)??[];K.push(Y.seq),W.set(Y.host,K)}for(let[Y,X]of W)await V.downloads.deq(Y,X)}async function IZ({conn:V,store:$,enclave:Z,host:J,crypto:Q,onProgress:W,peekProgressEvery:Y,peekConcurrency:X}){let K=await V.keys(),G=[],[N,R]=await V.peek(J.lastSeq);if(R!==0)return R;let z=N.length,q=Y??wV,F=X??AJ;if(W&&z>0)W({phase:"peek",host:J.label,done:0,total:z});let w=0,U=await YZ(N,F,async(P)=>{let[H,A]=await sV(P,K,Z,Q),O;if(A!==0||!H)O={ok:!1,seq:P.seq,stat:A};else{let D=await Q.blake3(H.headEnc);O={ok:!0,seq:P.seq,kdm:H.kdm,headEnc:H.headEnc,headEncHash:D}}if(w+=1,W&&JZ(w,z,q))W({phase:"peek",host:J.label,done:w,total:z});return O});for(let P of U){if(!P.ok){console.error("peek: decrypting item head",P.stat);continue}if(await $.messages.has(P.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await $.uploads.deq(J.label,[P.headEncHash]),await $.downloads.deq(J.label,[P.seq]);continue}let A=new m(P.headEnc),[O,D]=A.readStruct(W0);if(D!==0){console.error("peek: reading item head",D);continue}G.push({kdm:P.kdm,head:O,seq:P.seq,host:J.label,headEnc:P.headEnc,headEncHash:P.headEncHash})}if(await $.downloads.enq(G),N.length>0){let P=Math.max(...N.map((H)=>H.seq));await $.hosts.touch(J.label,P)}if(W)W({phase:"peek",host:J.label,done:z,total:z});return 0}async function RZ({conn:V,store:$,host:Z,maxPushBytes:J,onProgress:Q}){let W=J??eV,Y=await $.uploads.list(Z.label),X=Y.length,K=0;if(Q&&X>0)Q({phase:"push",host:Z.label,done:0,total:X});let G=[],N=[],R=0,z=async()=>{if(G.length<1)return 0;let q=G.length,F=await _J(V,$,Z.label,G,N);if(G=[],N=[],R=0,F===0){if(K+=q,Q)Q({phase:"push",host:Z.label,done:K,total:X})}return F};for(let q of Y){let F=await $.messages.get(q);if(!F){K+=1;continue}let w={...F.head,bod:F.body},[U,P]=await V.seal(w);if(P!==0)return P;if(!U)return 12;let H=DJ(U);if(G.length>0&&R+H>W){let A=await z();if(A!==0)return A}if(G.push(U),N.push(q),R+=H,R>=W){let A=await z();if(A!==0)return A}}return z()}async function zZ({conn:V,store:$,enclave:Z,host:J,crypto:Q,maxPullBytes:W,onProgress:Y},X){let K=W??V$,G=await $.downloads.list(),N=Array.from(G).filter((U)=>U.host===J.label);if(N.length<1)return 15;let R=d0(N,(U)=>U.head),z=WZ(R,(U)=>U.head.len,K),q=R.length,F=0;if(Y)Y({phase:"pull",host:J.label,done:0,total:q});let w=KZ(V,z[0]);for(let U=0;U<z.length;U++){let[P,H]=await w;if(H!==0||!P)return H;if(F+=z[U].length,Y)Y({phase:"pull",host:J.label,done:F,total:q});let A=z[U+1];if(A)w=KZ(V,A);if(Y)Y({phase:"open",host:J.label,done:F,total:q});let O=d0(P,(L)=>L.dl.head),[,D]=await jJ($,Z,Q,O);if(D!==0)return D;if(X){if(Y)Y({phase:"exec",host:J.label,done:F,total:q});await X()}}return 0}function wZ({head:V,body:$}){let Z={eid:V.eid,body:$,apld:B0};if(V.off!==0)Z.off=V.off;if(V.ctr!==0)Z.ctr=V.ctr;return Z}async function MZ(V,{conn:$,store:Z,enclave:J,host:Q,crypto:W,onProgress:Y},X){let K=Q.label,G=await $.keys(),N=new m(V),[R,z]=N.readStructs(YV);if(z!==0){console.error("Failed decoding notif",_[z]);return}let q=!1,w=(await Z.hosts.get(K))?.lastSeq,U=[],P=!1;for(let O of R){let[D,L]=await sV({seq:O.seq,headCph:O.headCph},G,J,W);if(L!==0){console.error("Failed decrypting notif",_[L]);continue}let k=await W.blake3(D.headEnc);if(await Z.messages.has(k))continue;let S=new m(D.headEnc),[E,B]=S.readStruct(W0);if(B!==0){console.error("Failed to parse head",_[B]);continue}if(!O.bodyCph&&E.len>0)P=!0,await Z.downloads.enq([{seq:O.seq,host:K,kdm:D.kdm,head:E,headEnc:D.headEnc,headEncHash:k}]);else U.push({...D,head:E,bodyCph:O.bodyCph,headEncHash:k});if(w===void 0||O.seq!==w+1)console.log("out of seq",O.seq,w),q=!0;else w=O.seq}if(w!==void 0)await Z.hosts.touch(Q.label,w);let H=[];for(let O of U){let D=await J.deriveFromKDM(O.kdm),[L,k]=await mV(O.headEnc,O.bodyCph,D,W);if(k!==0){console.error("Failed to open body",_[k]);continue}H.push({key:O.headEncHash,data:wZ({head:O.head,body:L.bod})})}let A=await Z.messages.add(H);for(let O=0;O<A.length;O++){let D=A[O];if(D!==0&&D!==15)console.error("ERR storing",_[D],"for message",O)}if(Y&&H.length>0)Y({phase:"open",host:Q.label,done:H.length,total:H.length});if(q||P||H.length>0)X()}class $${clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new zV;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=wV;lastProgress=aV;scheduledSync;constructor(V,$,Z,J,Q,W=!0,Y=eV,X=V$,K){this.clock=V;this.state=$;this.store=Z;this.transport=J;this.crypto=Q;this.forceSkewHandlingByDefault=W;this.onScheduleSync=K;this.maxPushBytes=Y,this.maxPullBytes=X,this.clientState=new P0(()=>this.getClientState()),this.xferState=new P0(()=>this.getXferState()),this.scheduledSync=new oV($Z,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,Z=await V.seed.load(),J=await V.hosts.list(),Q=!1;for(let W of $.values())if(W.isConnected()){Q=!0;break}return{hasSeed:Z!==void 0,hasHost:Array.from(J).length>0,connected:Q}}async getXferState(){let{uploads:V,downloads:$}=this.store,Z=await V.count();return{numDownloads:await $.count(),numUploads:Z,progress:this.lastProgress}}apply=(V,$)=>{return this.enqueueApplyJob(()=>this.doApply(V,$))};async doApply(V,$={enqueueUpload:!0,triggerUpload:!0}){let Z=[],J=[];for(let{head:W,body:Y}of V){let X=new f;X.writeStruct(W0,W);let K=X.result(),G=await this.crypto.blake3(K),N={eid:W.eid,body:Y,apld:B0};if(W.off!==0)N.off=W.off;if(W.ctr!==0)N.ctr=W.ctr;Z.push(G),J.push({key:G,data:N})}await this.store.messages.add(J),await NZ(this.store,Z,this.crypto);let Q=await this.doApplyHashes(Z);if($.enqueueUpload){let W=[];for(let Y=0;Y<Z.length;Y++){let X=Q[Y];if(X===0||X===15)W.push(Z[Y])}if(W.length>0){let Y=await this.store.hosts.list();for(let X of Y)await this.store.uploads.enq(X.label,W);this.xferState.emit()}}if($.triggerUpload)this.scheduleSync();return Q}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(B0);if(V.length<1)return[];let $=d0(V,(Z)=>Z.head);return this.applyStored($)}applyHashes=(V)=>{return this.enqueueApplyJob(()=>this.doApplyHashes(V))};async doApplyHashes(V){let $=[];for(let Q of V){let W=await this.store.messages.get(Q);if(W)$.push(W)}let Z=await this.applyStored($),J=new Map;for(let Q=0;Q<$.length;Q++)J.set(x($[Q].hash),Z[Q]??12);return V.map((Q)=>J.get(x(Q))??13)}async applyStored(V){if(V.length<1)return[];let $=V.map((W)=>({...W.head,bod:W.body})),Z=await this.state.apply($),J=[],Q=[];for(let W=0;W<V.length;W++){let Y=Z[W];if(Y===0||Y===15)J.push(V[W].hash);else if(Y!==void 0&&XZ(Y))Q.push({key:V[W].hash,err:Y})}if(J.length>0)await this.store.messages.markApplied(J);if(Q.length>0)await this.store.messages.markFailed(Q);return Z}async insertRaw(V){let{clock:$,crypto:Z}=this,[J,Q]=await o$({now:$.now(),bod:V,crypto:Z});if(Q!==0)return I(Q);let Y=(await this.apply([{head:J,body:V}]))[0];if(Y!==0&&Y!==15)return I(Y??12);return M(J)}async makeUpdate(V,$){let{clock:Z,crypto:J}=this,Q=Z.now();if(V.updatedAt.getTime()>Q.getTime())return I(4);let W=V.ctr+1,[Y,X]=await NV({now:Q,eid:V.eid,ctr:W,bod:$,crypto:J});if(X!==0)return I(X);return M({head:Y,body:$})}async updateWithSkew(V,$,Z){if(Z===!1)return I(4);let{clock:J,crypto:Q}=this,W=J.now(),Y=new m(V.eid),[X,K]=Y.readStruct(V0);if(K!==0)return I(K);let G=V.updatedAt.getTime()-X.ts.getTime(),N={eid:V.eid,off:G+1,ctr:V.ctr+1,len:0},z=(await this.apply([{head:N,body:void 0}]))[0];if(z!==0&&z!==15)return I(z??12);if($===void 0)return M(N);let[q,F]=QV({id:X.id,ts:W});if(F!==0)return I(F);let[w,U]=await NV({now:W,eid:q,ctr:0,bod:$,crypto:Q});if(U!==0)return I(U);let H=(await this.apply([{head:w,body:$}]))[0];if(H!==0&&H!==15)return I(H??12);return M(w)}async updateRaw(V,$,Z=this.forceSkewHandlingByDefault){if(V.updatedAt.getTime()>this.clock.now().getTime())return this.updateWithSkew(V,$,Z);return this.enqueueApplyJob(async()=>{let[J,Q]=await this.makeUpdate(V,$);if(Q!==0)return I(Q);let Y=(await this.doApply([J]))[0];if(Y!==0&&Y!==15)return I(Y??12);return M(J.head)})}async insert(V){let{body:$,type:Z,gid:J,pid:Q}=V,Y=O0({body:$,type:Z,gid:J,pid:Q});return this.insertRaw(Y)}async update(V){let{prior:$,body:Z,type:J,gid:Q,pid:W,force:Y}=V,K=O0({body:Z,type:J,gid:Q,pid:W});return this.updateRaw($,K,Y??this.forceSkewHandlingByDefault)}async delete(V){let $=V.force??!0;if("prior"in V)return this.updateRaw(V.prior,void 0,$);let[Z,J]=await this.revFromArchive(V.eid);if(J!==0)return I(J);return this.updateRaw(Z,void 0,$)}async revFromArchive(V){let $=await this.store.messages.last(V);if($)return VZ($.head);let Z=new m(V),[J,Q]=Z.readStruct(V0);if(Q!==0)return I(Q);return M({eid:V,ctr:-1,updatedAt:J.ts})}async genEID(V){let{clock:$,crypto:Z}=this,J=$.now();if(V!==void 0)return QV({id:V,ts:J});let Q=await Z.genRandomBytes(8);return QV({id:Q,ts:J})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:V,crypto:$,store:Z}=this,J=await Z.seed.load();if(!J)return 22;await this.drainApplyQueue();for(let[Q,W]of V){let Y=await Z.hosts.get(Q);if(!Y)continue;let X={conn:W,store:Z,enclave:J,host:Y,crypto:$,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},K=await IZ(X);if(K!==0)return console.error(`Failed to peek: ${K}`),K;this.xferState.emit();let G=await RZ(X);if(G!==0)return console.error(`Failed to push: ${G}`),G;this.xferState.emit();let N=await zZ(X,async()=>{await this.drainApplyQueue()});if(N!==0&&N!==15)return console.error(`Failed to pull: ${N}`),N;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=aV,this.clientState.emit(),this.xferState.emit()}import=async(V,$)=>{let{crypto:Z,store:J}=this,Q=$?.onProgress,W=await J.seed.load();if(!W)return 22;console.time("import: decoding file...");let Y=await V.bytes(),[X,K]=await d$(Y,Z,W);if(K!==0)return K;console.timeEnd("import: decoding file...");let G=0;while(G<X.length){let N=0,R=0,z=G;for(let w=G;w<X.length&&R<100&&N<102400;w++)N+=X[w].head.len,R++,z=w+1;let q=X.slice(G,z);console.time(`import: applying [${G}, ${z}]`);let F=await this.apply(q,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${G}, ${z}]`);for(let w=0;w<q.length;w++){let U=F[w];if(U!==0&&U!==15)console.warn(`failed to import msg ${G+w}: ${_[U]}`)}if(Q)queueMicrotask(()=>Q(z,X.length,0));this.emitProgress({phase:"import",done:z,total:X.length}),G=z}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,Z=await $.seed.load();if(!Z)return I(22);let J=await $.messages.list();return r$("export",0,J,V,Z)}async export(V){let[$,Z]=await this.exportBytes();if(Z!==0)return Z;if(!$)return 12;let J=new Blob([$.slice()]);return QZ(J,V),0}async link(V,$=!0){if(await this.store.hosts.add(V),this.clientState.emit(),$){let Z=await this.store.hosts.get(V.label);if(Z)await this.connectToHost(Z)}}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,Z=!0)=>{let{clock:J,connections:Q,crypto:W,store:Y,transport:X}=this,K=Q.get(V.label);if(K){if(K.isConnected())return;try{K.closeListener()}catch{}Q.delete(V.label)}let G=await Y.seed.load();if(!G)return;console.info(`Connecting to ${V.handle} (${V.label})`);let N=new GV(G,W,V,J,X(V),(R)=>Y.hosts.set(V.label,R));if(await N.register(),$)await N.listen(async(R)=>{let z={conn:N,store:Y,enclave:G,host:V,crypto:W,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return MZ(R,z,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(Q.set(V.label,N),this.clientState.emit(),Z)this.scheduleSync()};async connect(V=!0,$=!0){let{connectToHost:Z,scheduleSync:J,store:Q}=this;if(!await Q.seed.load())return;await this.drainApplyQueue();let Y=await Q.hosts.list();for(let X of Y)await Z(X,V,!1);if($)J()}disconnect=async()=>{for(let V of this.connections.values())try{V.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var H0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function UV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function Z$(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function p(V,...$){if(!Z$(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function J$(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function FZ(V,$){p(V);let Z=$.outputLen;if(V.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function Q$(V){if(typeof V!=="boolean")throw Error(`boolean expected, not ${V}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var N0=(V)=>new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4));var LJ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!LJ)throw Error("Non little-endian hardware is not supported");function EJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function qV(V){if(typeof V==="string")V=EJ(V);else if(Z$(V))V=OV(V);else throw Error("Uint8Array expected, got "+typeof V);return V}function UZ(V,$){if($==null||typeof $!=="object")throw Error("options must be defined");return Object.assign(V,$)}function qZ(V,$){if(V.length!==$.length)return!1;let Z=0;for(let J=0;J<V.length;J++)Z|=V[J]^$[J];return Z===0}var OZ=(V,$)=>{function Z(J,...Q){if(p(J),V.nonceLength!==void 0){let N=Q[0];if(!N)throw Error("nonce / iv required");if(V.varSizeNonce)p(N);else p(N,V.nonceLength)}let W=V.tagLength;if(W&&Q[1]!==void 0)p(Q[1]);let Y=$(J,...Q),X=(N,R)=>{if(R!==void 0){if(N!==2)throw Error("cipher output not supported");p(R)}},K=!1;return{encrypt(N,R){if(K)throw Error("cannot encrypt() twice with same key + nonce");return K=!0,p(N),X(Y.encrypt.length,R),Y.encrypt(N,R)},decrypt(N,R){if(p(N),W&&N.length<W)throw Error("invalid ciphertext length: smaller than tagLength="+W);return X(Y.decrypt.length,R),Y.decrypt(N,R)}}}return Object.assign(Z,V),Z};function W$(V,$,Z=!0){if($===void 0)return new Uint8Array(V);if($.length!==V)throw Error("invalid output length, expected "+V+", got: "+$.length);if(Z&&!xJ($))throw Error("invalid output, must be aligned");return $}function xJ(V){return V.byteOffset%4===0}function OV(V){return Uint8Array.from(V)}function X0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function PV(V=32){if(H0&&typeof H0.getRandomValues==="function")return H0.getRandomValues(new Uint8Array(V));if(H0&&typeof H0.randomBytes==="function")return H0.randomBytes(V);throw Error("crypto.getRandomValues must be defined")}var HZ=(V)=>Uint8Array.from(V.split("").map(($)=>$.charCodeAt(0))),SJ=HZ("expand 16-byte k"),kJ=HZ("expand 32-byte k"),mJ=N0(SJ),fJ=N0(kJ);function T(V,$){return V<<$|V>>>32-$}function Y$(V){return V.byteOffset%4===0}var HV=64,BJ=16,CZ=4294967295,PZ=new Uint32Array;function gJ(V,$,Z,J,Q,W,Y,X){let K=Q.length,G=new Uint8Array(HV),N=N0(G),R=Y$(Q)&&Y$(W),z=R?N0(Q):PZ,q=R?N0(W):PZ;for(let F=0;F<K;Y++){if(V($,Z,J,N,Y,X),Y>=CZ)throw Error("arx: counter overflow");let w=Math.min(HV,K-F);if(R&&w===HV){let U=F/4;if(F%4!==0)throw Error("arx: invalid block position");for(let P=0,H;P<BJ;P++)H=U+P,q[H]=z[H]^N[P];F+=HV;continue}for(let U=0,P;U<w;U++)P=F+U,W[P]=Q[P]^G[U];F+=w}}function TZ(V,$){let{allowShortKeys:Z,extendNonceFn:J,counterLength:Q,counterRight:W,rounds:Y}=UZ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},$);if(typeof V!=="function")throw Error("core must be a function");return UV(Q),UV(Y),Q$(W),Q$(Z),(X,K,G,N,R=0)=>{p(X),p(K),p(G);let z=G.length;if(N===void 0)N=new Uint8Array(z);if(p(N),UV(R),R<0||R>=CZ)throw Error("arx: counter overflow");if(N.length<z)throw Error(`arx: output (${N.length}) is shorter than data (${z})`);let q=[],F=X.length,w,U;if(F===32)q.push(w=OV(X)),U=fJ;else if(F===16&&Z)w=new Uint8Array(32),w.set(X),w.set(X,16),U=mJ,q.push(w);else throw Error(`arx: invalid 32-byte key, got length=${F}`);if(!Y$(K))q.push(K=OV(K));let P=N0(w);if(J){if(K.length!==24)throw Error("arx: extended nonce must be 24 bytes");J(U,P,N0(K.subarray(0,16)),P),K=K.subarray(16)}let H=16-Q;if(H!==K.length)throw Error(`arx: nonce must be ${H} or 16 bytes`);if(H!==12){let O=new Uint8Array(12);O.set(K,W?0:12-K.length),K=O,q.push(K)}let A=N0(K);return gJ(V,U,P,A,G,N,R,Y),X0(...q),N}}var r=(V,$)=>V[$++]&255|(V[$++]&255)<<8;class AZ{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=qV(V),p(V,32);let $=r(V,0),Z=r(V,2),J=r(V,4),Q=r(V,6),W=r(V,8),Y=r(V,10),X=r(V,12),K=r(V,14);this.r[0]=$&8191,this.r[1]=($>>>13|Z<<3)&8191,this.r[2]=(Z>>>10|J<<6)&7939,this.r[3]=(J>>>7|Q<<9)&8191,this.r[4]=(Q>>>4|W<<12)&255,this.r[5]=W>>>1&8190,this.r[6]=(W>>>14|Y<<2)&8191,this.r[7]=(Y>>>11|X<<5)&8065,this.r[8]=(X>>>8|K<<8)&8191,this.r[9]=K>>>5&127;for(let G=0;G<8;G++)this.pad[G]=r(V,16+2*G)}process(V,$,Z=!1){let J=Z?0:2048,{h:Q,r:W}=this,Y=W[0],X=W[1],K=W[2],G=W[3],N=W[4],R=W[5],z=W[6],q=W[7],F=W[8],w=W[9],U=r(V,$+0),P=r(V,$+2),H=r(V,$+4),A=r(V,$+6),O=r(V,$+8),D=r(V,$+10),L=r(V,$+12),k=r(V,$+14),S=Q[0]+(U&8191),E=Q[1]+((U>>>13|P<<3)&8191),B=Q[2]+((P>>>10|H<<6)&8191),C=Q[3]+((H>>>7|A<<9)&8191),g=Q[4]+((A>>>4|O<<12)&8191),i=Q[5]+(O>>>1&8191),y=Q[6]+((O>>>14|D<<2)&8191),l=Q[7]+((D>>>11|L<<5)&8191),n=Q[8]+((L>>>8|k<<8)&8191),h=Q[9]+(k>>>5|J),j=0,d=j+S*Y+E*(5*w)+B*(5*F)+C*(5*q)+g*(5*z);j=d>>>13,d&=8191,d+=i*(5*R)+y*(5*N)+l*(5*G)+n*(5*K)+h*(5*X),j+=d>>>13,d&=8191;let o=j+S*X+E*Y+B*(5*w)+C*(5*F)+g*(5*q);j=o>>>13,o&=8191,o+=i*(5*z)+y*(5*R)+l*(5*N)+n*(5*G)+h*(5*K),j+=o>>>13,o&=8191;let e=j+S*K+E*X+B*Y+C*(5*w)+g*(5*F);j=e>>>13,e&=8191,e+=i*(5*q)+y*(5*z)+l*(5*R)+n*(5*N)+h*(5*G),j+=e>>>13,e&=8191;let v=j+S*G+E*K+B*X+C*Y+g*(5*w);j=v>>>13,v&=8191,v+=i*(5*F)+y*(5*q)+l*(5*z)+n*(5*R)+h*(5*N),j+=v>>>13,v&=8191;let G0=j+S*N+E*G+B*K+C*X+g*Y;j=G0>>>13,G0&=8191,G0+=i*(5*w)+y*(5*F)+l*(5*q)+n*(5*z)+h*(5*R),j+=G0>>>13,G0&=8191;let A0=j+S*R+E*N+B*G+C*K+g*X;j=A0>>>13,A0&=8191,A0+=i*Y+y*(5*w)+l*(5*F)+n*(5*q)+h*(5*z),j+=A0>>>13,A0&=8191;let D0=j+S*z+E*R+B*N+C*G+g*K;j=D0>>>13,D0&=8191,D0+=i*X+y*Y+l*(5*w)+n*(5*F)+h*(5*q),j+=D0>>>13,D0&=8191;let _0=j+S*q+E*z+B*R+C*N+g*G;j=_0>>>13,_0&=8191,_0+=i*K+y*X+l*Y+n*(5*w)+h*(5*F),j+=_0>>>13,_0&=8191;let j0=j+S*F+E*q+B*z+C*R+g*N;j=j0>>>13,j0&=8191,j0+=i*G+y*K+l*X+n*Y+h*(5*w),j+=j0>>>13,j0&=8191;let L0=j+S*w+E*F+B*q+C*z+g*R;j=L0>>>13,L0&=8191,L0+=i*N+y*G+l*K+n*X+h*Y,j+=L0>>>13,L0&=8191,j=(j<<2)+j|0,j=j+d|0,d=j&8191,j=j>>>13,o+=j,Q[0]=d,Q[1]=o,Q[2]=e,Q[3]=v,Q[4]=G0,Q[5]=A0,Q[6]=D0,Q[7]=_0,Q[8]=j0,Q[9]=L0}finalize(){let{h:V,pad:$}=this,Z=new Uint16Array(10),J=V[1]>>>13;V[1]&=8191;for(let Y=2;Y<10;Y++)V[Y]+=J,J=V[Y]>>>13,V[Y]&=8191;V[0]+=J*5,J=V[0]>>>13,V[0]&=8191,V[1]+=J,J=V[1]>>>13,V[1]&=8191,V[2]+=J,Z[0]=V[0]+5,J=Z[0]>>>13,Z[0]&=8191;for(let Y=1;Y<10;Y++)Z[Y]=V[Y]+J,J=Z[Y]>>>13,Z[Y]&=8191;Z[9]-=8192;let Q=(J^1)-1;for(let Y=0;Y<10;Y++)Z[Y]&=Q;Q=~Q;for(let Y=0;Y<10;Y++)V[Y]=V[Y]&Q|Z[Y];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 W=V[0]+$[0];V[0]=W&65535;for(let Y=1;Y<8;Y++)W=(V[Y]+$[Y]|0)+(W>>>16)|0,V[Y]=W&65535;X0(Z)}update(V){J$(this);let{buffer:$,blockLen:Z}=this;V=qV(V);let J=V.length;for(let Q=0;Q<J;){let W=Math.min(Z-this.pos,J-Q);if(W===Z){for(;Z<=J-Q;Q+=Z)this.process(V,Q);continue}if($.set(V.subarray(Q,Q+W),this.pos),this.pos+=W,Q+=W,this.pos===Z)this.process($,0,!1),this.pos=0}return this}destroy(){X0(this.h,this.r,this.buffer,this.pad)}digestInto(V){J$(this),FZ(V,this),this.finished=!0;let{buffer:$,h:Z}=this,{pos:J}=this;if(J){$[J++]=1;for(;J<16;J++)$[J]=0;this.process($,0,!0)}this.finalize();let Q=0;for(let W=0;W<8;W++)V[Q++]=Z[W]>>>0,V[Q++]=Z[W]>>>8;return V}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Z=V.slice(0,$);return this.destroy(),Z}}function vJ(V){let $=(J,Q)=>V(Q).update(qV(J)).digest(),Z=V(new Uint8Array(32));return $.outputLen=Z.outputLen,$.blockLen=Z.blockLen,$.create=(J)=>V(J),$}var X$=vJ((V)=>new AZ(V));function iJ(V,$,Z,J,Q,W=20){let Y=V[0],X=$[0],K=$[1],G=$[2],N=$[3],R=V[1],z=Z[0],q=Z[1],F=Q,w=0,U=V[2],P=$[4],H=$[5],A=$[6],O=$[7],D=V[3],L=Y,k=X,S=K,E=G,B=N,C=R,g=z,i=q,y=F,l=w,n=U,h=P,j=H,d=A,o=O,e=D;for(let G0=0;G0<W;G0+=2)B^=T(L+j|0,7),y^=T(B+L|0,9),j^=T(y+B|0,13),L^=T(j+y|0,18),l^=T(C+k|0,7),d^=T(l+C|0,9),k^=T(d+l|0,13),C^=T(k+d|0,18),o^=T(n+g|0,7),S^=T(o+n|0,9),g^=T(S+o|0,13),n^=T(g+S|0,18),E^=T(e+h|0,7),i^=T(E+e|0,9),h^=T(i+E|0,13),e^=T(h+i|0,18),k^=T(L+E|0,7),S^=T(k+L|0,9),E^=T(S+k|0,13),L^=T(E+S|0,18),g^=T(C+B|0,7),i^=T(g+C|0,9),B^=T(i+g|0,13),C^=T(B+i|0,18),h^=T(n+l|0,7),y^=T(h+n|0,9),l^=T(y+h|0,13),n^=T(l+y|0,18),j^=T(e+o|0,7),d^=T(j+e|0,9),o^=T(d+j|0,13),e^=T(o+d|0,18);let v=0;J[v++]=Y+L|0,J[v++]=X+k|0,J[v++]=K+S|0,J[v++]=G+E|0,J[v++]=N+B|0,J[v++]=R+C|0,J[v++]=z+g|0,J[v++]=q+i|0,J[v++]=F+y|0,J[v++]=w+l|0,J[v++]=U+n|0,J[v++]=P+h|0,J[v++]=H+j|0,J[v++]=A+d|0,J[v++]=O+o|0,J[v++]=D+e|0}function uJ(V,$,Z,J){let Q=V[0],W=$[0],Y=$[1],X=$[2],K=$[3],G=V[1],N=Z[0],R=Z[1],z=Z[2],q=Z[3],F=V[2],w=$[4],U=$[5],P=$[6],H=$[7],A=V[3];for(let D=0;D<20;D+=2)K^=T(Q+U|0,7),z^=T(K+Q|0,9),U^=T(z+K|0,13),Q^=T(U+z|0,18),q^=T(G+W|0,7),P^=T(q+G|0,9),W^=T(P+q|0,13),G^=T(W+P|0,18),H^=T(F+N|0,7),Y^=T(H+F|0,9),N^=T(Y+H|0,13),F^=T(N+Y|0,18),X^=T(A+w|0,7),R^=T(X+A|0,9),w^=T(R+X|0,13),A^=T(w+R|0,18),W^=T(Q+X|0,7),Y^=T(W+Q|0,9),X^=T(Y+W|0,13),Q^=T(X+Y|0,18),N^=T(G+K|0,7),R^=T(N+G|0,9),K^=T(R+N|0,13),G^=T(K+R|0,18),w^=T(F+q|0,7),z^=T(w+F|0,9),q^=T(z+w|0,13),F^=T(q+z|0,18),U^=T(A+H|0,7),P^=T(U+A|0,9),H^=T(P+U|0,13),A^=T(H+P|0,18);let O=0;J[O++]=Q,J[O++]=G,J[O++]=F,J[O++]=A,J[O++]=N,J[O++]=R,J[O++]=z,J[O++]=q}var K$=TZ(iJ,{counterRight:!0,extendNonceFn:uJ}),G$=OZ({blockSize:64,nonceLength:24,tagLength:16},(V,$)=>{return{encrypt(Z,J){J=W$(Z.length+32,J,!1);let Q=J.subarray(0,32),W=J.subarray(32);J.set(Z,32),X0(Q),K$(V,$,J,J);let Y=X$(W,Q);return J.set(Y,16),X0(J.subarray(0,16),Y),J.subarray(16)},decrypt(Z,J){p(Z),J=W$(Z.length+32,J,!1);let Q=J.subarray(0,32),W=J.subarray(32,48),Y=J.subarray(48);J.set(Z,32),X0(Q);let X=K$(V,$,Q,Q),K=X$(Y,X);if(!qZ(W,K))throw Error("invalid tag");return K$(V,$,J.subarray(16),J.subarray(16)),X0(Q,W,K),Y}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function bJ(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function o0(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function C0(V,...$){if(!bJ(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function a0(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function CV(V,$){C0(V);let Z=$.outputLen;if(V.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function DZ(V){return new Uint8Array(V.buffer,V.byteOffset,V.byteLength)}function g0(V){return new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4))}function v0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function s0(V,$){return V<<32-$|V>>>$}var _Z=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function jZ(V){return V<<24&4278190080|V<<8&16711680|V>>>8&65280|V>>>24&255}var LZ=_Z?(V)=>V:(V)=>jZ(V);function yJ(V){for(let $=0;$<V.length;$++)V[$]=jZ(V[$]);return V}var s=_Z?(V)=>V:yJ;function lJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function i0(V){if(typeof V==="string")V=lJ(V);return C0(V),V}class N${}function EZ(V){let $=(J,Q)=>V(Q).update(i0(J)).digest(),Z=V({});return $.outputLen=Z.outputLen,$.blockLen=Z.blockLen,$.create=(J)=>V(J),$}var xZ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var TV=BigInt(4294967295),SZ=BigInt(32);function I$(V,$=!1){if($)return{h:Number(V&TV),l:Number(V>>SZ&TV)};return{h:Number(V>>SZ&TV)|0,l:Number(V&TV)|0}}function I0(V,$,Z,J,Q){return V=V+$+Q|0,J=s0(J^V,16),Z=Z+J|0,$=s0($^Z,12),{a:V,b:$,c:Z,d:J}}function R0(V,$,Z,J,Q){return V=V+$+Q|0,J=s0(J^V,8),Z=Z+J|0,$=s0($^Z,7),{a:V,b:$,c:Z,d:J}}class R$ extends N${constructor(V,$){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,o0(V),o0($),this.blockLen=V,this.outputLen=$,this.buffer=new Uint8Array(V),this.buffer32=g0(this.buffer)}update(V){a0(this),V=i0(V),C0(V);let{blockLen:$,buffer:Z,buffer32:J}=this,Q=V.length,W=V.byteOffset,Y=V.buffer;for(let X=0;X<Q;){if(this.pos===$)s(J),this.compress(J,0,!1),s(J),this.pos=0;let K=Math.min($-this.pos,Q-X),G=W+X;if(K===$&&!(G%4)&&X+K<Q){let N=new Uint32Array(Y,G,Math.floor((Q-X)/4));s(N);for(let R=0;X+$<Q;R+=J.length,X+=$)this.length+=$,this.compress(N,R,!1);s(N);continue}Z.set(V.subarray(X,X+K),this.pos),this.pos+=K,this.length+=K,X+=K}return this}digestInto(V){a0(this),CV(V,this);let{pos:$,buffer32:Z}=this;this.finished=!0,v0(this.buffer.subarray($)),s(Z),this.compress(Z,0,!0),s(Z);let J=g0(V);this.get().forEach((Q,W)=>J[W]=LZ(Q))}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Z=V.slice(0,$);return this.destroy(),Z}_cloneInto(V){let{buffer:$,length:Z,finished:J,destroyed:Q,outputLen:W,pos:Y}=this;return V||(V=new this.constructor({dkLen:W})),V.set(...this.get()),V.buffer.set($),V.destroyed=Q,V.finished=J,V.length=Z,V.pos=Y,V.outputLen=W,V}clone(){return this._cloneInto()}}function z$(V,$,Z,J,Q,W,Y,X,K,G,N,R,z,q,F,w,U,P,H,A){let O=0;for(let D=0;D<J;D++)({a:Q,b:K,c:z,d:U}=I0(Q,K,z,U,Z[$+V[O++]])),{a:Q,b:K,c:z,d:U}=R0(Q,K,z,U,Z[$+V[O++]]),{a:W,b:G,c:q,d:P}=I0(W,G,q,P,Z[$+V[O++]]),{a:W,b:G,c:q,d:P}=R0(W,G,q,P,Z[$+V[O++]]),{a:Y,b:N,c:F,d:H}=I0(Y,N,F,H,Z[$+V[O++]]),{a:Y,b:N,c:F,d:H}=R0(Y,N,F,H,Z[$+V[O++]]),{a:X,b:R,c:w,d:A}=I0(X,R,w,A,Z[$+V[O++]]),{a:X,b:R,c:w,d:A}=R0(X,R,w,A,Z[$+V[O++]]),{a:Q,b:G,c:F,d:A}=I0(Q,G,F,A,Z[$+V[O++]]),{a:Q,b:G,c:F,d:A}=R0(Q,G,F,A,Z[$+V[O++]]),{a:W,b:N,c:w,d:U}=I0(W,N,w,U,Z[$+V[O++]]),{a:W,b:N,c:w,d:U}=R0(W,N,w,U,Z[$+V[O++]]),{a:Y,b:R,c:z,d:P}=I0(Y,R,z,P,Z[$+V[O++]]),{a:Y,b:R,c:z,d:P}=R0(Y,R,z,P,Z[$+V[O++]]),{a:X,b:K,c:q,d:H}=I0(X,K,q,H,Z[$+V[O++]]),{a:X,b:K,c:q,d:H}=R0(X,K,q,H,Z[$+V[O++]]);return{v0:Q,v1:W,v2:Y,v3:X,v4:K,v5:G,v6:N,v7:R,v8:z,v9:q,v10:F,v11:w,v12:U,v13:P,v14:H,v15:A}}var K0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},z0=xZ.slice(),kZ=(()=>{let V=Array.from({length:16},(J,Q)=>Q),$=(J)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((Q)=>J[Q]),Z=[];for(let J=0,Q=V;J<7;J++,Q=$(Q))Z.push(...Q);return Uint8Array.from(Z)})();class w$ extends R${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:Z,context:J}=V,Q=J!==void 0;if(Z!==void 0){if(Q)throw Error('Only "key" or "context" can be specified at same time');let W=i0(Z).slice();C0(W,32),this.IV=g0(W),s(this.IV),this.flags=$|K0.KEYED_HASH}else if(Q){let W=i0(J),Y=new w$({dkLen:32},K0.DERIVE_KEY_CONTEXT).update(W).digest();this.IV=g0(Y),s(this.IV),this.flags=$|K0.DERIVE_KEY_MATERIAL}else this.IV=z0.slice(),this.flags=$;this.state=this.IV.slice(),this.bufferOut=DZ(this.bufferOut32)}get(){return[]}set(){}b2Compress(V,$,Z,J=0){let{state:Q,pos:W}=this,{h:Y,l:X}=I$(BigInt(V),!0),{v0:K,v1:G,v2:N,v3:R,v4:z,v5:q,v6:F,v7:w,v8:U,v9:P,v10:H,v11:A,v12:O,v13:D,v14:L,v15:k}=z$(kZ,J,Z,7,Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7],z0[0],z0[1],z0[2],z0[3],Y,X,W,$);Q[0]=K^U,Q[1]=G^P,Q[2]=N^H,Q[3]=R^A,Q[4]=z^O,Q[5]=q^D,Q[6]=F^L,Q[7]=w^k}compress(V,$=0,Z=!1){let J=this.flags;if(!this.chunkPos)J|=K0.CHUNK_START;if(this.chunkPos===15||Z)J|=K0.CHUNK_END;if(!Z)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,J,V,$),this.chunkPos+=1,this.chunkPos===16||Z){let Q=this.state;this.state=this.IV.slice();for(let W,Y=this.chunksDone+1;Z||!(Y&1);Y>>=1){if(!(W=this.stack.pop()))break;this.buffer32.set(W,0),this.buffer32.set(Q,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|K0.PARENT,this.buffer32,0),Q=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(Q)}this.pos=0}_cloneInto(V){V=super._cloneInto(V);let{IV:$,flags:Z,state:J,chunkPos:Q,posOut:W,chunkOut:Y,stack:X,chunksDone:K}=this;return V.state.set(J.slice()),V.stack=X.map((G)=>Uint32Array.from(G)),V.IV.set($),V.flags=Z,V.chunkPos=Q,V.chunksDone=K,V.posOut=W,V.chunkOut=Y,V.enableXOF=this.enableXOF,V.bufferOut32.set(this.bufferOut32),V}destroy(){this.destroyed=!0,v0(this.state,this.buffer32,this.IV,this.bufferOut32),v0(...this.stack)}b2CompressOut(){let{state:V,pos:$,flags:Z,buffer32:J,bufferOut32:Q}=this,{h:W,l:Y}=I$(BigInt(this.chunkOut++));s(J);let{v0:X,v1:K,v2:G,v3:N,v4:R,v5:z,v6:q,v7:F,v8:w,v9:U,v10:P,v11:H,v12:A,v13:O,v14:D,v15:L}=z$(kZ,0,J,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],z0[0],z0[1],z0[2],z0[3],Y,W,$,Z);Q[0]=X^w,Q[1]=K^U,Q[2]=G^P,Q[3]=N^H,Q[4]=R^A,Q[5]=z^O,Q[6]=q^D,Q[7]=F^L,Q[8]=V[0]^w,Q[9]=V[1]^U,Q[10]=V[2]^P,Q[11]=V[3]^H,Q[12]=V[4]^A,Q[13]=V[5]^O,Q[14]=V[6]^D,Q[15]=V[7]^L,s(J),s(Q),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,v0(this.buffer.subarray(this.pos));let V=this.flags|K0.ROOT;if(this.stack.length)V|=K0.PARENT,s(this.buffer32),this.compress(this.buffer32,0,!0),s(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else V|=(!this.chunkPos?K0.CHUNK_START:0)|K0.CHUNK_END;this.flags=V,this.b2CompressOut()}writeInto(V){a0(this,!1),C0(V),this.finish();let{blockLen:$,bufferOut:Z}=this;for(let J=0,Q=V.length;J<Q;){if(this.posOut>=$)this.b2CompressOut();let W=Math.min($-this.posOut,Q-J);V.set(Z.subarray(this.posOut,this.posOut+W),J),this.posOut+=W,J+=W}return V}xofInto(V){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(V)}xof(V){return o0(V),this.xofInto(new Uint8Array(V))}digestInto(V){if(CV(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 mZ=EZ((V)=>new w$(V));var M$=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function fZ(V){let $=new Uint8Array(M$.length+32);return $.set(M$),$.set(V.subarray(0,32),M$.length),$}function BZ(V){return typeof V==="string"?new TextEncoder().encode(V):V}function u0(V){let $=new ArrayBuffer(V.byteLength);return new Uint8Array($).set(V),$}class F${verifyKeys=new Map;signKeys=new Map;async genRandomBytes(V){return PV(V)}async gen256BitSecureRandomSeed(){return PV(32)}async encryptXSalsa20Poly1305Combined(V,$){let Z=PV(24),Q=G$($,Z).encrypt(V);return new Uint8Array([...Z,...Q])}async decryptXSalsa20Poly1305Combined(V,$){let Z=V.slice(0,24),J=V.slice(24);return G$($,Z).decrypt(J)}async deriveEd25519KeyPair(V){let $=V,Z=fZ($),J=await globalThis.crypto.subtle.importKey("pkcs8",u0(Z),{name:"Ed25519"},!0,["sign"]),Q=await globalThis.crypto.subtle.exportKey("jwk",J);if(typeof Q.x!=="string")throw Error("Ed25519 JWK missing x");let W=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:Q.x},{name:"Ed25519"},!0,["verify"]),Y=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",W)),X=new Uint8Array(64);return X.set($,0),X.set(Y,32),this.signKeys.set(Y0($),J),this.verifyKeys.set(Y0(Y),W),{keyType:"ed25519",privateKey:X,publicKey:Y}}async importSignKey(V){let $=V.subarray(0,32),Z=Y0($),J=this.signKeys.get(Z);if(J)return J;let Q=fZ($),W=await globalThis.crypto.subtle.importKey("pkcs8",u0(Q),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Z,W),W}async importVerifyKey(V){let $=Y0(V),Z=this.verifyKeys.get($);if(Z)return Z;let J=await globalThis.crypto.subtle.importKey("raw",u0(V),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set($,J),J}async signEd25519(V,$){let Z=BZ(V),J=await this.importSignKey($),Q=await globalThis.crypto.subtle.sign({name:"Ed25519"},J,u0(Z));return new Uint8Array(Q)}async checkSigEd25519(V,$,Z){let J=BZ($);try{let Q=await this.importVerifyKey(Z);return await globalThis.crypto.subtle.verify({name:"Ed25519"},Q,u0(V),u0(J))}catch{return!1}}async blake3(V){return mZ(V)}}var nJ=new F$,b0=nJ;class U${db;constructor(V){this.db=V}async enq(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(J0,"readwrite"),J=Z.objectStore(J0);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=`${Y.host}:${Y.seq}`;J.put(Y,X)}})}async deq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(J0,"readwrite"),Q=J.objectStore(J0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let K=`${V}:${X}`;Q.delete(K)}})}async list(){let $=this.db.transaction(J0,"readonly").objectStore(J0);return new Promise((Z,J)=>{let Q=$.getAll();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async count(){let $=this.db.transaction(J0,"readonly").objectStore(J0);return new Promise((Z,J)=>{let Q=$.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(J0,"readwrite"),$=V.objectStore(J0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}function gZ(V){return{label:V.label,handle:new URL(V.handle),idx:V.idx,lastSeq:V.lastSeq||0,clockOffset:V.clockOffset,subscription:V.subscription}}class q${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},Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error),J.put($)})}async touch(V,$){let Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);let Y=J.get(V);Y.onsuccess=()=>{let X=Y.result;if(!X)return;let K=X.lastSeq||0;if($<=K)return;J.put({...X,lastSeq:$})}})}async get(V){let Z=this.db.transaction(t,"readonly").objectStore(t);return new Promise((J,Q)=>{let W=Z.get(V);W.onsuccess=()=>{let Y=W.result;if(!Y)J(void 0);else J(gZ(Y))},W.onerror=()=>Q(W.error)})}async set(V,$){let Z=await this.get(V);if(!Z)return 13;try{return await this.put({...Z,...$}),0}catch{return 18}}async del(V){let $=this.db.transaction(t,"readwrite"),Z=$.objectStore(t);return new Promise((J,Q)=>{$.oncomplete=()=>J(),$.onerror=()=>Q($.error),Z.delete(V)})}async list(){let $=this.db.transaction(t,"readonly").objectStore(t);return new Promise((Z,J)=>{let Q=$.getAll();Q.onsuccess=()=>{let W=Q.result;Z(W.map(gZ))},Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(t,"readwrite"),$=V.objectStore(t);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}class O${crypto;db;constructor(V,$){this.crypto=$;this.db=V}async add(V){let $=this.db.transaction(u,"readwrite"),Z=$.objectStore(u);return new Promise((J)=>{if(V.length===0){J([]);return}let Q=Array(V.length).fill(0);$.oncomplete=()=>J(Q),$.onerror=()=>{for(let W=0;W<Q.length;W++)Q[W]=18;J(Q)};for(let W=0;W<V.length;W++){let{key:Y,data:X}=V[W],K=x(Y),G=Z.put(X,K);G.onerror=(N)=>{N.preventDefault(),Q[W]=18}}})}async del(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(u,"readwrite"),J=Z.objectStore(u);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=x(Y);J.delete(X)}})}async get(V){let Z=this.db.transaction(u,"readonly").objectStore(u);return new Promise((J,Q)=>{let W=x(V),Y=Z.get(W);Y.onsuccess=async()=>{let X=Y.result;if(X)J(await FV(V,X,this.crypto));else J(void 0)},Y.onerror=()=>Q(Y.error)})}async has(V){return await this.get(V)!==void 0}async list(V){let Z=this.db.transaction(u,"readonly").objectStore(u);return new Promise((J,Q)=>{let W=[],Y=V===void 0?Z.openCursor():Z.index(AV).openCursor(IDBKeyRange.only(V));Y.onsuccess=(X)=>{let K=X.target.result;if(K){let G=V===void 0?K.key:K.primaryKey,N=K.value;W.push({hash:q0(G),data:N}),K.continue()}else Promise.all(W.map(({hash:G,data:N})=>FV(G,N,this.crypto))).then(J).catch(Q)},Y.onerror=()=>Q(Y.error)})}async last(V){let Z=this.db.transaction(u,"readonly").objectStore(u);return new Promise((J,Q)=>{let W,Y=Z.openCursor();Y.onsuccess=async(X)=>{let K=X.target.result;if(K){let{key:G,value:N}=K;if($0(V,N.eid)){if(!W||(N.ctr??0)>(W.data.ctr??0)||(N.ctr??0)===(W.data.ctr??0)&&(N.off??0)>(W.data.off??0))W={key:G,data:N}}K.continue()}else if(W){let G=q0(W.key);J(await FV(G,W.data,this.crypto))}else J(void 0)},Y.onerror=()=>Q(Y.error)})}async markApplied(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(u,"readwrite"),J=Z.objectStore(u);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=x(Y),K=J.get(X);K.onsuccess=()=>{let G=K.result;if(!G)return;tV(G,MV),J.put(G,X)},K.onerror=(G)=>{G.preventDefault()}}})}async markFailed(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(u,"readwrite"),J=Z.objectStore(u);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let{key:Y,err:X}of $){let K=x(Y),G=J.get(K);G.onsuccess=()=>{let N=G.result;if(!N)return;tV(N,f0,X),J.put(N,K)},G.onerror=(N)=>{N.preventDefault()}}})}async wipe(){let V=this.db.transaction(u,"readwrite"),$=V.objectStore(u);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}class DV{seed;crypto;constructor(V,$){this.seed=V,this.crypto=$}async deriveFromKDM(V){let $=c0(this.seed,V);return await this.crypto.blake3($)}async derive(V,$=0){let Z=new TextEncoder().encode(V),J=new Uint8Array(8);new DataView(J.buffer).setBigUint64(0,BigInt($),!1);let Q=c0(Z,J);return await this.deriveFromKDM(Q)}}class P${enclave;db;constructor(V){this.db=V}async save(V){let $=Y0(V),Z=this.db.transaction(w0,"readwrite"),J=Z.objectStore(w0);return new Promise((Q,W)=>{Z.oncomplete=()=>{this.enclave=new DV(V,b0),Q(this.enclave)},Z.onerror=()=>W(Z.error),J.put($,"seed")})}async load(){if(this.enclave)return this.enclave;let $=this.db.transaction(w0,"readonly").objectStore(w0);return new Promise((Z,J)=>{let Q=$.get("seed");Q.onsuccess=()=>{let W=Q.result;if(!W)Z(void 0);else{let Y=WV(W);this.enclave=new DV(Y,b0),Z(this.enclave)}},Q.onerror=()=>J(Q.error)})}async wipe(){this.enclave=void 0;let V=this.db.transaction(w0,"readwrite"),$=V.objectStore(w0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.delete("seed")})}}class H${db;constructor(V){this.db=V}async enq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(Q0,"readwrite"),Q=J.objectStore(Q0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let K=Y0(X);Q.put({host:V,hash:K})}})}async deq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(Q0,"readwrite"),Q=J.objectStore(Q0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let K=Y0(X);Q.delete([V,K])}})}async list(V){let Z=this.db.transaction(Q0,"readonly").objectStore(Q0);return new Promise((J,Q)=>{let W=Z.getAll();W.onsuccess=()=>{let X=W.result.filter((K)=>K.host===V).map((K)=>K.hash);J(X.map((K)=>WV(K)))},W.onerror=()=>Q(W.error)})}async count(){let $=this.db.transaction(Q0,"readonly").objectStore(Q0);return new Promise((Z,J)=>{let Q=$.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(Q0,"readwrite"),$=V.objectStore(Q0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}var w0="seedMeta",t="hosts",Q0="uploadQueue",J0="downloadQueue",u="messages",AV="apld",hJ=3;class vZ{seed;hosts;uploads;downloads;messages;db;constructor(V,$){this.db=V,this.seed=new P$(V),this.hosts=new q$(V),this.uploads=new H$(V),this.downloads=new U$(V),this.messages=new O$(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 pJ(){return new Promise((V,$)=>{let Z=indexedDB.open("diplomatic-store-db",hJ);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!J.objectStoreNames.contains(w0))J.createObjectStore(w0);if(!J.objectStoreNames.contains(t))J.createObjectStore(t,{keyPath:"label"});if(!J.objectStoreNames.contains(Q0))J.createObjectStore(Q0,{keyPath:["host","hash"]});if(!J.objectStoreNames.contains(J0))J.createObjectStore(J0);let W;if(!J.objectStoreNames.contains(u))W=J.createObjectStore(u);else{if(!Q)throw Error("missing upgrade transaction for messages store");W=Q.objectStore(u)}if(!W.indexNames.contains(AV))W.createIndex(AV,"apld",{unique:!1})},Z.onsuccess=()=>V(Z.result),Z.onerror=()=>$(Z.error)})}async function iZ(V){let $=await pJ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new vZ($,V)}class C${client;post;whenReady;resolveReady;rejectReady;constructor(V){this.post=V,this.whenReady=new Promise(($,Z)=>{this.resolveReady=$,this.rejectReady=Z})}async init(){try{let V=await iZ(b0),$=await e$({cache:!1}),Z=new IV($.apply,()=>$.clear(),(W)=>{if(W.length<1)return;this.post({kind:"dirty",eids:W.map((Y)=>Y.slice())})}),J=Z.clear;Z.clear=async()=>{let W=await J();if(W===0)this.post({kind:"wiped"});return W};let Q=new $$(new fV,Z,V,c$,b0);this.client=Q,Q.clientState.listen(()=>{this.emitClientState()}),Q.xferState.listen(()=>{this.emitXferState()}),await this.emitClientState(),await this.emitXferState(),this.post({kind:"ready"}),this.markReady()}catch(V){let $=V instanceof Error?V:Error(String(V));throw this.failReady($),$}}markReady(){let V=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V()}failReady(V){let $=this.rejectReady;if(this.resolveReady=void 0,this.rejectReady=void 0,$)$(V)}requireClient(){if(!this.client)throw Error("WorkerRuntime not initialized");return this.client}async emitClientState(){let V=this.client;if(!V)return;let $=await V.clientState.get();this.post({kind:"clientState",state:$})}async emitXferState(){let V=this.client;if(!V)return;let $=await V.xferState.get();this.post({kind:"xferState",state:$})}hostFromSerialized(V){return{handle:new URL(V.handle),label:V.label,idx:V.idx}}async handle(V){await this.whenReady;let $=this.requireClient();switch(V.op){case"ping":return"pong";case"setSeed":{await $.setSeed(cJ(V.seed));return}case"link":{await $.link(this.hostFromSerialized(V.host),V.connect??!0);return}case"unlink":{await $.unlink(V.label);return}case"connect":{await $.connect(V.listen??!0,V.sync??!0);return}case"disconnect":{await $.disconnect();return}case"sync":return await $.sync();case"wipe":{await $.wipe();return}case"import":{let Z=V.bytes.slice(),J=new Blob([Z]),Q=new File([J],"import.dip");return await $.import(Q)}case"export":{let[Z,J]=await $.exportBytes();if(J!==0)throw new y0(J);if(!Z)throw new y0(12);return Z}case"getClientState":return await $.clientState.get();case"getXferState":return await $.xferState.get();default:{let Z=V;throw Error("unknown worker command")}}}}class y0 extends Error{status;constructor(V){super(`WorkerStatusError: ${_[V]}`);this.status=V;this.name="WorkerStatusError"}}function T$(V,$){return{kind:"reply",id:V,ok:!0,result:$}}function A$(V,$){return{kind:"reply",id:V,ok:!1,status:$}}function cJ(V){if(V.length!==32)throw new y0(10);return V}var T0=globalThis,uZ=new C$((V,$)=>{if($&&$.length>0)T0.postMessage(V,$);else T0.postMessage(V)});T0.onmessage=(V)=>{let $=V.data;if(!L$($))return;rJ($)};async function rJ(V){try{let $=await uZ.handle(V);if(V.op==="export"&&$ instanceof Uint8Array){let Z=$.slice();T0.postMessage(T$(V.id,Z),[Z.buffer]);return}T0.postMessage(T$(V.id,$))}catch($){if($ instanceof y0){T0.postMessage(A$(V.id,$.status));return}console.error("worker command failed",$),T0.postMessage(A$(V.id,12))}}uZ.init().catch((V)=>{console.error("worker init failed",V)});
1
+ var M0=64;var D$=32,F0=8;var t0=32;var _$=30000,j$=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 L$(V){if(!V||typeof V!=="object")return!1;if(!("op"in V)||!("id"in V))return!1;return typeof V.op==="string"&&typeof V.id==="number"}function E$(V){let $=V.length,Z=0,J=0;while(J<$){let Q=V.charCodeAt(J++);if((Q&4294967168)===0){Z++;continue}else if((Q&4294965248)===0)Z+=2;else{if(Q>=55296&&Q<=56319){if(J<$){let W=V.charCodeAt(J);if((W&64512)===56320)++J,Q=((Q&1023)<<10)+(W&1023)+65536}}if((Q&4294901760)===0)Z+=3;else Z+=4}}return Z}function uZ(V,$,Z){let J=V.length,Q=Z,W=0;while(W<J){let Y=V.charCodeAt(W++);if((Y&4294967168)===0){$[Q++]=Y;continue}else if((Y&4294965248)===0)$[Q++]=Y>>6&31|192;else{if(Y>=55296&&Y<=56319){if(W<J){let X=V.charCodeAt(W);if((X&64512)===56320)++W,Y=((Y&1023)<<10)+(X&1023)+65536}}if((Y&4294901760)===0)$[Q++]=Y>>12&15|224,$[Q++]=Y>>6&63|128;else $[Q++]=Y>>18&7|240,$[Q++]=Y>>12&63|128,$[Q++]=Y>>6&63|128}$[Q++]=Y&63|128}}var yZ=new TextEncoder,lZ=50;function nZ(V,$,Z){yZ.encodeInto(V,$.subarray(Z))}function x$(V,$,Z){if(V.length>lZ)nZ(V,$,Z);else uZ(V,$,Z)}var hZ=4096;function _V(V,$,Z){let J=$,Q=J+Z,W=[],Y="";while(J<Q){let X=V[J++];if((X&128)===0)W.push(X);else if((X&224)===192){let K=V[J++]&63;W.push((X&31)<<6|K)}else if((X&240)===224){let K=V[J++]&63,G=V[J++]&63;W.push((X&31)<<12|K<<6|G)}else if((X&248)===240){let K=V[J++]&63,G=V[J++]&63,N=V[J++]&63,R=(X&7)<<18|K<<12|G<<6|N;if(R>65535)R-=65536,W.push(R>>>10&1023|55296),R=56320|R&1023;W.push(R)}else W.push(X);if(W.length>=hZ)Y+=String.fromCharCode(...W),W.length=0}if(W.length>0)Y+=String.fromCharCode(...W);return Y}var pZ=new TextDecoder,cZ=200;function rZ(V,$,Z){let J=V.subarray($,$+Z);return pZ.decode(J)}function S$(V,$,Z){if(Z>cZ)return rZ(V,$,Z);else return _V(V,$,Z)}class E0{type;data;constructor(V,$){this.type=V,this.data=$}}class a extends Error{constructor(V){super(V);let $=Object.create(a.prototype);Object.setPrototypeOf(this,$),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:a.name})}}var x0=4294967295;function k$(V,$,Z){let J=Z/4294967296,Q=Z;V.setUint32($,J),V.setUint32($+4,Q)}function e0(V,$,Z){let J=Math.floor(Z/4294967296),Q=Z;V.setUint32($,J),V.setUint32($+4,Q)}function VV(V,$){let Z=V.getInt32($),J=V.getUint32($+4);return Z*4294967296+J}function m$(V,$){let Z=V.getUint32($),J=V.getUint32($+4);return Z*4294967296+J}var dZ=-1,oZ=4294967295,aZ=17179869183;function sZ({sec:V,nsec:$}){if(V>=0&&$>=0&&V<=aZ)if($===0&&V<=oZ){let Z=new Uint8Array(4);return new DataView(Z.buffer).setUint32(0,V),Z}else{let Z=V/4294967296,J=V&4294967295,Q=new Uint8Array(8),W=new DataView(Q.buffer);return W.setUint32(0,$<<2|Z&3),W.setUint32(4,J),Q}else{let Z=new Uint8Array(12),J=new DataView(Z.buffer);return J.setUint32(0,$),e0(J,4,V),Z}}function tZ(V){let $=V.getTime(),Z=Math.floor($/1000),J=($-Z*1000)*1e6,Q=Math.floor(J/1e9);return{sec:Z+Q,nsec:J-Q*1e9}}function eZ(V){if(V instanceof Date){let $=tZ(V);return sZ($)}else return null}function VJ(V){let $=new DataView(V.buffer,V.byteOffset,V.byteLength);switch(V.byteLength){case 4:{let Z=$.getUint32(0),J=0;return{sec:Z,nsec:0}}case 8:{let Z=$.getUint32(0),J=$.getUint32(4),Q=(Z&3)*4294967296+J,W=Z>>>2;return{sec:Q,nsec:W}}case 12:{let Z=VV($,4),J=$.getUint32(0);return{sec:Z,nsec:J}}default:throw new a(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${V.length}`)}}function $J(V){let $=VJ(V);return new Date($.sec*1000+$.nsec/1e6)}var f$={type:dZ,encode:eZ,decode:$J};class S0{static defaultCodec=new S0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(f$)}register({type:V,encode:$,decode:Z}){if(V>=0)this.encoders[V]=$,this.decoders[V]=Z;else{let J=-1-V;this.builtInEncoders[J]=$,this.builtInDecoders[J]=Z}}tryToEncode(V,$){for(let Z=0;Z<this.builtInEncoders.length;Z++){let J=this.builtInEncoders[Z];if(J!=null){let Q=J(V,$);if(Q!=null){let W=-1-Z;return new E0(W,Q)}}}for(let Z=0;Z<this.encoders.length;Z++){let J=this.encoders[Z];if(J!=null){let Q=J(V,$);if(Q!=null)return new E0(Z,Q)}}if(V instanceof E0)return V;return null}decode(V,$,Z){let J=$<0?this.builtInDecoders[-1-$]:this.decoders[$];if(J)return J(V,$,Z);else return new E0($,V)}}function ZJ(V){return V instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&V instanceof SharedArrayBuffer}function l0(V){if(V instanceof Uint8Array)return V;else if(ArrayBuffer.isView(V))return new Uint8Array(V.buffer,V.byteOffset,V.byteLength);else if(ZJ(V))return new Uint8Array(V);else return Uint8Array.from(V)}var JJ=100,QJ=2048;class $V{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??S0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.maxDepth=V?.maxDepth??JJ,this.initialBufferSize=V?.initialBufferSize??QJ,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 $V({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),Z=new Uint8Array($),J=new DataView($);Z.set(this.bytes),this.view=J,this.bytes=Z}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 Z=E$(V);this.ensureBufferSizeToWrite(5+Z),this.writeStringHeader(Z),x$(V,this.bytes,this.pos),this.pos+=Z}encodeObject(V,$){let Z=this.extensionCodec.tryToEncode(V,this.context);if(Z!=null)this.encodeExtension(Z);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 Z=l0(V);this.writeU8a(Z)}encodeArray(V,$){let Z=V.length;if(Z<16)this.writeU8(144+Z);else if(Z<65536)this.writeU8(220),this.writeU16(Z);else if(Z<4294967296)this.writeU8(221),this.writeU32(Z);else throw Error(`Too large array: ${Z}`);for(let J of V)this.doEncode(J,$+1)}countWithoutUndefined(V,$){let Z=0;for(let J of $)if(V[J]!==void 0)Z++;return Z}encodeMap(V,$){let Z=Object.keys(V);if(this.sortKeys)Z.sort();let J=this.ignoreUndefined?this.countWithoutUndefined(V,Z):Z.length;if(J<16)this.writeU8(128+J);else if(J<65536)this.writeU8(222),this.writeU16(J);else if(J<4294967296)this.writeU8(223),this.writeU32(J);else throw Error(`Too large map object: ${J}`);for(let Q of Z){let W=V[Q];if(!(this.ignoreUndefined&&W===void 0))this.encodeString(Q),this.doEncode(W,$+1)}}encodeExtension(V){if(typeof V.data==="function"){let Z=V.data(this.pos+6),J=Z.length;if(J>=4294967296)throw Error(`Too large extension object: ${J}`);this.writeU8(201),this.writeU32(J),this.writeI8(V.type),this.writeU8a(Z);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),k$(this.view,this.pos,V),this.pos+=8}writeI64(V){this.ensureBufferSizeToWrite(8),e0(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 O0(V,$){return new $V($).encodeSharedRef(V)}function ZV(V){return`${V<0?"-":""}0x${Math.abs(V).toString(16).padStart(2,"0")}`}var WJ=16,YJ=16;class jV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(V=WJ,$=YJ){this.maxKeyLength=V,this.maxLengthPerKey=$,this.caches=[];for(let Z=0;Z<this.maxKeyLength;Z++)this.caches.push([])}canBeCached(V){return V>0&&V<=this.maxKeyLength}find(V,$,Z){let J=this.caches[Z-1];V:for(let Q of J){let W=Q.bytes;for(let Y=0;Y<Z;Y++)if(W[Y]!==V[$+Y])continue V;return Q.str}return null}store(V,$){let Z=this.caches[V.length-1],J={bytes:V,str:$};if(Z.length>=this.maxLengthPerKey)Z[Math.random()*Z.length|0]=J;else Z.push(J)}decode(V,$,Z){let J=this.find(V,$,Z);if(J!=null)return this.hit++,J;this.miss++;let Q=_V(V,$,Z),W=Uint8Array.prototype.slice.call(V,$,$+Z);return this.store(W,Q),Q}}var LV="array",h0="map_key",g$="map_value",XJ=(V)=>{if(typeof V==="string"||typeof V==="number")return V;throw new a("The type of key must be string or number but "+typeof V)};class v${stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(V){let $=this.getUninitializedStateFromPool();$.type=LV,$.position=0,$.size=V,$.array=Array(V)}pushMapState(V){let $=this.getUninitializedStateFromPool();$.type=h0,$.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===LV){let Z=V;Z.size=0,Z.array=void 0,Z.position=0,Z.type=void 0}if(V.type===h0||V.type===g$){let Z=V;Z.size=0,Z.map=void 0,Z.readCount=0,Z.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var n0=-1,EV=new DataView(new ArrayBuffer(0)),KJ=new Uint8Array(EV.buffer);try{EV.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 B$=RangeError("Insufficient data"),GJ=new jV;class JV{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=EV;bytes=KJ;headByte=n0;stack=new v$;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??S0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.rawStrings=V?.rawStrings??!1,this.maxStrLength=V?.maxStrLength??x0,this.maxBinLength=V?.maxBinLength??x0,this.maxArrayLength=V?.maxArrayLength??x0,this.maxMapLength=V?.maxMapLength??x0,this.maxExtLength=V?.maxExtLength??x0,this.keyDecoder=V?.keyDecoder!==void 0?V.keyDecoder:GJ,this.mapKeyConverter=V?.mapKeyConverter??XJ}clone(){return new JV({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=n0,this.stack.reset()}setBuffer(V){let $=l0(V);this.bytes=$,this.view=new DataView($.buffer,$.byteOffset,$.byteLength),this.pos=0}appendBuffer(V){if(this.headByte===n0&&!this.hasRemaining(1))this.setBuffer(V);else{let $=this.bytes.subarray(this.pos),Z=l0(V),J=new Uint8Array($.length+Z.length);J.set($),J.set(Z,$.length),this.setBuffer(J)}}hasRemaining(V){return this.view.byteLength-this.pos>=V}createExtraByteError(V){let{view:$,pos:Z}=this;return RangeError(`Extra ${$.byteLength-Z} 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,Z;for await(let Y of V){if($)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(Y);try{Z=this.doDecodeSync(),$=!0}catch(X){if(!(X instanceof RangeError))throw X}this.totalPos+=this.pos}if($){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Z}let{headByte:J,pos:Q,totalPos:W}=this;throw RangeError(`Insufficient data in parsing ${ZV(J)} at ${W} (${Q} 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 Z=$,J=-1;for await(let Q of V){if($&&J===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(Q),Z)J=this.readArraySize(),Z=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--J===0)break}catch(W){if(!(W instanceof RangeError))throw W}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 J=V-128;if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V<160){let J=V-144;if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else{let J=V-160;$=this.decodeString(J,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 J=this.lookU8();$=this.decodeString(J,1)}else if(V===218){let J=this.lookU16();$=this.decodeString(J,2)}else if(V===219){let J=this.lookU32();$=this.decodeString(J,4)}else if(V===220){let J=this.readU16();if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else if(V===221){let J=this.readU32();if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else if(V===222){let J=this.readU16();if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V===223){let J=this.readU32();if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V===196){let J=this.lookU8();$=this.decodeBinary(J,1)}else if(V===197){let J=this.lookU16();$=this.decodeBinary(J,2)}else if(V===198){let J=this.lookU32();$=this.decodeBinary(J,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 J=this.lookU8();$=this.decodeExtension(J,1)}else if(V===200){let J=this.lookU16();$=this.decodeExtension(J,2)}else if(V===201){let J=this.lookU32();$=this.decodeExtension(J,4)}else throw new a(`Unrecognized type byte: ${ZV(V)}`);this.complete();let Z=this.stack;while(Z.length>0){let J=Z.top();if(J.type===LV)if(J.array[J.position]=$,J.position++,J.position===J.size)$=J.array,Z.release(J);else continue V;else if(J.type===h0){if($==="__proto__")throw new a("The key __proto__ is not allowed");J.key=this.mapKeyConverter($),J.type=g$;continue V}else if(J.map[J.key]=$,J.readCount++,J.readCount===J.size)$=J.map,Z.release(J);else{J.key=null,J.type=h0;continue V}}return $}}readHeadByte(){if(this.headByte===n0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=n0}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 a(`Unrecognized array type byte: ${ZV(V)}`)}}pushMapState(V){if(V>this.maxMapLength)throw new a(`Max length exceeded: map length (${V}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(V)}pushArrayState(V){if(V>this.maxArrayLength)throw new a(`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 a(`Max length exceeded: UTF-8 byte length (${V}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+$+V)throw B$;let Z=this.pos+$,J;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached(V))J=this.keyDecoder.decode(this.bytes,Z,V);else J=S$(this.bytes,Z,V);return this.pos+=$+V,J}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===h0;return!1}decodeBinary(V,$){if(V>this.maxBinLength)throw new a(`Max length exceeded: bin length (${V}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(V+$))throw B$;let Z=this.pos+$,J=this.bytes.subarray(Z,Z+V);return this.pos+=$+V,J}decodeExtension(V,$){if(V>this.maxExtLength)throw new a(`Max length exceeded: ext length (${V}) > maxExtLength (${this.maxExtLength})`);let Z=this.view.getInt8(this.pos+$),J=this.decodeBinary(V,$+1);return this.extensionCodec.decode(J,Z,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=m$(this.view,this.pos);return this.pos+=8,V}readI64(){let V=VV(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 xV(V,$){return new JV($).decode(V)}class p0{listeners=new Map;addEventListener(V,$){let Z=this.listeners.get(V);if(!Z)Z=new Set,this.listeners.set(V,Z);return Z.add($),()=>{this.removeEventListener(V,$)}}removeEventListener(V,$){let Z=this.listeners.get(V);if(Z){if(Z.delete($),Z.size===0)this.listeners.delete(V)}}emit(V,$){let Z=this.listeners.get(V);if(Z){let J=Array.from(Z);for(let Q of J)Q($)}}emitAll(V){let $=Array.from(this.listeners.keys());for(let Z of $)this.emit(Z,V)}}class P0{getter;static eventName="update";emitter;constructor(V){this.getter=V;this.emitter=new p0}get=()=>this.getter();async emit(){let V=await this.getter();queueMicrotask(()=>this.emitter.emit(P0.eventName,V))}listen(V){return this.emitter.addEventListener(P0.eventName,V),()=>{this.emitter.removeEventListener(P0.eventName,V)}}}function M(V){return[V,0]}function I(V){return[void 0,V]}function NJ(V){if(V<0)console.info("N",V),console.trace();if(typeof V!=="bigint")V=BigInt(V);if(V<0n)return I(10);let $=[];while(V>0n){let Z=Number(V&0x7fn);if(V>>=7n,V>0n)$.push(Z|128);else $.push(Z)}if($.length===0)return M(new Uint8Array([0]));if($.length>8)return I(26);return M(new Uint8Array($))}function IJ(V,$=0){let Z=0n,J=0,Q=$;while(!0){if(Q>=V.length)return I(14);let W=V[Q++];if(W===void 0)return I(14);if(Z|=BigInt(W&127)<<BigInt(J),(W&128)===0){if(Q-$>8)return I(26);return M({value:Z>0x1fffffffffffffn?Z:Number(Z),bytesRead:Q-$})}if(J+=7,J>=56)return I(26)}}class m{data;pos=0;constructor(V){this.data=V}static async fromResponse(V){let $=await V.arrayBuffer(),Z=new Uint8Array($);return new m(Z)}readBigInt(){if(this.pos+8>this.data.length)return I(7);let V=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,M(V)}readDate(){let[V,$]=this.readVarInt();if($!==0)return I($);return M(new Date(V))}readVarInt(){let[V,$]=IJ(this.data,this.pos);if($!==0)return I($);this.pos+=V.bytesRead;let Z=V.value;return M(typeof Z==="bigint"?Number(Z):Z)}readVarString(){let[V,$]=this.readVarInt();if($!==0)return I($);let[Z,J]=this.readBytes(V);if(J!==0)return I(J);let Q=new TextDecoder().decode(Z);return M(Q)}readBytes(V){if(V<0)return I(10);if(this.pos+V>this.data.length)return I(23);let $=this.data.slice(this.pos,this.pos+V);return this.pos+=V,M($)}readVarBytes(){let[V,$]=this.readVarInt();if($!==0)return I($);return this.readBytes(V)}readStruct(V){return V.decode(this)}readStructs(V){let $=[];while(!this.done()){let[Z,J]=this.readStruct(V);if(J!==0)return I(J);$.push(Z)}return M($)}readBytesSeq(V){let $=[];while(!this.done()){let[Z,J]=this.readBytes(V);if(J!==0)return I(J);$.push(Z)}return M($)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class f{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[$,Z]=NJ(V);if(Z!==0)return Z;return this.parts.push($),0}writeVarString(V){let $=new TextEncoder().encode(V),Z=this.writeVarInt($.length);if(Z!==0)return Z;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 Z of $){let J=this.writeStruct(V,Z);if(J!==0)return J}return 0}writeBytesSeq(V){for(let $ of V)this.writeBytes($)}result(){let V=this.parts.reduce((J,Q)=>J+Q.length,0),$=new Uint8Array(V),Z=0;for(let J of this.parts)$.set(J,Z),Z+=J.length;return $}*scan(){for(let V of this.parts)yield V}}async function SV(V,$,Z){let J=new f,Q=J.writeDate($);if(Q!==0)return I(Q);let W=J.result(),Y=await Z.signEd25519(W,V.privateKey);return M({pubKey:V.publicKey,sig:Y,timestamp:$})}async function U0(V,$,Z){let J=Z.now().getTime(),Q=V.timestamp.getTime();if(Math.abs(J-Q)>_$)return 4;let Y=new f;Y.writeDate(V.timestamp);let X=Y.result();if(!await $.checkSigEd25519(V.sig,X,V.pubKey))return 3;return 0}var V0={encode(V,$){let Z=V.writeVarBytes($.id);if(Z!==0)return Z;let J=V.writeDate($.ts);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return I(Z);let[J,Q]=V.readDate();if(Q!==0)return I(Q);return M({id:$,ts:J})}};function QV(V){let $=new f,Z=$.writeStruct(V0,V);if(Z!==0)return I(Z);let J=$.result();return M(J)}var W0={encode(V,$){let Z=V.writeVarBytes($.eid);if(Z!==0)return Z;let J=V.writeVarInt($.off);if(J!==0)return J;let Q=V.writeVarInt($.ctr);if(Q!==0)return Q;let W=V.writeVarInt($.len);if(W!==0)return W;if($.hsh)V.writeBytes($.hsh);return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return I(Z);let J=new m($),[,Q]=V0.decode(J);if(Q!==0)return I(Q);let[W,Y]=V.readVarInt();if(Y!==0)return I(Y);let[X,K]=V.readVarInt();if(K!==0)return I(K);let[G,N]=V.readVarInt();if(N!==0)return I(N);let R;if(G>0){let[z,q]=V.readBytes(t0);if(q!==0)return I(q);R=z}return M({eid:$,off:W,ctr:X,len:G,hsh:R})}};function Y0(V){return Array.from(V).map((Z)=>Z.toString(16).padStart(2,"0")).join("")}function WV(V){if(V.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(V.length/2);for(let Z=0;Z<V.length;Z+=2)$[Z/2]=Number.parseInt(V.substr(Z,2),16);return $}function $0(V,$){if(V===$)return!0;if(V.byteLength!==$.byteLength)return!1;return V.every((Z,J)=>Z===$[J])}var x;if(typeof Uint8Array.prototype.toBase64==="function")x=(V)=>V.toBase64();else x=(V)=>btoa(String.fromCharCode(...V));var q0;if(typeof Uint8Array.fromBase64==="function")q0=(V)=>Uint8Array.fromBase64(V);else q0=(V)=>Uint8Array.from(atob(V),($)=>$.charCodeAt(0));function c0(V,$){let Z=new Uint8Array(V.length+$.length);return Z.set(V,0),Z.set($,V.length),Z}function i$(V,$,Z){return Z.checkSigEd25519(V.sig,V.headCph,$)}async function kV(V,$,Z){let J=c0($.privateKey,V);return(await Z.blake3(J)).slice(0,F0)}async function b$(V,$,Z,J){let Q;if(V.bod&&V.len>0)Q=await Z.blake3(V.bod);let W=new f,Y=W0.encode(W,{...V,hsh:Q});if(Y!==0)return I(Y);let X=W.result(),K=await kV(X,$,Z),G=await J.deriveFromKDM(K),N=await Z.encryptXSalsa20Poly1305Combined(X,G),R=V.bod?await Z.encryptXSalsa20Poly1305Combined(V.bod,G):new Uint8Array(0),z=await Z.signEd25519(N,$.privateKey);return M({sig:z,kdm:K,headCph:N,bodyCph:R})}async function mV(V,$,Z,J,Q){let W=new m(V),[Y,X]=W0.decode(W);if(X!==0)return I(14);let K;try{K=$&&$.length>0?await J.decryptXSalsa20Poly1305Combined($,Z):void 0}catch{return I(20)}let G=Y.hsh&&K===void 0,N=Y.hsh===void 0&&K!==void 0;if(G||N)return I(19);if(Y.hsh&&K){let z=await J.blake3(K);if(!$0(z,Y.hsh))return I(19)}let R=Q??await J.blake3(V);return M({msgHead:Y,bod:K,headHash:R})}class fV{now(){return new Date}}function u$(V,$,Z,J){let Q=$.getTime()-V.getTime(),W=Z.getTime()-J.getTime();return(Q+W)/2}var r0={encode(V,$){if(V.writeVarInt($.quota),$.quota>0){if($.usage===void 0)return 9;V.writeVarInt($.usage)}return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return I(Z);let J;if($>0){let[Q,W]=V.readVarInt();if(W!==0)return I(W);J=Q}return M({quota:$,usage:J})}};var BV={encode(V,$){V.writeBytes(new Uint8Array([$.status]));let Z=V.writeDate($.timeRcvd);if(Z!==0)return Z;let J=V.writeDate($.timeSent);if(J!==0)return J;let Q=V.writeVarInt($.subscription.term);if(Q!==0)return Q;let W=V.writeVarInt($.subscription.elapsed);if(W!==0)return W;let Y=V.writeStruct(r0,$.subscription.stat);if(Y!==0)return Y;let X=V.writeStruct(r0,$.subscription.dyn);if(X!==0)return X;return 0},decode(V){let[$,Z]=V.readBytes(1);if(Z!==0)return I(Z);let J=$[0],[Q,W]=V.readDate();if(W!==0)return I(W);let[Y,X]=V.readDate();if(X!==0)return I(X);let[K,G]=V.readVarInt();if(G!==0)return I(G);let[N,R]=V.readVarInt();if(R!==0)return I(R);let[z,q]=V.readStruct(r0);if(q!==0)return I(q);let[F,w]=V.readStruct(r0);if(w!==0)return I(w);return M({status:J,timeRcvd:Q,timeSent:Y,subscription:{term:K,elapsed:N,stat:z,dyn:F}})}};async function gV(V,$,Z){let{crypto:J,enclave:Q}=V,W=await Q.derive($,Z);return await J.deriveEd25519KeyPair(W)}var vV={encode(V,$){let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarInt($.seq);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return I(Z);let[J,Q]=V.readVarInt();if(Q!==0)return I(Q);return M({headCph:$,seq:J})}};var Z0={encode(V,$){V.writeBytes($.pubKey),V.writeBytes($.sig);let Z=V.writeDate($.timestamp);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readBytes(D$);if(Z!==0)return I(Z);let[J,Q]=V.readBytes(M0);if(Q!==0)return I(Q);let[W,Y]=V.readDate();if(Y!==0)return I(Y);return M({pubKey:$,sig:J,timestamp:W})}};var y$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(Z0,Z);if(W!==0)return W;for(let Y of J)Q.writeVarInt(Y);return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(Z0);if(X!==0)return X;let K=await U0(Y,Q,J);if(K!==0)return K;let{pubKey:G}=Y,[N,R]=await W.hasUser(G);if(R!==0)return R;if(!N)return 5;let[z,q]=$.readVarInt();if(q!==0)return q;if(!$.done())return 8;let[F,w]=await W.listHeads(G,z);if(w!==0)return w;return Z.writeStructs(vV,F)},decodeResp(V){return V.readStructs(vV)}};var iV={encode(V,$){V.writeVarInt($.seq);let Z=V.writeVarBytes($.bodyCph);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return I(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return I(Q);return M({seq:$,bodyCph:J})}};var l$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(Z0,Z);if(W!==0)return W;for(let Y of J){let X=Q.writeVarInt(Y);if(X!==0)return X}return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(Z0);if(X!==0)return X;let K=await U0(Y,Q,J);if(K!==0)return K;let{pubKey:G}=Y,[N,R]=await W.hasUser(G);if(R!==0)return R;if(!N)return 5;let z=[];while(!$.done()){let[w,U]=$.readVarInt();if(U!==0)return U;z.push(w)}console.info(`PULL: ${z.length} bags`);let[q,F]=await W.getBodies(G,z);if(F!==0)return F;if(!q)return 17;for(let{seq:w,bodyCph:U}of q){let P={seq:w,bodyCph:U},H=Z.writeStruct(iV,P);if(H!==0)return H}return 0},decodeResp(V){return V.readStructs(iV)}};var bV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarBytes($.bodyCph);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readBytes(M0);if(Z!==0)return I(Z);let[J,Q]=V.readBytes(F0);if(Q!==0)return I(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return I(Y);let[X,K]=V.readVarBytes();if(K!==0)return I(K);return M({sig:$,kdm:J,headCph:W,bodyCph:X})}};var YV={encode(V,$){let Z=V.writeVarInt($.seq);if(Z!==0)return Z;let J=V.writeVarBytes($.headCph);if(J!==0)return J;let Q=$.bodyCph?$.bodyCph.length:0,W=V.writeVarInt(Q);if(W!==0)return W;if(Q>0){if(!$.bodyCph)return 10;V.writeBytes($.bodyCph)}return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return I(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return I(Q);let[W,Y]=V.readVarInt();if(Y!==0)return I(Y);let X;if(W>0){let[K,G]=V.readBytes(W);if(G!==0)return I(G);X=K}return M({seq:$,headCph:J,bodyCph:X})}};var XV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readBytes(M0);if(Z!==0)return I(Z);let[J,Q]=V.readBytes(F0);if(Q!==0)return I(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return I(Y);return M({sig:$,kdm:J,headCph:W})}};var KV={encode(V,$){if(V.writeVarInt($.idx),V.writeBytes(new Uint8Array([$.status])),$.status===0)V.writeVarInt($.seq);return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return I(Z);let[J,Q]=V.readBytes(1);if(Q!==0)return I(Q);let W=J[0];if(W!==0)return M({idx:$,status:W});let[Y,X]=V.readVarInt();if(X!==0)return I(X);return M({idx:$,status:W,seq:Y})}};var n$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(Z0,Z);if(W!==0)return W;let Y=Q.writeStructs(bV,J);if(Y!==0)return Y;return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W,notifier:Y}=V,[X,K]=$.readStruct(Z0);if(K!==0)return K;let G=await U0(X,Q,J);if(G!==0)return G;let{pubKey:N}=X,[R,z]=await W.hasUser(N);if(z!==0)return z;if(!R)return 5;let[q,F]=$.readStructs(bV);if(F!==0)return F;console.info(`PUSH: ${q.length} bags`);let w=[],U=[];for(let O=0;O<q.length;O++){let D=q[O];if(!await i$(D,N,Q)){let k={idx:O,status:3},S=Z.writeStruct(KV,k);if(S!==0)return S;continue}w.push(O),U.push(D)}let[P,H]=await W.setBags(N,U);if(H!==0)return H;if(!P||P.length!==U.length)return 17;let A=[];for(let O=0;O<U.length;O++){let D=U[O],L=w[O],k=P[O],S=new f,E=S.writeStruct(XV,D);if(E!==0)return E;let B=S.result(),C={seq:k,headCph:B};if(q.length===1&&D.bodyCph.length<=j$)C.bodyCph=D.bodyCph;A.push(C);let g={idx:L,status:0,seq:k},i=Z.writeStruct(KV,g);if(i!==0)return i}if(A.length>0){let O=new f,D=O.writeStructs(YV,A);if(D!==0)return D;let L=O.result();await Promise.resolve(Y.push(N,L))}return 0},decodeResp(V){return V.readStructs(KV)}};var h$={async encodeReq(V,$,Z,J,Q){return Q.writeStruct(Z0,Z)},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(Z0);if(X!==0)return X;let K=await U0(Y,Q,J);if(K!==0)return K;let{pubKey:G}=Y;if(!$.done())return 8;let[N,R]=await W.addUser(G);if(R!==0)return R;return 0},decodeResp(V){return M(void 0)}};class uV{url;websocket;constructor(V){this.url=V}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(V,$,Z=()=>{},J=()=>{}){let{url:Q}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let W=new f;W.writeStruct(Z0,V);let Y=W.result(),X=Y0(Y);return Q.searchParams.set("t",X),this.websocket=new WebSocket(Q),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),J()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Z()},this.websocket.onmessage=(K)=>{let G=new Uint8Array(K.data);$(G)},this.websocket.onerror=(K)=>{console.log(`ERROR: ${JSON.stringify(K)}`),this.websocket=void 0,Z()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var c={user:{path:"/user",endpoint:h$,name:0},push:{path:"/push",endpoint:n$,name:2},peek:{path:"/peek",endpoint:y$,name:1},pull:{path:"/pull",endpoint:l$,name:3}},RJ={0:c.user,2:c.push,1:c.peek,3:c.pull},VX={[c.user.path]:c.user,[c.push.path]:c.push,[c.peek.path]:c.peek,[c.pull.path]:c.pull};class p${url;listener;constructor(V){this.url=V;this.listener=new uV(V)}async call(V,$){let{path:Z}=RJ[V],J=new URL(Z,this.url);try{return await zJ(J,$)}catch{return I(25)}}}var c$=(V)=>{return new p$(V.handle)};async function zJ(V,$){let Z=await fetch(V,{method:"POST",body:$.result().slice()});if(!Z.ok)return I(24);let J=await m.fromResponse(Z);return M(J)}class GV{enclave;crypto;host;clock;transport;updateHostMeta;constructor(V,$,Z,J,Q,W){this.enclave=V;this.crypto=$;this.host=Z;this.clock=J;this.transport=Q;this.updateHostMeta=W}async call(V,$){let{clock:Z,crypto:J,transport:Q}=this,{endpoint:W,name:Y}=V,X=await this.keys(),K=Z.now(),[G,N]=await SV(X,K,J);if(N!==0)return I(N);let R=new f,z=await W.encodeReq(this,X,G,$,R);if(z!==0)return I(z);let q=Z.now(),[F,w]=await Q.call(Y,R),U=Z.now();if(w!==0)return I(w);let[P,H]=F.readStruct(BV);if(H!==0)return I(H);if(P.status!==0)return I(P.status);let O={clockOffset:u$(q,P.timeRcvd,P.timeSent,U),subscription:P.subscription},D=await this.updateHostMeta(O);if(D!==0)return I(D);return W.decodeResp(F)}keys=()=>{let{host:V}=this;return gV(this,V.label,V.idx)};seal=async(V)=>{let{crypto:$,enclave:Z}=this,J=await this.keys();return b$(V,J,$,Z)};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,$,Z)=>{let{clock:J,crypto:Q,host:W,transport:Y}=this,{listener:X}=Y,K=await gV(this,W.label,W.idx),G=J.now(),[N,R]=await SV(K,G,Q);if(R!==0)return R;return await X.connect(N,V,$,Z)};isConnected(){let V=this.transport?.listener;if(V&&typeof V.connected==="function")return V.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var yV={encode(V,$){let Z=V.writeVarString($.lbl);if(Z!==0)return Z;let J=V.writeVarInt($.idx);if(J!==0)return J;let Q=V.writeVarInt($.num);if(Q!==0)return Q;return V.writeBytes($.hsh),V.writeBytes($.sig),0},decode(V){let[$,Z]=V.readVarString();if(Z!==0)return I(Z);let[J,Q]=V.readVarInt();if(Q!==0)return I(Q);let[W,Y]=V.readVarInt();if(Y!==0)return I(Y);let[X,K]=V.readBytes(t0);if(K!==0)return I(K);let[G,N]=V.readBytes(M0);if(N!==0)return I(N);return M({lbl:$,idx:J,num:W,hsh:X,sig:G})}};var lV={encode(V,$){let Z=V.writeStruct(yV,$.head);if(Z!==0)return Z;let J=V.writeVarBytes($.indexEnc);if(J!==0)return J;let Q=V.writeVarBytes($.bodyEnc);if(Q!==0)return Q;return 0},decode(V){let[$,Z]=V.readStruct(yV);if(Z!==0)return I(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return I(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return I(Y);return M({head:$,indexEnc:J,bodyEnc:W})}};var nV={encode(V,$){V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarInt($.lenBody);if(J!==0)return J;if($.lenBody>0&&$.offBody!==void 0){let Q=V.writeVarInt($.offBody);if(Q!==0)return Q}return 0},decode(V){let[$,Z]=V.readBytes(F0);if(Z!==0)return I(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return I(Q);let[W,Y]=V.readVarInt();if(Y!==0)return I(Y);let X;if(W>0){let[K,G]=V.readVarInt();if(G!==0)return I(G);X=K}return M({kdm:$,headCph:J,lenBody:W,offBody:X})}};async function r$(V,$,Z,J,Q){let W=await Q.derive(V,$),Y=await J.deriveEd25519KeyPair(W),X=new f,K=new f,G=0,N=0;for(let H of Z){let A=new f,O=A.writeStruct(W0,H.head);if(O!==0)return I(O);let D=A.result(),L=await kV(D,Y,J),k=await Q.deriveFromKDM(L),S=await J.encryptXSalsa20Poly1305Combined(D,k),E=H.body?await J.encryptXSalsa20Poly1305Combined(H.body,k):new Uint8Array(0),B=H.head.len>0&&H.head.hsh!==void 0?E.length:0,C={kdm:L,headCph:S,lenBody:B,offBody:B>0?N:void 0},g=X.writeStruct(nV,C);if(g!==0)return I(g);if(H.body)K.writeBytes(E),N+=E.length;G++}let R=K.result(),z=X.result(),q=await J.blake3(z),F=await J.signEd25519(q,Y.privateKey),w={lbl:V,idx:$,num:G,hsh:q,sig:F},U=new f;U.writeStruct(lV,{head:w,indexEnc:z,bodyEnc:R});let P=U.result();return M(P)}async function d$(V,$,Z){let[J,Q]=lV.decode(new m(V));if(Q!==0)return I(Q);let{head:W,indexEnc:Y,bodyEnc:X}=J,K=await Z.derive(W.lbl,W.idx),G=await $.deriveEd25519KeyPair(K);if(!await $.checkSigEd25519(W.sig,W.hsh,G.publicKey))return I(3);let R=await $.blake3(Y);if(!$0(R,W.hsh))return I(19);let z=new m(Y),q=[];for(let w=0;w<W.num;w++){let[U,P]=z.readStruct(nV);if(P!==0)return I(P);q.push(U)}if(q.length!==W.num)return I(14);let F=[];for(let w of q){let U=await Z.deriveFromKDM(w.kdm),P=await $.decryptXSalsa20Poly1305Combined(w.headCph,U),[H,A]=W0.decode(new m(P));if(A!==0)return I(A);let O;if(w.lenBody>0&&w.offBody!==void 0){if(H.hsh===void 0)return I(14);let D=X.slice(w.offBody,w.offBody+w.lenBody);O=await $.decryptXSalsa20Poly1305Combined(D,U);let L=await $.blake3(O);if(!$0(L,H.hsh))return I(19)}F.push({head:H,body:O})}return M(F)}async function o$({now:V,bod:$,crypto:Z}){let J=await Z.genRandomBytes(8),Q=new f,W=Q.writeStruct(V0,{id:J,ts:V});if(W!==0)return I(W);let Y=Q.result();return NV({now:V,eid:Y,ctr:0,bod:$,crypto:Z})}async function NV({now:V,eid:$,ctr:Z,bod:J,crypto:Q}){let W=new m($),[Y,X]=V0.decode(W);if(X!==0)return I(X);let K=V.getTime()-Y.ts.getTime(),G,N=J?.length??0;if(J&&N>0)G=await Q.blake3(J);return M({eid:$,off:K,ctr:Z,len:N,hsh:G})}var hX=Symbol("EntityID");function a$(V){return"type"in V}var pX=Symbol("MasterSeed"),cX=Symbol("DerivationSeed"),rX=Symbol("PublicKey"),dX=Symbol("PrivateKey"),oX=Symbol("HostSpecificKeyPair"),aX=Symbol("Hash");function wJ(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 MJ(V){if(!V.bod||V.bod.length===0){let J={off:V.off,ctr:V.ctr,eid:V.eid};return M(J)}let $=xV(V.bod);if(wJ($)===!1)return console.warn("msg body invalid",$),I(14);let Z={off:V.off,ctr:V.ctr,eid:V.eid,gid:$.gid,pid:$.pid,type:$.type,body:$.body};return M(Z)}class IV{applier;emitter=new p0;clearer;onDirtyEids;cacheDriven;peerIngest;constructor(V,$,Z,J){this.applier=V;this.clearer=$,this.onDirtyEids=Z,this.cacheDriven=J?.cacheDriven??!1,this.peerIngest=J?.peerIngest}apply=async(V)=>{let $=[],Z=[];for(let X of V){let[K,G]=MJ(X);if(Z.push(G),G!==0)continue;$.push(K)}let{stats:J,types:Q,eids:W}=await this.applier($),Y=[];for(let X=0;X<V.length;X++){let K=Z[X],G=J[X];if(K!==0){Y.push(K);continue}if(G!==0){Y.push(G);continue}Y.push(0)}if(!this.cacheDriven)for(let X of Q)this.emitter.emit(X,null);if(W.length>0)this.onDirtyEids?.(W);return Y};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 u="entities",RV="entity_type_created_at",hV="entity_type_updated_at",pV="entity_type_group_id",cV="entity_type_parent_id";function FJ(V){let $={bod:V.body,crd:V.createdAt,...V.ctr!==0?{ctr:V.ctr}:{},eid:x(V.eid),gid:V.gid,pid:V.pid?x(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 k0(V){return{body:V.bod,createdAt:V.crd,updatedAt:V.upd,ctr:V.ctr??0,type:V.typ,eid:q0(V.eid),gid:V.gid,pid:V.pid?q0(V.pid):void 0}}class s${db;async init(){this.db=await new Promise((V,$)=>{let Z=indexedDB.open("db",11);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!Q)throw Error("Transaction is null during upgrade");if(!J.objectStoreNames.contains(u))J.createObjectStore(u,{keyPath:"eid",autoIncrement:!1});let W=Q.objectStore(u);if(!W.indexNames.contains(RV))W.createIndex(RV,["typ","crd"],{unique:!1});if(!W.indexNames.contains(hV))W.createIndex(hV,["typ","upd"],{unique:!1});if(!W.indexNames.contains(pV))W.createIndex(pV,["typ","gid"],{unique:!1});if(!W.indexNames.contains(cV))W.createIndex(cV,["typ","pid"],{unique:!1})},Z.onsuccess=()=>V(Z.result),Z.onerror=()=>$(Z.error)})}apply=async(V)=>{let $=new Set,Z=[];if(!this.db)return{stats:V.map(()=>16),types:$,eids:Z};let J=this.db.transaction(u,"readwrite"),Q=J.objectStore(u);return new Promise((W)=>{let Y=Array(V.length).fill(0);if(V.length<1){W({stats:[],types:$,eids:Z});return}J.oncomplete=()=>{W({stats:Y,types:$,eids:Z})},J.onerror=()=>{for(let K=0;K<Y.length;K++)if(Y[K]===void 0)Y[K]=18;W({stats:Y,types:$,eids:Z})};let X=new Map;for(let K=0;K<V.length;K++){let G=V[K],N=x(G.eid),R={op:G,index:K},z=X.get(N);if(z)z.push(R);else X.set(N,[R])}for(let[K,G]of X){if(G.length<1)continue;let N=Q.get(K);N.onsuccess=()=>{let R=N.result,z=R?k0(R):void 0,q=!1;for(let{op:F,index:w}of G){let[U,P]=m0(z,F);if(P!==0){Y[w]=P;continue}if(q=!0,U)$.add(U.type);else if(z)$.add(z.type);z=U}if(q)Z.push(G[0].op.eid);if(z){let F=FJ(z),w=Q.put(F);w.onerror=(U)=>{U.preventDefault();for(let{index:P}of G)Y[P]=18}}else{let F=Q.delete(K);F.onerror=()=>{for(let{index:w}of G)Y[w]=18}}},N.onerror=()=>{for(let{index:R}of G)Y[R]=18}}})};async clear(){if(!this.db)return 16;let V=this.db.transaction(u,"readwrite"),$=V.objectStore(u);return new Promise((Z)=>{V.oncomplete=()=>Z(0),V.onerror=()=>Z(18),$.clear()})}async getEnt(V){if(!this.db)return I(16);let $=x(V),J=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Q)=>{let W=J.get($);W.onsuccess=()=>{let Y=W.result;if(!Y)Q(M(void 0));else{let X=k0(Y);Q(M(X))}},W.onerror=()=>Q(I(18))})}async getAllOfTypeUpdatedBetween(V,$,Z){if(!this.db)return I(16);let Q=this.db.transaction(u,"readonly").objectStore(u).index(hV);return new Promise((W)=>{let Y=Q.getAll(IDBKeyRange.bound([V,$],[V,Z]));Y.onsuccess=()=>{let X=Y.result;W(M(X.map(k0)))},Y.onerror=()=>W(I(18))})}async getGroupMembers(V,$){if(!this.db)return I(16);let J=this.db.transaction(u,"readonly").objectStore(u).index(pV);return new Promise((Q)=>{let W=J.getAll(IDBKeyRange.only([V,$]));W.onsuccess=()=>{let Y=W.result;Q(M(Y.map(k0)))},W.onerror=()=>Q(I(18))})}async getAllOfType(V){if(!this.db)return I(16);let Z=this.db.transaction(u,"readonly").objectStore(u).index(RV);return new Promise((J)=>{let Q=Z.getAll(IDBKeyRange.bound([V],[V,[]]));Q.onsuccess=()=>{let W=Q.result;J(M(W.map(k0)))},Q.onerror=()=>J(I(18))})}async getAllEntities(V){if(!this.db)return I(16);if("pid"in V){let $=x(V.pid),J=this.db.transaction(u,"readonly").objectStore(u).index(cV);return new Promise((Q)=>{let W=J.getAll(IDBKeyRange.only([V.type,$]));W.onsuccess=()=>{let X=W.result.map(k0);Q(M(X))},W.onerror=()=>Q(I(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[$,Z]=await this.getAllEntities(V);if(Z!==0)return I(Z);return M($)}async countEntities({type:V}){if(!this.db)return I(16);let Z=this.db.transaction(u,"readonly").objectStore(u).index(RV);return new Promise((J)=>{let Q=IDBKeyRange.bound([V],[V,[]]),W=Z.count(Q);W.onsuccess=()=>J(M(W.result)),W.onerror=()=>J(I(18))})}}async function t$(){let V=new s$;return await V.init(),V}class rV{ents=new Map;useIndex;byType=new Map;byTypePid=new Map;byTypeGid=new Map;constructor(V=[],$){this.useIndex=$?.indexes!==!1;for(let Z of V)this.put(Z)}put(V){let $=x(V.eid),Z=this.ents.get($);if(Z)this.unindex($,Z);this.ents.set($,V),this.index($,V)}del(V){let $=this.ents.get(V);if(!$)return;this.unindex(V,$),this.ents.delete(V)}index(V,$){if(!this.useIndex)return;let Z=this.byType.get($.type);if(!Z)Z=new Map,this.byType.set($.type,Z);if(Z.set(V,$),$.pid){let J=x($.pid),Q=this.byTypePid.get($.type);if(!Q)Q=new Map,this.byTypePid.set($.type,Q);let W=Q.get(J);if(!W)W=new Map,Q.set(J,W);W.set(V,$)}if(typeof $.gid==="string"){let J=this.byTypeGid.get($.type);if(!J)J=new Map,this.byTypeGid.set($.type,J);let Q=J.get($.gid);if(!Q)Q=new Map,J.set($.gid,Q);Q.set(V,$)}}unindex(V,$){if(!this.useIndex)return;let Z=this.byType.get($.type);if(Z){if(Z.delete(V),Z.size===0)this.byType.delete($.type)}if($.pid){let J=x($.pid),Q=this.byTypePid.get($.type),W=Q?.get(J);if(W){if(W.delete(V),W.size===0)Q?.delete(J)}if(Q&&Q.size===0)this.byTypePid.delete($.type)}if(typeof $.gid==="string"){let J=this.byTypeGid.get($.type),Q=J?.get($.gid);if(Q){if(Q.delete(V),Q.size===0)J?.delete($.gid)}if(J&&J.size===0)this.byTypeGid.delete($.type)}}clearIndexes(){this.byType.clear(),this.byTypePid.clear(),this.byTypeGid.clear()}bucketList(V){if(!V||V.size===0)return[];let $=[];for(let Z of V.values())$.push(Z);return $}async apply(V){let $=new Set,Z=[],J=[];for(let Q of V){let W=x(Q.eid),Y=this.ents.get(W),[X,K]=m0(Y,Q);if(K!==0){J.push(K);continue}if(X)$.add(X.type);else if(Y)$.add(Y.type);if(X)this.put(X);else this.del(W);Z.push(Q.eid),J.push(0)}return{stats:J,types:$,eids:Z}}async clear(){return this.ents.clear(),this.clearIndexes(),0}async getEnt(V){let $=x(V),Z=this.ents.get($);return M(Z)}async getAllEntities({type:V,gid:$,pid:Z,updatedBetween:J}){if(this.useIndex){if(Z!==void 0){let W=x(Z);return M(this.bucketList(this.byTypePid.get(V)?.get(W)))}if($!==void 0)return M(this.bucketList(this.byTypeGid.get(V)?.get($)));if(J!==void 0){let W=[],Y=this.byType.get(V);if(Y){for(let X of Y.values())if(X.updatedAt>=J.start&&X.updatedAt<=J.end)W.push(X)}return M(W)}return M(this.bucketList(this.byType.get(V)))}let Q=[];if(Z!==void 0){for(let W of this.ents.values())if(W.type===V&&W.pid&&$0(W.pid,Z))Q.push(W)}else if($!==void 0){for(let W of this.ents.values())if(W.type===V&&(typeof W.gid==="string"&&W.gid===$))Q.push(W)}else if(J!==void 0){for(let W of this.ents.values())if(W.type===V&&W.updatedAt>=J.start&&W.updatedAt<=J.end)Q.push(W)}else for(let W of this.ents.values())if(W.type===V)Q.push(W);return M(Q)}async getEntities(V){let[$,Z]=await this.getAllEntities(V);if(Z!==0)return I(Z);return M($)}async countEntities({type:V}){if(this.useIndex)return M(this.byType.get(V)?.size??0);let $=0;for(let Z of this.ents.values())if(Z.type===V)$+=1;return M($)}}async function e$(V){let $=await t$();if(V?.cache===!1)return $;return new dV($,void 0,{indexes:V?.indexes})}class dV{mem;durable;warmed=new Set;listeners=new Set;chain=Promise.resolve();constructor(V,$,Z){if(this.durable=V,this.mem=new rV($??[],{indexes:Z?.indexes}),$)for(let J of $)this.warmed.add(J.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 $=HJ(this.mem,V);this.emit($.types);let Z=await this.durable.apply(V),{changed:J,status:Q}=await this.pullEids(V.map((W)=>W.eid));this.emit(J);for(let W of Z.types)this.warmed.add(W);if(Q!==0)return{stats:V.map(()=>Q),types:Z.types,eids:Z.eids};return Z})}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:Z}=await this.pullEids(V);return this.emit($),Z})}async pullEids(V){let $=new Set,Z=new Set;for(let J of V){let Q=x(J);if(Z.has(Q))continue;Z.add(Q);let W=this.mem.ents.get(Q),[Y,X]=await this.durable.getEnt(J);if(X!==0)return{changed:$,status:X};if(Y){if(this.mem.put(Y),this.warmed.add(Y.type),!W||!UJ(W,Y)){if($.add(Y.type),W&&W.type!==Y.type)$.add(W.type)}}else if(W)this.mem.del(Q),$.add(W.type)}return{changed:$,status:0}}async warmType(V){if(this.warmed.has(V))return 0;let[$,Z]=await this.durable.getEntities({type:V});if(Z!==0)return Z;if($)for(let J of $){let Q=x(J.eid),W=this.mem.ents.get(Q);if(!W||PJ(J,W))this.mem.put(J)}return this.warmed.add(V),0}async getEnt(V){let $=x(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[Z,J]=await this.durable.getEnt(V);if(J!==0)return I(J);if(Z)this.mem.put(Z),this.warmed.add(Z.type);return M(Z)})}async getEntities(V){if(!this.warmed.has(V.type)){let $=await this.run(()=>this.warmType(V.type));if($!==0)return I($)}return this.mem.getEntities(V)}async countEntities({type:V}){if(!this.warmed.has(V)){let $=await this.run(()=>this.warmType(V));if($!==0)return I($)}return this.mem.countEntities({type:V})}}function UJ(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(!$0(V.eid,$.eid))return!1;if(!qJ(V.pid,$.pid))return!1;return OJ(V.body,$.body)}function qJ(V,$){if(V===void 0&&$===void 0)return!0;if(V===void 0||$===void 0)return!1;return $0(V,$)}function OJ(V,$){if(Object.is(V,$))return!0;if(V instanceof Uint8Array&&$ instanceof Uint8Array)return $0(V,$);if(V instanceof Date&&$ instanceof Date)return V.getTime()===$.getTime();try{return $0(O0(V),O0($))}catch{return!1}}function PJ(V,$){let Z=V.updatedAt.getTime(),J=$.updatedAt.getTime();if(Z!==J)return Z>J;return V.ctr>$.ctr}function HJ(V,$){let Z=new Set,J=[];for(let Q of $){let W=x(Q.eid),Y=V.ents.get(W),[X,K]=m0(Y,Q);if(K!==0){J.push(K);continue}if(X)Z.add(X.type);else if(Y)Z.add(Y.type);if(X)V.put(X);else V.del(W);J.push(0)}return{stats:J,types:Z}}function VZ(V){let $=new m(V.eid),[Z,J]=$.readStruct(V0);if(J!==0)return I(J);return M({eid:V.eid,ctr:V.ctr,updatedAt:new Date(Z.ts.getTime()+V.off)})}function m0(V,$){let Z=new m($.eid),[J,Q]=Z.readStruct(V0);if(Q!==0)return I(Q);let W=new Date(J.ts.getTime()+$.off);if(V!==void 0&&W<=V.updatedAt)return I(15);if(a$($))return M({eid:$.eid,gid:$.gid,pid:$.pid,type:$.type,createdAt:J.ts,updatedAt:W,ctr:$.ctr,body:$.body});else return M(void 0)}class zV{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 $Z=100;class oV{timer=null;delayMs;work;tail=new zV;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 ZZ(V){let $=new m(V.eid),[Z,J]=V0.decode($);if(J!==0)return;return Z.ts.getTime()+V.off}function CJ(V,$){let Z=ZZ(V),J=ZZ($);if(Z===void 0&&J===void 0)return 0;if(Z===void 0)return 1;if(J===void 0)return-1;if(J!==Z)return J-Z;return $.ctr-V.ctr}function d0(V,$){return V.slice().sort((Z,J)=>CJ($(Z),$(J)))}var aV={phase:"idle"},wV=50;function JZ(V,$,Z){if(V<=0||$<=0)return!1;if(V===1||V===$)return!0;return V%Z===0}function QZ(V,$){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(V,$);return}let Z=URL.createObjectURL(V),J=document.createElement("a");J.href=Z,J.download=$,document.body.appendChild(J),J.click(),document.body.removeChild(J),URL.revokeObjectURL(Z)}function WZ(V,$,Z){let J=[],Q=[],W=0;for(let Y of V){let X=$(Y);if(Q.length>0&&W+X>Z)J.push(Q),Q=[],W=0;if(Q.push(Y),W+=X,W>=Z)J.push(Q),Q=[],W=0}if(Q.length>0)J.push(Q);return J}async function YZ(V,$,Z){let J=V.length;if(J<1)return[];let Q=Array(J),W=0,Y=Math.min(Math.max(1,$),J),X=async()=>{while(!0){let G=W;if(W+=1,G>=J)return;Q[G]=await Z(V[G],G)}},K=[];for(let G=0;G<Y;G++)K.push(X());return await Promise.all(K),Q}async function sV(V,$,Z,J){let Q=new m(V.headCph),[W,Y]=Q.readStruct(XV);if(Y!==0)return I(Y);let{sig:X,kdm:K,headCph:G}=W;if(!await J.checkSigEd25519(X,G,$.publicKey))return I(3);let R=await Z.deriveFromKDM(K),z;try{z=await J.decryptXSalsa20Poly1305Combined(G,R)}catch{return I(20)}return M({kdm:K,headEnc:z})}var B0="f",MV="t",f0="e";function TJ(V){if(V===!0||V===MV)return MV;if(V===f0)return f0;return B0}function XZ(V){return V!==0&&V!==15&&V!==18&&V!==17}function tV(V,$,Z){if(V.apld=$,$===f0&&Z!==void 0)V.err=Z;else delete V.err}async function FV(V,$,Z){let J=TJ($.apld),Q=$.body,W=Q?.length??0,Y;if(Q&&W>0)Y=await Z.blake3(Q);let X={eid:$.eid,off:$.off??0,ctr:$.ctr??0,len:W,hsh:Y},K={hash:V,head:X,apld:J};if(Q!==void 0)K.body=Q;if(J===f0&&$.err!==void 0)K.err=$.err;return K}var eV=1048576,V$=1048576,AJ=64;function DJ(V){return V.sig.length+V.kdm.length+V.headCph.length+V.bodyCph.length}async function _J(V,$,Z,J,Q){if(J.length<1)return 0;let[W,Y]=await V.push(J);if(Y!==0)return Y;if(!W)return 27;for(let K of W){if(K.status!==0){console.error("push err",K);continue}let G=Q[K.idx];if(!G){console.error("no hash",K);continue}await $.uploads.deq(Z,[G])}let X=await $.hosts.get(Z);if(X){let K=X.lastSeq,G=K,N=[];for(let R of W)if(R.status===0)N.push(R.seq);N.sort((R,z)=>R-z);for(let R of N)if(R===K+1)K=R;if(K>G)await $.hosts.touch(Z,K)}return 0}async function KZ(V,$){if($.length<1)return M([]);let Z=new Map,J=[];for(let X of $)Z.set(X.seq,X),J.push(X.seq);let[Q,W]=await V.pull(J);if(W!==0)return I(W);if(!Q)return I(27);let Y=[];for(let{seq:X,bodyCph:K}of Q){let G=Z.get(X);if(!G)continue;Y.push({dl:G,bodyCph:K})}return M(Y)}async function jJ(V,$,Z,J){if(J.length<1)return M({parts:[],hashes:[]});let Q=[],W=[],Y=[],X=new Map;for(let{dl:G,bodyCph:N}of J){let{head:R,kdm:z,seq:q,host:F}=G,[w,U]=await GZ(G,Z);if(U!==0||!w){let E=X.get(F)??[];E.push(q),X.set(F,E);continue}let{headEnc:P,headEncHash:H}=w,A=await $.deriveFromKDM(z),[O,D]=await mV(P,N,A,Z,H);if(D!==0||!O){let E=X.get(F)??[];E.push(q),X.set(F,E);continue}let L={head:R,body:O.bod},k=O.headHash;Y.push({key:k,data:wZ(L)}),Q.push(L),W.push(k);let S=X.get(F)??[];S.push(q),X.set(F,S)}let K=await V.messages.add(Y);for(let[G,N]of X)await V.downloads.deq(G,N);for(let G=0;G<K.length;G++){let N=K[G];if(N!==0&&N!==15)console.error("ERR storing",_[N],"for message",G)}return M({parts:Q,hashes:W})}async function GZ(V,$){let Z=V.headEnc;if(!Z){let Q=new f,W=Q.writeStruct(W0,V.head);if(W!==0)return I(W);Z=Q.result()}if(V.headEncHash)return M({headEnc:Z,headEncHash:V.headEncHash});let J=await $.blake3(Z);return M({headEnc:Z,headEncHash:J})}async function NZ(V,$,Z){let J=new Set;for(let Y of $)J.add(x(Y));if(J.size<1)return;let Q=Array.from(await V.downloads.list());if(Q.length<1)return;let W=new Map;for(let Y of Q){let X;if(Y.headEncHash)X=x(Y.headEncHash);else{let[G,N]=await GZ(Y,Z);if(N!==0||!G)continue;X=x(G.headEncHash)}if(!J.has(X))continue;let K=W.get(Y.host)??[];K.push(Y.seq),W.set(Y.host,K)}for(let[Y,X]of W)await V.downloads.deq(Y,X)}async function IZ({conn:V,store:$,enclave:Z,host:J,crypto:Q,onProgress:W,peekProgressEvery:Y,peekConcurrency:X}){let K=await V.keys(),G=[],[N,R]=await V.peek(J.lastSeq);if(R!==0)return R;let z=N.length,q=Y??wV,F=X??AJ;if(W&&z>0)W({phase:"peek",host:J.label,done:0,total:z});let w=0,U=await YZ(N,F,async(P)=>{let[H,A]=await sV(P,K,Z,Q),O;if(A!==0||!H)O={ok:!1,seq:P.seq,stat:A};else{let D=await Q.blake3(H.headEnc);O={ok:!0,seq:P.seq,kdm:H.kdm,headEnc:H.headEnc,headEncHash:D}}if(w+=1,W&&JZ(w,z,q))W({phase:"peek",host:J.label,done:w,total:z});return O});for(let P of U){if(!P.ok){console.error("peek: decrypting item head",P.stat);continue}if(await $.messages.has(P.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await $.uploads.deq(J.label,[P.headEncHash]),await $.downloads.deq(J.label,[P.seq]);continue}let A=new m(P.headEnc),[O,D]=A.readStruct(W0);if(D!==0){console.error("peek: reading item head",D);continue}G.push({kdm:P.kdm,head:O,seq:P.seq,host:J.label,headEnc:P.headEnc,headEncHash:P.headEncHash})}if(await $.downloads.enq(G),N.length>0){let P=Math.max(...N.map((H)=>H.seq));await $.hosts.touch(J.label,P)}if(W)W({phase:"peek",host:J.label,done:z,total:z});return 0}async function RZ({conn:V,store:$,host:Z,maxPushBytes:J,onProgress:Q}){let W=J??eV,Y=await $.uploads.list(Z.label),X=Y.length,K=0;if(Q&&X>0)Q({phase:"push",host:Z.label,done:0,total:X});let G=[],N=[],R=0,z=async()=>{if(G.length<1)return 0;let q=G.length,F=await _J(V,$,Z.label,G,N);if(G=[],N=[],R=0,F===0){if(K+=q,Q)Q({phase:"push",host:Z.label,done:K,total:X})}return F};for(let q of Y){let F=await $.messages.get(q);if(!F){K+=1;continue}let w={...F.head,bod:F.body},[U,P]=await V.seal(w);if(P!==0)return P;if(!U)return 12;let H=DJ(U);if(G.length>0&&R+H>W){let A=await z();if(A!==0)return A}if(G.push(U),N.push(q),R+=H,R>=W){let A=await z();if(A!==0)return A}}return z()}async function zZ({conn:V,store:$,enclave:Z,host:J,crypto:Q,maxPullBytes:W,onProgress:Y},X){let K=W??V$,G=await $.downloads.list(),N=Array.from(G).filter((U)=>U.host===J.label);if(N.length<1)return 15;let R=d0(N,(U)=>U.head),z=WZ(R,(U)=>U.head.len,K),q=R.length,F=0;if(Y)Y({phase:"pull",host:J.label,done:0,total:q});let w=KZ(V,z[0]);for(let U=0;U<z.length;U++){let[P,H]=await w;if(H!==0||!P)return H;if(F+=z[U].length,Y)Y({phase:"pull",host:J.label,done:F,total:q});let A=z[U+1];if(A)w=KZ(V,A);if(Y)Y({phase:"open",host:J.label,done:F,total:q});let O=d0(P,(L)=>L.dl.head),[,D]=await jJ($,Z,Q,O);if(D!==0)return D;if(X){if(Y)Y({phase:"exec",host:J.label,done:F,total:q});await X()}}return 0}function wZ({head:V,body:$}){let Z={eid:V.eid,body:$,apld:B0};if(V.off!==0)Z.off=V.off;if(V.ctr!==0)Z.ctr=V.ctr;return Z}async function MZ(V,{conn:$,store:Z,enclave:J,host:Q,crypto:W,onProgress:Y},X){let K=Q.label,G=await $.keys(),N=new m(V),[R,z]=N.readStructs(YV);if(z!==0){console.error("Failed decoding notif",_[z]);return}let q=!1,w=(await Z.hosts.get(K))?.lastSeq,U=[],P=!1;for(let O of R){let[D,L]=await sV({seq:O.seq,headCph:O.headCph},G,J,W);if(L!==0){console.error("Failed decrypting notif",_[L]);continue}let k=await W.blake3(D.headEnc);if(await Z.messages.has(k))continue;let S=new m(D.headEnc),[E,B]=S.readStruct(W0);if(B!==0){console.error("Failed to parse head",_[B]);continue}if(!O.bodyCph&&E.len>0)P=!0,await Z.downloads.enq([{seq:O.seq,host:K,kdm:D.kdm,head:E,headEnc:D.headEnc,headEncHash:k}]);else U.push({...D,head:E,bodyCph:O.bodyCph,headEncHash:k});if(w===void 0||O.seq!==w+1)console.log("out of seq",O.seq,w),q=!0;else w=O.seq}if(w!==void 0)await Z.hosts.touch(Q.label,w);let H=[];for(let O of U){let D=await J.deriveFromKDM(O.kdm),[L,k]=await mV(O.headEnc,O.bodyCph,D,W);if(k!==0){console.error("Failed to open body",_[k]);continue}H.push({key:O.headEncHash,data:wZ({head:O.head,body:L.bod})})}let A=await Z.messages.add(H);for(let O=0;O<A.length;O++){let D=A[O];if(D!==0&&D!==15)console.error("ERR storing",_[D],"for message",O)}if(Y&&H.length>0)Y({phase:"open",host:Q.label,done:H.length,total:H.length});if(q||P||H.length>0)X()}class $${clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new zV;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=wV;lastProgress=aV;scheduledSync;constructor(V,$,Z,J,Q,W=!0,Y=eV,X=V$,K){this.clock=V;this.state=$;this.store=Z;this.transport=J;this.crypto=Q;this.forceSkewHandlingByDefault=W;this.onScheduleSync=K;this.maxPushBytes=Y,this.maxPullBytes=X,this.clientState=new P0(()=>this.getClientState()),this.xferState=new P0(()=>this.getXferState()),this.scheduledSync=new oV($Z,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,Z=await V.seed.load(),J=await V.hosts.list(),Q=!1;for(let W of $.values())if(W.isConnected()){Q=!0;break}return{hasSeed:Z!==void 0,hasHost:Array.from(J).length>0,connected:Q}}async getXferState(){let{uploads:V,downloads:$}=this.store,Z=await V.count();return{numDownloads:await $.count(),numUploads:Z,progress:this.lastProgress}}apply=(V,$)=>{return this.enqueueApplyJob(()=>this.doApply(V,$))};async doApply(V,$={enqueueUpload:!0,triggerUpload:!0}){let Z=[],J=[];for(let{head:W,body:Y}of V){let X=new f;X.writeStruct(W0,W);let K=X.result(),G=await this.crypto.blake3(K),N={eid:W.eid,body:Y,apld:B0};if(W.off!==0)N.off=W.off;if(W.ctr!==0)N.ctr=W.ctr;Z.push(G),J.push({key:G,data:N})}await this.store.messages.add(J),await NZ(this.store,Z,this.crypto);let Q=await this.doApplyHashes(Z);if($.enqueueUpload){let W=[];for(let Y=0;Y<Z.length;Y++){let X=Q[Y];if(X===0||X===15)W.push(Z[Y])}if(W.length>0){let Y=await this.store.hosts.list();for(let X of Y)await this.store.uploads.enq(X.label,W);this.xferState.emit()}}if($.triggerUpload)this.scheduleSync();return Q}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(B0);if(V.length<1)return[];let $=d0(V,(Z)=>Z.head);return this.applyStored($)}applyHashes=(V)=>{return this.enqueueApplyJob(()=>this.doApplyHashes(V))};async doApplyHashes(V){let $=[];for(let Q of V){let W=await this.store.messages.get(Q);if(W)$.push(W)}let Z=await this.applyStored($),J=new Map;for(let Q=0;Q<$.length;Q++)J.set(x($[Q].hash),Z[Q]??12);return V.map((Q)=>J.get(x(Q))??13)}async applyStored(V){if(V.length<1)return[];let $=V.map((W)=>({...W.head,bod:W.body})),Z=await this.state.apply($),J=[],Q=[];for(let W=0;W<V.length;W++){let Y=Z[W];if(Y===0||Y===15)J.push(V[W].hash);else if(Y!==void 0&&XZ(Y))Q.push({key:V[W].hash,err:Y})}if(J.length>0)await this.store.messages.markApplied(J);if(Q.length>0)await this.store.messages.markFailed(Q);return Z}async insertRaw(V){let{clock:$,crypto:Z}=this,[J,Q]=await o$({now:$.now(),bod:V,crypto:Z});if(Q!==0)return I(Q);let Y=(await this.apply([{head:J,body:V}]))[0];if(Y!==0&&Y!==15)return I(Y??12);return M(J)}async makeUpdate(V,$){let{clock:Z,crypto:J}=this,Q=Z.now();if(V.updatedAt.getTime()>Q.getTime())return I(4);let W=V.ctr+1,[Y,X]=await NV({now:Q,eid:V.eid,ctr:W,bod:$,crypto:J});if(X!==0)return I(X);return M({head:Y,body:$})}async updateWithSkew(V,$,Z){if(Z===!1)return I(4);let{clock:J,crypto:Q}=this,W=J.now(),Y=new m(V.eid),[X,K]=Y.readStruct(V0);if(K!==0)return I(K);let G=V.updatedAt.getTime()-X.ts.getTime(),N={eid:V.eid,off:G+1,ctr:V.ctr+1,len:0},z=(await this.apply([{head:N,body:void 0}]))[0];if(z!==0&&z!==15)return I(z??12);if($===void 0)return M(N);let[q,F]=QV({id:X.id,ts:W});if(F!==0)return I(F);let[w,U]=await NV({now:W,eid:q,ctr:0,bod:$,crypto:Q});if(U!==0)return I(U);let H=(await this.apply([{head:w,body:$}]))[0];if(H!==0&&H!==15)return I(H??12);return M(w)}async updateRaw(V,$,Z=this.forceSkewHandlingByDefault){if(V.updatedAt.getTime()>this.clock.now().getTime())return this.updateWithSkew(V,$,Z);return this.enqueueApplyJob(async()=>{let[J,Q]=await this.makeUpdate(V,$);if(Q!==0)return I(Q);let Y=(await this.doApply([J]))[0];if(Y!==0&&Y!==15)return I(Y??12);return M(J.head)})}async insert(V){let{body:$,type:Z,gid:J,pid:Q}=V,Y=O0({body:$,type:Z,gid:J,pid:Q});return this.insertRaw(Y)}async update(V){let{prior:$,body:Z,type:J,gid:Q,pid:W,force:Y}=V,K=O0({body:Z,type:J,gid:Q,pid:W});return this.updateRaw($,K,Y??this.forceSkewHandlingByDefault)}async delete(V){let $=V.force??!0;if("prior"in V)return this.updateRaw(V.prior,void 0,$);let[Z,J]=await this.revFromArchive(V.eid);if(J!==0)return I(J);return this.updateRaw(Z,void 0,$)}async revFromArchive(V){let $=await this.store.messages.last(V);if($)return VZ($.head);let Z=new m(V),[J,Q]=Z.readStruct(V0);if(Q!==0)return I(Q);return M({eid:V,ctr:-1,updatedAt:J.ts})}async genEID(V){let{clock:$,crypto:Z}=this,J=$.now();if(V!==void 0)return QV({id:V,ts:J});let Q=await Z.genRandomBytes(8);return QV({id:Q,ts:J})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:V,crypto:$,store:Z}=this,J=await Z.seed.load();if(!J)return 22;await this.drainApplyQueue();for(let[Q,W]of V){let Y=await Z.hosts.get(Q);if(!Y)continue;let X={conn:W,store:Z,enclave:J,host:Y,crypto:$,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},K=await IZ(X);if(K!==0)return console.error(`Failed to peek: ${K}`),K;this.xferState.emit();let G=await RZ(X);if(G!==0)return console.error(`Failed to push: ${G}`),G;this.xferState.emit();let N=await zZ(X,async()=>{await this.drainApplyQueue()});if(N!==0&&N!==15)return console.error(`Failed to pull: ${N}`),N;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=aV,this.clientState.emit(),this.xferState.emit()}import=async(V,$)=>{let{crypto:Z,store:J}=this,Q=$?.onProgress,W=await J.seed.load();if(!W)return 22;console.time("import: decoding file...");let Y=await V.bytes(),[X,K]=await d$(Y,Z,W);if(K!==0)return K;console.timeEnd("import: decoding file...");let G=0;while(G<X.length){let N=0,R=0,z=G;for(let w=G;w<X.length&&R<100&&N<102400;w++)N+=X[w].head.len,R++,z=w+1;let q=X.slice(G,z);console.time(`import: applying [${G}, ${z}]`);let F=await this.apply(q,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${G}, ${z}]`);for(let w=0;w<q.length;w++){let U=F[w];if(U!==0&&U!==15)console.warn(`failed to import msg ${G+w}: ${_[U]}`)}if(Q)queueMicrotask(()=>Q(z,X.length,0));this.emitProgress({phase:"import",done:z,total:X.length}),G=z}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,Z=await $.seed.load();if(!Z)return I(22);let J=await $.messages.list();return r$("export",0,J,V,Z)}async export(V){let[$,Z]=await this.exportBytes();if(Z!==0)return Z;if(!$)return 12;let J=new Blob([$.slice()]);return QZ(J,V),0}async link(V,$=!0){if(await this.store.hosts.add(V),this.clientState.emit(),$){let Z=await this.store.hosts.get(V.label);if(Z)await this.connectToHost(Z)}}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,Z=!0)=>{let{clock:J,connections:Q,crypto:W,store:Y,transport:X}=this,K=Q.get(V.label);if(K){if(K.isConnected())return;try{K.closeListener()}catch{}Q.delete(V.label)}let G=await Y.seed.load();if(!G)return;console.info(`Connecting to ${V.handle} (${V.label})`);let N=new GV(G,W,V,J,X(V),(R)=>Y.hosts.set(V.label,R));if(await N.register(),$)await N.listen(async(R)=>{let z={conn:N,store:Y,enclave:G,host:V,crypto:W,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return MZ(R,z,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(Q.set(V.label,N),this.clientState.emit(),Z)this.scheduleSync()};async connect(V=!0,$=!0){let{connectToHost:Z,scheduleSync:J,store:Q}=this;if(!await Q.seed.load())return;await this.drainApplyQueue();let Y=await Q.hosts.list();for(let X of Y)await Z(X,V,!1);if($)J()}disconnect=async()=>{for(let V of this.connections.values())try{V.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var H0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function UV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function Z$(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function p(V,...$){if(!Z$(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function J$(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function FZ(V,$){p(V);let Z=$.outputLen;if(V.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function Q$(V){if(typeof V!=="boolean")throw Error(`boolean expected, not ${V}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var N0=(V)=>new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4));var LJ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!LJ)throw Error("Non little-endian hardware is not supported");function EJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function qV(V){if(typeof V==="string")V=EJ(V);else if(Z$(V))V=OV(V);else throw Error("Uint8Array expected, got "+typeof V);return V}function UZ(V,$){if($==null||typeof $!=="object")throw Error("options must be defined");return Object.assign(V,$)}function qZ(V,$){if(V.length!==$.length)return!1;let Z=0;for(let J=0;J<V.length;J++)Z|=V[J]^$[J];return Z===0}var OZ=(V,$)=>{function Z(J,...Q){if(p(J),V.nonceLength!==void 0){let N=Q[0];if(!N)throw Error("nonce / iv required");if(V.varSizeNonce)p(N);else p(N,V.nonceLength)}let W=V.tagLength;if(W&&Q[1]!==void 0)p(Q[1]);let Y=$(J,...Q),X=(N,R)=>{if(R!==void 0){if(N!==2)throw Error("cipher output not supported");p(R)}},K=!1;return{encrypt(N,R){if(K)throw Error("cannot encrypt() twice with same key + nonce");return K=!0,p(N),X(Y.encrypt.length,R),Y.encrypt(N,R)},decrypt(N,R){if(p(N),W&&N.length<W)throw Error("invalid ciphertext length: smaller than tagLength="+W);return X(Y.decrypt.length,R),Y.decrypt(N,R)}}}return Object.assign(Z,V),Z};function W$(V,$,Z=!0){if($===void 0)return new Uint8Array(V);if($.length!==V)throw Error("invalid output length, expected "+V+", got: "+$.length);if(Z&&!xJ($))throw Error("invalid output, must be aligned");return $}function xJ(V){return V.byteOffset%4===0}function OV(V){return Uint8Array.from(V)}function X0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function PV(V=32){if(H0&&typeof H0.getRandomValues==="function")return H0.getRandomValues(new Uint8Array(V));if(H0&&typeof H0.randomBytes==="function")return H0.randomBytes(V);throw Error("crypto.getRandomValues must be defined")}var HZ=(V)=>Uint8Array.from(V.split("").map(($)=>$.charCodeAt(0))),SJ=HZ("expand 16-byte k"),kJ=HZ("expand 32-byte k"),mJ=N0(SJ),fJ=N0(kJ);function T(V,$){return V<<$|V>>>32-$}function Y$(V){return V.byteOffset%4===0}var HV=64,BJ=16,CZ=4294967295,PZ=new Uint32Array;function gJ(V,$,Z,J,Q,W,Y,X){let K=Q.length,G=new Uint8Array(HV),N=N0(G),R=Y$(Q)&&Y$(W),z=R?N0(Q):PZ,q=R?N0(W):PZ;for(let F=0;F<K;Y++){if(V($,Z,J,N,Y,X),Y>=CZ)throw Error("arx: counter overflow");let w=Math.min(HV,K-F);if(R&&w===HV){let U=F/4;if(F%4!==0)throw Error("arx: invalid block position");for(let P=0,H;P<BJ;P++)H=U+P,q[H]=z[H]^N[P];F+=HV;continue}for(let U=0,P;U<w;U++)P=F+U,W[P]=Q[P]^G[U];F+=w}}function TZ(V,$){let{allowShortKeys:Z,extendNonceFn:J,counterLength:Q,counterRight:W,rounds:Y}=UZ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},$);if(typeof V!=="function")throw Error("core must be a function");return UV(Q),UV(Y),Q$(W),Q$(Z),(X,K,G,N,R=0)=>{p(X),p(K),p(G);let z=G.length;if(N===void 0)N=new Uint8Array(z);if(p(N),UV(R),R<0||R>=CZ)throw Error("arx: counter overflow");if(N.length<z)throw Error(`arx: output (${N.length}) is shorter than data (${z})`);let q=[],F=X.length,w,U;if(F===32)q.push(w=OV(X)),U=fJ;else if(F===16&&Z)w=new Uint8Array(32),w.set(X),w.set(X,16),U=mJ,q.push(w);else throw Error(`arx: invalid 32-byte key, got length=${F}`);if(!Y$(K))q.push(K=OV(K));let P=N0(w);if(J){if(K.length!==24)throw Error("arx: extended nonce must be 24 bytes");J(U,P,N0(K.subarray(0,16)),P),K=K.subarray(16)}let H=16-Q;if(H!==K.length)throw Error(`arx: nonce must be ${H} or 16 bytes`);if(H!==12){let O=new Uint8Array(12);O.set(K,W?0:12-K.length),K=O,q.push(K)}let A=N0(K);return gJ(V,U,P,A,G,N,R,Y),X0(...q),N}}var r=(V,$)=>V[$++]&255|(V[$++]&255)<<8;class AZ{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=qV(V),p(V,32);let $=r(V,0),Z=r(V,2),J=r(V,4),Q=r(V,6),W=r(V,8),Y=r(V,10),X=r(V,12),K=r(V,14);this.r[0]=$&8191,this.r[1]=($>>>13|Z<<3)&8191,this.r[2]=(Z>>>10|J<<6)&7939,this.r[3]=(J>>>7|Q<<9)&8191,this.r[4]=(Q>>>4|W<<12)&255,this.r[5]=W>>>1&8190,this.r[6]=(W>>>14|Y<<2)&8191,this.r[7]=(Y>>>11|X<<5)&8065,this.r[8]=(X>>>8|K<<8)&8191,this.r[9]=K>>>5&127;for(let G=0;G<8;G++)this.pad[G]=r(V,16+2*G)}process(V,$,Z=!1){let J=Z?0:2048,{h:Q,r:W}=this,Y=W[0],X=W[1],K=W[2],G=W[3],N=W[4],R=W[5],z=W[6],q=W[7],F=W[8],w=W[9],U=r(V,$+0),P=r(V,$+2),H=r(V,$+4),A=r(V,$+6),O=r(V,$+8),D=r(V,$+10),L=r(V,$+12),k=r(V,$+14),S=Q[0]+(U&8191),E=Q[1]+((U>>>13|P<<3)&8191),B=Q[2]+((P>>>10|H<<6)&8191),C=Q[3]+((H>>>7|A<<9)&8191),g=Q[4]+((A>>>4|O<<12)&8191),i=Q[5]+(O>>>1&8191),y=Q[6]+((O>>>14|D<<2)&8191),l=Q[7]+((D>>>11|L<<5)&8191),n=Q[8]+((L>>>8|k<<8)&8191),h=Q[9]+(k>>>5|J),j=0,d=j+S*Y+E*(5*w)+B*(5*F)+C*(5*q)+g*(5*z);j=d>>>13,d&=8191,d+=i*(5*R)+y*(5*N)+l*(5*G)+n*(5*K)+h*(5*X),j+=d>>>13,d&=8191;let o=j+S*X+E*Y+B*(5*w)+C*(5*F)+g*(5*q);j=o>>>13,o&=8191,o+=i*(5*z)+y*(5*R)+l*(5*N)+n*(5*G)+h*(5*K),j+=o>>>13,o&=8191;let e=j+S*K+E*X+B*Y+C*(5*w)+g*(5*F);j=e>>>13,e&=8191,e+=i*(5*q)+y*(5*z)+l*(5*R)+n*(5*N)+h*(5*G),j+=e>>>13,e&=8191;let v=j+S*G+E*K+B*X+C*Y+g*(5*w);j=v>>>13,v&=8191,v+=i*(5*F)+y*(5*q)+l*(5*z)+n*(5*R)+h*(5*N),j+=v>>>13,v&=8191;let G0=j+S*N+E*G+B*K+C*X+g*Y;j=G0>>>13,G0&=8191,G0+=i*(5*w)+y*(5*F)+l*(5*q)+n*(5*z)+h*(5*R),j+=G0>>>13,G0&=8191;let A0=j+S*R+E*N+B*G+C*K+g*X;j=A0>>>13,A0&=8191,A0+=i*Y+y*(5*w)+l*(5*F)+n*(5*q)+h*(5*z),j+=A0>>>13,A0&=8191;let D0=j+S*z+E*R+B*N+C*G+g*K;j=D0>>>13,D0&=8191,D0+=i*X+y*Y+l*(5*w)+n*(5*F)+h*(5*q),j+=D0>>>13,D0&=8191;let _0=j+S*q+E*z+B*R+C*N+g*G;j=_0>>>13,_0&=8191,_0+=i*K+y*X+l*Y+n*(5*w)+h*(5*F),j+=_0>>>13,_0&=8191;let j0=j+S*F+E*q+B*z+C*R+g*N;j=j0>>>13,j0&=8191,j0+=i*G+y*K+l*X+n*Y+h*(5*w),j+=j0>>>13,j0&=8191;let L0=j+S*w+E*F+B*q+C*z+g*R;j=L0>>>13,L0&=8191,L0+=i*N+y*G+l*K+n*X+h*Y,j+=L0>>>13,L0&=8191,j=(j<<2)+j|0,j=j+d|0,d=j&8191,j=j>>>13,o+=j,Q[0]=d,Q[1]=o,Q[2]=e,Q[3]=v,Q[4]=G0,Q[5]=A0,Q[6]=D0,Q[7]=_0,Q[8]=j0,Q[9]=L0}finalize(){let{h:V,pad:$}=this,Z=new Uint16Array(10),J=V[1]>>>13;V[1]&=8191;for(let Y=2;Y<10;Y++)V[Y]+=J,J=V[Y]>>>13,V[Y]&=8191;V[0]+=J*5,J=V[0]>>>13,V[0]&=8191,V[1]+=J,J=V[1]>>>13,V[1]&=8191,V[2]+=J,Z[0]=V[0]+5,J=Z[0]>>>13,Z[0]&=8191;for(let Y=1;Y<10;Y++)Z[Y]=V[Y]+J,J=Z[Y]>>>13,Z[Y]&=8191;Z[9]-=8192;let Q=(J^1)-1;for(let Y=0;Y<10;Y++)Z[Y]&=Q;Q=~Q;for(let Y=0;Y<10;Y++)V[Y]=V[Y]&Q|Z[Y];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 W=V[0]+$[0];V[0]=W&65535;for(let Y=1;Y<8;Y++)W=(V[Y]+$[Y]|0)+(W>>>16)|0,V[Y]=W&65535;X0(Z)}update(V){J$(this);let{buffer:$,blockLen:Z}=this;V=qV(V);let J=V.length;for(let Q=0;Q<J;){let W=Math.min(Z-this.pos,J-Q);if(W===Z){for(;Z<=J-Q;Q+=Z)this.process(V,Q);continue}if($.set(V.subarray(Q,Q+W),this.pos),this.pos+=W,Q+=W,this.pos===Z)this.process($,0,!1),this.pos=0}return this}destroy(){X0(this.h,this.r,this.buffer,this.pad)}digestInto(V){J$(this),FZ(V,this),this.finished=!0;let{buffer:$,h:Z}=this,{pos:J}=this;if(J){$[J++]=1;for(;J<16;J++)$[J]=0;this.process($,0,!0)}this.finalize();let Q=0;for(let W=0;W<8;W++)V[Q++]=Z[W]>>>0,V[Q++]=Z[W]>>>8;return V}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Z=V.slice(0,$);return this.destroy(),Z}}function vJ(V){let $=(J,Q)=>V(Q).update(qV(J)).digest(),Z=V(new Uint8Array(32));return $.outputLen=Z.outputLen,$.blockLen=Z.blockLen,$.create=(J)=>V(J),$}var X$=vJ((V)=>new AZ(V));function iJ(V,$,Z,J,Q,W=20){let Y=V[0],X=$[0],K=$[1],G=$[2],N=$[3],R=V[1],z=Z[0],q=Z[1],F=Q,w=0,U=V[2],P=$[4],H=$[5],A=$[6],O=$[7],D=V[3],L=Y,k=X,S=K,E=G,B=N,C=R,g=z,i=q,y=F,l=w,n=U,h=P,j=H,d=A,o=O,e=D;for(let G0=0;G0<W;G0+=2)B^=T(L+j|0,7),y^=T(B+L|0,9),j^=T(y+B|0,13),L^=T(j+y|0,18),l^=T(C+k|0,7),d^=T(l+C|0,9),k^=T(d+l|0,13),C^=T(k+d|0,18),o^=T(n+g|0,7),S^=T(o+n|0,9),g^=T(S+o|0,13),n^=T(g+S|0,18),E^=T(e+h|0,7),i^=T(E+e|0,9),h^=T(i+E|0,13),e^=T(h+i|0,18),k^=T(L+E|0,7),S^=T(k+L|0,9),E^=T(S+k|0,13),L^=T(E+S|0,18),g^=T(C+B|0,7),i^=T(g+C|0,9),B^=T(i+g|0,13),C^=T(B+i|0,18),h^=T(n+l|0,7),y^=T(h+n|0,9),l^=T(y+h|0,13),n^=T(l+y|0,18),j^=T(e+o|0,7),d^=T(j+e|0,9),o^=T(d+j|0,13),e^=T(o+d|0,18);let v=0;J[v++]=Y+L|0,J[v++]=X+k|0,J[v++]=K+S|0,J[v++]=G+E|0,J[v++]=N+B|0,J[v++]=R+C|0,J[v++]=z+g|0,J[v++]=q+i|0,J[v++]=F+y|0,J[v++]=w+l|0,J[v++]=U+n|0,J[v++]=P+h|0,J[v++]=H+j|0,J[v++]=A+d|0,J[v++]=O+o|0,J[v++]=D+e|0}function bJ(V,$,Z,J){let Q=V[0],W=$[0],Y=$[1],X=$[2],K=$[3],G=V[1],N=Z[0],R=Z[1],z=Z[2],q=Z[3],F=V[2],w=$[4],U=$[5],P=$[6],H=$[7],A=V[3];for(let D=0;D<20;D+=2)K^=T(Q+U|0,7),z^=T(K+Q|0,9),U^=T(z+K|0,13),Q^=T(U+z|0,18),q^=T(G+W|0,7),P^=T(q+G|0,9),W^=T(P+q|0,13),G^=T(W+P|0,18),H^=T(F+N|0,7),Y^=T(H+F|0,9),N^=T(Y+H|0,13),F^=T(N+Y|0,18),X^=T(A+w|0,7),R^=T(X+A|0,9),w^=T(R+X|0,13),A^=T(w+R|0,18),W^=T(Q+X|0,7),Y^=T(W+Q|0,9),X^=T(Y+W|0,13),Q^=T(X+Y|0,18),N^=T(G+K|0,7),R^=T(N+G|0,9),K^=T(R+N|0,13),G^=T(K+R|0,18),w^=T(F+q|0,7),z^=T(w+F|0,9),q^=T(z+w|0,13),F^=T(q+z|0,18),U^=T(A+H|0,7),P^=T(U+A|0,9),H^=T(P+U|0,13),A^=T(H+P|0,18);let O=0;J[O++]=Q,J[O++]=G,J[O++]=F,J[O++]=A,J[O++]=N,J[O++]=R,J[O++]=z,J[O++]=q}var K$=TZ(iJ,{counterRight:!0,extendNonceFn:bJ}),G$=OZ({blockSize:64,nonceLength:24,tagLength:16},(V,$)=>{return{encrypt(Z,J){J=W$(Z.length+32,J,!1);let Q=J.subarray(0,32),W=J.subarray(32);J.set(Z,32),X0(Q),K$(V,$,J,J);let Y=X$(W,Q);return J.set(Y,16),X0(J.subarray(0,16),Y),J.subarray(16)},decrypt(Z,J){p(Z),J=W$(Z.length+32,J,!1);let Q=J.subarray(0,32),W=J.subarray(32,48),Y=J.subarray(48);J.set(Z,32),X0(Q);let X=K$(V,$,Q,Q),K=X$(Y,X);if(!qZ(W,K))throw Error("invalid tag");return K$(V,$,J.subarray(16),J.subarray(16)),X0(Q,W,K),Y}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function uJ(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function o0(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function C0(V,...$){if(!uJ(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function a0(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function CV(V,$){C0(V);let Z=$.outputLen;if(V.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function DZ(V){return new Uint8Array(V.buffer,V.byteOffset,V.byteLength)}function g0(V){return new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4))}function v0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function s0(V,$){return V<<32-$|V>>>$}var _Z=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function jZ(V){return V<<24&4278190080|V<<8&16711680|V>>>8&65280|V>>>24&255}var LZ=_Z?(V)=>V:(V)=>jZ(V);function yJ(V){for(let $=0;$<V.length;$++)V[$]=jZ(V[$]);return V}var s=_Z?(V)=>V:yJ;function lJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function i0(V){if(typeof V==="string")V=lJ(V);return C0(V),V}class N${}function EZ(V){let $=(J,Q)=>V(Q).update(i0(J)).digest(),Z=V({});return $.outputLen=Z.outputLen,$.blockLen=Z.blockLen,$.create=(J)=>V(J),$}var xZ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var TV=BigInt(4294967295),SZ=BigInt(32);function I$(V,$=!1){if($)return{h:Number(V&TV),l:Number(V>>SZ&TV)};return{h:Number(V>>SZ&TV)|0,l:Number(V&TV)|0}}function I0(V,$,Z,J,Q){return V=V+$+Q|0,J=s0(J^V,16),Z=Z+J|0,$=s0($^Z,12),{a:V,b:$,c:Z,d:J}}function R0(V,$,Z,J,Q){return V=V+$+Q|0,J=s0(J^V,8),Z=Z+J|0,$=s0($^Z,7),{a:V,b:$,c:Z,d:J}}class R$ extends N${constructor(V,$){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,o0(V),o0($),this.blockLen=V,this.outputLen=$,this.buffer=new Uint8Array(V),this.buffer32=g0(this.buffer)}update(V){a0(this),V=i0(V),C0(V);let{blockLen:$,buffer:Z,buffer32:J}=this,Q=V.length,W=V.byteOffset,Y=V.buffer;for(let X=0;X<Q;){if(this.pos===$)s(J),this.compress(J,0,!1),s(J),this.pos=0;let K=Math.min($-this.pos,Q-X),G=W+X;if(K===$&&!(G%4)&&X+K<Q){let N=new Uint32Array(Y,G,Math.floor((Q-X)/4));s(N);for(let R=0;X+$<Q;R+=J.length,X+=$)this.length+=$,this.compress(N,R,!1);s(N);continue}Z.set(V.subarray(X,X+K),this.pos),this.pos+=K,this.length+=K,X+=K}return this}digestInto(V){a0(this),CV(V,this);let{pos:$,buffer32:Z}=this;this.finished=!0,v0(this.buffer.subarray($)),s(Z),this.compress(Z,0,!0),s(Z);let J=g0(V);this.get().forEach((Q,W)=>J[W]=LZ(Q))}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Z=V.slice(0,$);return this.destroy(),Z}_cloneInto(V){let{buffer:$,length:Z,finished:J,destroyed:Q,outputLen:W,pos:Y}=this;return V||(V=new this.constructor({dkLen:W})),V.set(...this.get()),V.buffer.set($),V.destroyed=Q,V.finished=J,V.length=Z,V.pos=Y,V.outputLen=W,V}clone(){return this._cloneInto()}}function z$(V,$,Z,J,Q,W,Y,X,K,G,N,R,z,q,F,w,U,P,H,A){let O=0;for(let D=0;D<J;D++)({a:Q,b:K,c:z,d:U}=I0(Q,K,z,U,Z[$+V[O++]])),{a:Q,b:K,c:z,d:U}=R0(Q,K,z,U,Z[$+V[O++]]),{a:W,b:G,c:q,d:P}=I0(W,G,q,P,Z[$+V[O++]]),{a:W,b:G,c:q,d:P}=R0(W,G,q,P,Z[$+V[O++]]),{a:Y,b:N,c:F,d:H}=I0(Y,N,F,H,Z[$+V[O++]]),{a:Y,b:N,c:F,d:H}=R0(Y,N,F,H,Z[$+V[O++]]),{a:X,b:R,c:w,d:A}=I0(X,R,w,A,Z[$+V[O++]]),{a:X,b:R,c:w,d:A}=R0(X,R,w,A,Z[$+V[O++]]),{a:Q,b:G,c:F,d:A}=I0(Q,G,F,A,Z[$+V[O++]]),{a:Q,b:G,c:F,d:A}=R0(Q,G,F,A,Z[$+V[O++]]),{a:W,b:N,c:w,d:U}=I0(W,N,w,U,Z[$+V[O++]]),{a:W,b:N,c:w,d:U}=R0(W,N,w,U,Z[$+V[O++]]),{a:Y,b:R,c:z,d:P}=I0(Y,R,z,P,Z[$+V[O++]]),{a:Y,b:R,c:z,d:P}=R0(Y,R,z,P,Z[$+V[O++]]),{a:X,b:K,c:q,d:H}=I0(X,K,q,H,Z[$+V[O++]]),{a:X,b:K,c:q,d:H}=R0(X,K,q,H,Z[$+V[O++]]);return{v0:Q,v1:W,v2:Y,v3:X,v4:K,v5:G,v6:N,v7:R,v8:z,v9:q,v10:F,v11:w,v12:U,v13:P,v14:H,v15:A}}var K0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},z0=xZ.slice(),kZ=(()=>{let V=Array.from({length:16},(J,Q)=>Q),$=(J)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((Q)=>J[Q]),Z=[];for(let J=0,Q=V;J<7;J++,Q=$(Q))Z.push(...Q);return Uint8Array.from(Z)})();class w$ extends R${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:Z,context:J}=V,Q=J!==void 0;if(Z!==void 0){if(Q)throw Error('Only "key" or "context" can be specified at same time');let W=i0(Z).slice();C0(W,32),this.IV=g0(W),s(this.IV),this.flags=$|K0.KEYED_HASH}else if(Q){let W=i0(J),Y=new w$({dkLen:32},K0.DERIVE_KEY_CONTEXT).update(W).digest();this.IV=g0(Y),s(this.IV),this.flags=$|K0.DERIVE_KEY_MATERIAL}else this.IV=z0.slice(),this.flags=$;this.state=this.IV.slice(),this.bufferOut=DZ(this.bufferOut32)}get(){return[]}set(){}b2Compress(V,$,Z,J=0){let{state:Q,pos:W}=this,{h:Y,l:X}=I$(BigInt(V),!0),{v0:K,v1:G,v2:N,v3:R,v4:z,v5:q,v6:F,v7:w,v8:U,v9:P,v10:H,v11:A,v12:O,v13:D,v14:L,v15:k}=z$(kZ,J,Z,7,Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7],z0[0],z0[1],z0[2],z0[3],Y,X,W,$);Q[0]=K^U,Q[1]=G^P,Q[2]=N^H,Q[3]=R^A,Q[4]=z^O,Q[5]=q^D,Q[6]=F^L,Q[7]=w^k}compress(V,$=0,Z=!1){let J=this.flags;if(!this.chunkPos)J|=K0.CHUNK_START;if(this.chunkPos===15||Z)J|=K0.CHUNK_END;if(!Z)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,J,V,$),this.chunkPos+=1,this.chunkPos===16||Z){let Q=this.state;this.state=this.IV.slice();for(let W,Y=this.chunksDone+1;Z||!(Y&1);Y>>=1){if(!(W=this.stack.pop()))break;this.buffer32.set(W,0),this.buffer32.set(Q,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|K0.PARENT,this.buffer32,0),Q=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(Q)}this.pos=0}_cloneInto(V){V=super._cloneInto(V);let{IV:$,flags:Z,state:J,chunkPos:Q,posOut:W,chunkOut:Y,stack:X,chunksDone:K}=this;return V.state.set(J.slice()),V.stack=X.map((G)=>Uint32Array.from(G)),V.IV.set($),V.flags=Z,V.chunkPos=Q,V.chunksDone=K,V.posOut=W,V.chunkOut=Y,V.enableXOF=this.enableXOF,V.bufferOut32.set(this.bufferOut32),V}destroy(){this.destroyed=!0,v0(this.state,this.buffer32,this.IV,this.bufferOut32),v0(...this.stack)}b2CompressOut(){let{state:V,pos:$,flags:Z,buffer32:J,bufferOut32:Q}=this,{h:W,l:Y}=I$(BigInt(this.chunkOut++));s(J);let{v0:X,v1:K,v2:G,v3:N,v4:R,v5:z,v6:q,v7:F,v8:w,v9:U,v10:P,v11:H,v12:A,v13:O,v14:D,v15:L}=z$(kZ,0,J,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],z0[0],z0[1],z0[2],z0[3],Y,W,$,Z);Q[0]=X^w,Q[1]=K^U,Q[2]=G^P,Q[3]=N^H,Q[4]=R^A,Q[5]=z^O,Q[6]=q^D,Q[7]=F^L,Q[8]=V[0]^w,Q[9]=V[1]^U,Q[10]=V[2]^P,Q[11]=V[3]^H,Q[12]=V[4]^A,Q[13]=V[5]^O,Q[14]=V[6]^D,Q[15]=V[7]^L,s(J),s(Q),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,v0(this.buffer.subarray(this.pos));let V=this.flags|K0.ROOT;if(this.stack.length)V|=K0.PARENT,s(this.buffer32),this.compress(this.buffer32,0,!0),s(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else V|=(!this.chunkPos?K0.CHUNK_START:0)|K0.CHUNK_END;this.flags=V,this.b2CompressOut()}writeInto(V){a0(this,!1),C0(V),this.finish();let{blockLen:$,bufferOut:Z}=this;for(let J=0,Q=V.length;J<Q;){if(this.posOut>=$)this.b2CompressOut();let W=Math.min($-this.posOut,Q-J);V.set(Z.subarray(this.posOut,this.posOut+W),J),this.posOut+=W,J+=W}return V}xofInto(V){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(V)}xof(V){return o0(V),this.xofInto(new Uint8Array(V))}digestInto(V){if(CV(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 mZ=EZ((V)=>new w$(V));var M$=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function fZ(V){let $=new Uint8Array(M$.length+32);return $.set(M$),$.set(V.subarray(0,32),M$.length),$}function BZ(V){return typeof V==="string"?new TextEncoder().encode(V):V}function b0(V){let $=new ArrayBuffer(V.byteLength);return new Uint8Array($).set(V),$}class F${verifyKeys=new Map;signKeys=new Map;async genRandomBytes(V){return PV(V)}async gen256BitSecureRandomSeed(){return PV(32)}async encryptXSalsa20Poly1305Combined(V,$){let Z=PV(24),Q=G$($,Z).encrypt(V);return new Uint8Array([...Z,...Q])}async decryptXSalsa20Poly1305Combined(V,$){let Z=V.slice(0,24),J=V.slice(24);return G$($,Z).decrypt(J)}async deriveEd25519KeyPair(V){let $=V,Z=fZ($),J=await globalThis.crypto.subtle.importKey("pkcs8",b0(Z),{name:"Ed25519"},!0,["sign"]),Q=await globalThis.crypto.subtle.exportKey("jwk",J);if(typeof Q.x!=="string")throw Error("Ed25519 JWK missing x");let W=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:Q.x},{name:"Ed25519"},!0,["verify"]),Y=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",W)),X=new Uint8Array(64);return X.set($,0),X.set(Y,32),this.signKeys.set(Y0($),J),this.verifyKeys.set(Y0(Y),W),{keyType:"ed25519",privateKey:X,publicKey:Y}}async importSignKey(V){let $=V.subarray(0,32),Z=Y0($),J=this.signKeys.get(Z);if(J)return J;let Q=fZ($),W=await globalThis.crypto.subtle.importKey("pkcs8",b0(Q),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Z,W),W}async importVerifyKey(V){let $=Y0(V),Z=this.verifyKeys.get($);if(Z)return Z;let J=await globalThis.crypto.subtle.importKey("raw",b0(V),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set($,J),J}async signEd25519(V,$){let Z=BZ(V),J=await this.importSignKey($),Q=await globalThis.crypto.subtle.sign({name:"Ed25519"},J,b0(Z));return new Uint8Array(Q)}async checkSigEd25519(V,$,Z){let J=BZ($);try{let Q=await this.importVerifyKey(Z);return await globalThis.crypto.subtle.verify({name:"Ed25519"},Q,b0(V),b0(J))}catch{return!1}}async blake3(V){return mZ(V)}}var nJ=new F$,u0=nJ;class U${db;constructor(V){this.db=V}async enq(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(J0,"readwrite"),J=Z.objectStore(J0);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=`${Y.host}:${Y.seq}`;J.put(Y,X)}})}async deq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(J0,"readwrite"),Q=J.objectStore(J0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let K=`${V}:${X}`;Q.delete(K)}})}async list(){let $=this.db.transaction(J0,"readonly").objectStore(J0);return new Promise((Z,J)=>{let Q=$.getAll();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async count(){let $=this.db.transaction(J0,"readonly").objectStore(J0);return new Promise((Z,J)=>{let Q=$.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(J0,"readwrite"),$=V.objectStore(J0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}function gZ(V){return{label:V.label,handle:new URL(V.handle),idx:V.idx,lastSeq:V.lastSeq||0,clockOffset:V.clockOffset,subscription:V.subscription}}class q${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},Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error),J.put($)})}async touch(V,$){let Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);let Y=J.get(V);Y.onsuccess=()=>{let X=Y.result;if(!X)return;let K=X.lastSeq||0;if($<=K)return;J.put({...X,lastSeq:$})}})}async get(V){let Z=this.db.transaction(t,"readonly").objectStore(t);return new Promise((J,Q)=>{let W=Z.get(V);W.onsuccess=()=>{let Y=W.result;if(!Y)J(void 0);else J(gZ(Y))},W.onerror=()=>Q(W.error)})}async set(V,$){let Z=await this.get(V);if(!Z)return 13;try{return await this.put({...Z,...$}),0}catch{return 18}}async del(V){let $=this.db.transaction(t,"readwrite"),Z=$.objectStore(t);return new Promise((J,Q)=>{$.oncomplete=()=>J(),$.onerror=()=>Q($.error),Z.delete(V)})}async list(){let $=this.db.transaction(t,"readonly").objectStore(t);return new Promise((Z,J)=>{let Q=$.getAll();Q.onsuccess=()=>{let W=Q.result;Z(W.map(gZ))},Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(t,"readwrite"),$=V.objectStore(t);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}class O${crypto;db;constructor(V,$){this.crypto=$;this.db=V}async add(V){let $=this.db.transaction(b,"readwrite"),Z=$.objectStore(b);return new Promise((J)=>{if(V.length===0){J([]);return}let Q=Array(V.length).fill(0);$.oncomplete=()=>J(Q),$.onerror=()=>{for(let W=0;W<Q.length;W++)Q[W]=18;J(Q)};for(let W=0;W<V.length;W++){let{key:Y,data:X}=V[W],K=x(Y),G=Z.put(X,K);G.onerror=(N)=>{N.preventDefault(),Q[W]=18}}})}async del(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(b,"readwrite"),J=Z.objectStore(b);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=x(Y);J.delete(X)}})}async get(V){let Z=this.db.transaction(b,"readonly").objectStore(b);return new Promise((J,Q)=>{let W=x(V),Y=Z.get(W);Y.onsuccess=async()=>{let X=Y.result;if(X)J(await FV(V,X,this.crypto));else J(void 0)},Y.onerror=()=>Q(Y.error)})}async has(V){return await this.get(V)!==void 0}async list(V){let Z=this.db.transaction(b,"readonly").objectStore(b);return new Promise((J,Q)=>{let W=[],Y=V===void 0?Z.openCursor():Z.index(AV).openCursor(IDBKeyRange.only(V));Y.onsuccess=(X)=>{let K=X.target.result;if(K){let G=V===void 0?K.key:K.primaryKey,N=K.value;W.push({hash:q0(G),data:N}),K.continue()}else Promise.all(W.map(({hash:G,data:N})=>FV(G,N,this.crypto))).then(J).catch(Q)},Y.onerror=()=>Q(Y.error)})}async last(V){let Z=this.db.transaction(b,"readonly").objectStore(b);return new Promise((J,Q)=>{let W,Y=Z.openCursor();Y.onsuccess=async(X)=>{let K=X.target.result;if(K){let{key:G,value:N}=K;if($0(V,N.eid)){if(!W||(N.ctr??0)>(W.data.ctr??0)||(N.ctr??0)===(W.data.ctr??0)&&(N.off??0)>(W.data.off??0))W={key:G,data:N}}K.continue()}else if(W){let G=q0(W.key);J(await FV(G,W.data,this.crypto))}else J(void 0)},Y.onerror=()=>Q(Y.error)})}async markApplied(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(b,"readwrite"),J=Z.objectStore(b);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=x(Y),K=J.get(X);K.onsuccess=()=>{let G=K.result;if(!G)return;tV(G,MV),J.put(G,X)},K.onerror=(G)=>{G.preventDefault()}}})}async markFailed(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(b,"readwrite"),J=Z.objectStore(b);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let{key:Y,err:X}of $){let K=x(Y),G=J.get(K);G.onsuccess=()=>{let N=G.result;if(!N)return;tV(N,f0,X),J.put(N,K)},G.onerror=(N)=>{N.preventDefault()}}})}async wipe(){let V=this.db.transaction(b,"readwrite"),$=V.objectStore(b);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}class DV{seed;crypto;constructor(V,$){this.seed=V,this.crypto=$}async deriveFromKDM(V){let $=c0(this.seed,V);return await this.crypto.blake3($)}async derive(V,$=0){let Z=new TextEncoder().encode(V),J=new Uint8Array(8);new DataView(J.buffer).setBigUint64(0,BigInt($),!1);let Q=c0(Z,J);return await this.deriveFromKDM(Q)}}class P${enclave;db;constructor(V){this.db=V}async save(V){let $=Y0(V),Z=this.db.transaction(w0,"readwrite"),J=Z.objectStore(w0);return new Promise((Q,W)=>{Z.oncomplete=()=>{this.enclave=new DV(V,u0),Q(this.enclave)},Z.onerror=()=>W(Z.error),J.put($,"seed")})}async load(){if(this.enclave)return this.enclave;let $=this.db.transaction(w0,"readonly").objectStore(w0);return new Promise((Z,J)=>{let Q=$.get("seed");Q.onsuccess=()=>{let W=Q.result;if(!W)Z(void 0);else{let Y=WV(W);this.enclave=new DV(Y,u0),Z(this.enclave)}},Q.onerror=()=>J(Q.error)})}async wipe(){this.enclave=void 0;let V=this.db.transaction(w0,"readwrite"),$=V.objectStore(w0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.delete("seed")})}}class H${db;constructor(V){this.db=V}async enq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(Q0,"readwrite"),Q=J.objectStore(Q0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let K=Y0(X);Q.put({host:V,hash:K})}})}async deq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(Q0,"readwrite"),Q=J.objectStore(Q0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let K=Y0(X);Q.delete([V,K])}})}async list(V){let Z=this.db.transaction(Q0,"readonly").objectStore(Q0);return new Promise((J,Q)=>{let W=Z.getAll();W.onsuccess=()=>{let X=W.result.filter((K)=>K.host===V).map((K)=>K.hash);J(X.map((K)=>WV(K)))},W.onerror=()=>Q(W.error)})}async count(){let $=this.db.transaction(Q0,"readonly").objectStore(Q0);return new Promise((Z,J)=>{let Q=$.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(Q0,"readwrite"),$=V.objectStore(Q0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}var w0="seedMeta",t="hosts",Q0="uploadQueue",J0="downloadQueue",b="messages",AV="apld",hJ=3;class vZ{seed;hosts;uploads;downloads;messages;db;constructor(V,$){this.db=V,this.seed=new P$(V),this.hosts=new q$(V),this.uploads=new H$(V),this.downloads=new U$(V),this.messages=new O$(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 pJ(){return new Promise((V,$)=>{let Z=indexedDB.open("diplomatic-store-db",hJ);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!J.objectStoreNames.contains(w0))J.createObjectStore(w0);if(!J.objectStoreNames.contains(t))J.createObjectStore(t,{keyPath:"label"});if(!J.objectStoreNames.contains(Q0))J.createObjectStore(Q0,{keyPath:["host","hash"]});if(!J.objectStoreNames.contains(J0))J.createObjectStore(J0);let W;if(!J.objectStoreNames.contains(b))W=J.createObjectStore(b);else{if(!Q)throw Error("missing upgrade transaction for messages store");W=Q.objectStore(b)}if(!W.indexNames.contains(AV))W.createIndex(AV,"apld",{unique:!1})},Z.onsuccess=()=>V(Z.result),Z.onerror=()=>$(Z.error)})}async function iZ(V){let $=await pJ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new vZ($,V)}class C${client;post;whenReady;resolveReady;rejectReady;constructor(V){this.post=V,this.whenReady=new Promise(($,Z)=>{this.resolveReady=$,this.rejectReady=Z})}async init(){try{let V=await iZ(u0),$=await e$({cache:!1}),Z=new IV($.apply,()=>$.clear(),(W)=>{if(W.length<1)return;this.post({kind:"dirty",eids:W.map((Y)=>Y.slice())})}),J=Z.clear;Z.clear=async()=>{let W=await J();if(W===0)this.post({kind:"wiped"});return W};let Q=new $$(new fV,Z,V,c$,u0);this.client=Q,Q.clientState.listen(()=>{this.emitClientState()}),Q.xferState.listen(()=>{this.emitXferState()}),await this.emitClientState(),await this.emitXferState(),this.post({kind:"ready"}),this.markReady()}catch(V){let $=V instanceof Error?V:Error(String(V));throw this.failReady($),$}}markReady(){let V=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V()}failReady(V){let $=this.rejectReady;if(this.resolveReady=void 0,this.rejectReady=void 0,$)$(V)}requireClient(){if(!this.client)throw Error("WorkerRuntime not initialized");return this.client}async emitClientState(){let V=this.client;if(!V)return;let $=await V.clientState.get();this.post({kind:"clientState",state:$})}async emitXferState(){let V=this.client;if(!V)return;let $=await V.xferState.get();this.post({kind:"xferState",state:$})}hostFromSerialized(V){return{handle:new URL(V.handle),label:V.label,idx:V.idx}}async handle(V){await this.whenReady;let $=this.requireClient();switch(V.op){case"ping":return"pong";case"setSeed":{await $.setSeed(cJ(V.seed));return}case"link":{await $.link(this.hostFromSerialized(V.host),V.connect??!0);return}case"unlink":{await $.unlink(V.label);return}case"connect":{await $.connect(V.listen??!0,V.sync??!0);return}case"disconnect":{await $.disconnect();return}case"sync":return await $.sync();case"wipe":{await $.wipe();return}case"import":{let Z=V.bytes.slice(),J=new Blob([Z]),Q=new File([J],"import.dip");return await $.import(Q)}case"export":{let[Z,J]=await $.exportBytes();if(J!==0)throw new y0(J);if(!Z)throw new y0(12);return Z}case"getClientState":return await $.clientState.get();case"getXferState":return await $.xferState.get();default:{let Z=V;throw Error("unknown worker command")}}}}class y0 extends Error{status;constructor(V){super(`WorkerStatusError: ${_[V]}`);this.status=V;this.name="WorkerStatusError"}}function T$(V,$){return{kind:"reply",id:V,ok:!0,result:$}}function A$(V,$){return{kind:"reply",id:V,ok:!1,status:$}}function cJ(V){if(V.length!==32)throw new y0(10);return V}var T0=globalThis,bZ=new C$((V,$)=>{if($&&$.length>0)T0.postMessage(V,$);else T0.postMessage(V)});T0.onmessage=(V)=>{let $=V.data;if(!L$($))return;rJ($)};async function rJ(V){try{let $=await bZ.handle(V);if(V.op==="export"&&$ instanceof Uint8Array){let Z=$.slice();T0.postMessage(T$(V.id,Z),[Z.buffer]);return}T0.postMessage(T$(V.id,$))}catch($){if($ instanceof y0){T0.postMessage(A$(V.id,$.status));return}console.error("worker command failed",$),T0.postMessage(A$(V.id,12))}}bZ.init().catch((V)=>{console.error("worker init failed",V)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@interncom/diplomatic",
3
- "version": "0.6.2",
3
+ "version": "0.6.3",
4
4
  "type": "module",
5
5
  "description": "Secure sync layer and CLI utilities for DIPLOMATIC",
6
6
  "files": [