@interncom/diplomatic 0.3.1 → 0.3.2

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 pQ($){let J=$.length,Q=0,I=0;while(I<J){let V=$.charCodeAt(I++);if((V&4294967168)===0){Q++;continue}else if((V&4294965248)===0)Q+=2;else{if(V>=55296&&V<=56319){if(I<J){let Z=$.charCodeAt(I);if((Z&64512)===56320)++I,V=((V&1023)<<10)+(Z&1023)+65536}}if((V&4294901760)===0)Q+=3;else Q+=4}}return Q}function PV($,J,Q){let I=$.length,V=Q,Z=0;while(Z<I){let X=$.charCodeAt(Z++);if((X&4294967168)===0){J[V++]=X;continue}else if((X&4294965248)===0)J[V++]=X>>6&31|192;else{if(X>=55296&&X<=56319){if(Z<I){let Y=$.charCodeAt(Z);if((Y&64512)===56320)++Z,X=((X&1023)<<10)+(Y&1023)+65536}}if((X&4294901760)===0)J[V++]=X>>12&15|224,J[V++]=X>>6&63|128;else J[V++]=X>>18&7|240,J[V++]=X>>12&63|128,J[V++]=X>>6&63|128}J[V++]=X&63|128}}var jV=new TextEncoder,kV=50;function SV($,J,Q){jV.encodeInto($,J.subarray(Q))}function cQ($,J,Q){if($.length>kV)SV($,J,Q);else PV($,J,Q)}var LV=4096;function NJ($,J,Q){let I=J,V=I+Q,Z=[],X="";while(I<V){let Y=$[I++];if((Y&128)===0)Z.push(Y);else if((Y&224)===192){let K=$[I++]&63;Z.push((Y&31)<<6|K)}else if((Y&240)===224){let K=$[I++]&63,W=$[I++]&63;Z.push((Y&31)<<12|K<<6|W)}else if((Y&248)===240){let K=$[I++]&63,W=$[I++]&63,G=$[I++]&63,N=(Y&7)<<18|K<<12|W<<6|G;if(N>65535)N-=65536,Z.push(N>>>10&1023|55296),N=56320|N&1023;Z.push(N)}else Z.push(Y);if(Z.length>=LV)X+=String.fromCharCode(...Z),Z.length=0}if(Z.length>0)X+=String.fromCharCode(...Z);return X}var _V=new TextDecoder,EV=200;function BV($,J,Q){let I=$.subarray(J,J+Q);return _V.decode(I)}function lQ($,J,Q){if(Q>EV)return BV($,J,Q);else return NJ($,J,Q)}class t0{type;data;constructor($,J){this.type=$,this.data=J}}class Y0 extends Error{constructor($){super($);let J=Object.create(Y0.prototype);Object.setPrototypeOf(this,J),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Y0.name})}}var e0=4294967295;function rQ($,J,Q){let I=Q/4294967296,V=Q;$.setUint32(J,I),$.setUint32(J+4,V)}function P$($,J,Q){let I=Math.floor(Q/4294967296),V=Q;$.setUint32(J,I),$.setUint32(J+4,V)}function j$($,J){let Q=$.getInt32(J),I=$.getUint32(J+4);return Q*4294967296+I}function nQ($,J){let Q=$.getUint32(J),I=$.getUint32(J+4);return Q*4294967296+I}var fV=-1,xV=4294967295,gV=17179869183;function mV({sec:$,nsec:J}){if($>=0&&J>=0&&$<=gV)if(J===0&&$<=xV){let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,$),Q}else{let Q=$/4294967296,I=$&4294967295,V=new Uint8Array(8),Z=new DataView(V.buffer);return Z.setUint32(0,J<<2|Q&3),Z.setUint32(4,I),V}else{let Q=new Uint8Array(12),I=new DataView(Q.buffer);return I.setUint32(0,J),P$(I,4,$),Q}}function vV($){let J=$.getTime(),Q=Math.floor(J/1000),I=(J-Q*1000)*1e6,V=Math.floor(I/1e9);return{sec:Q+V,nsec:I-V*1e9}}function yV($){if($ instanceof Date){let J=vV($);return mV(J)}else return null}function bV($){let J=new DataView($.buffer,$.byteOffset,$.byteLength);switch($.byteLength){case 4:{let Q=J.getUint32(0),I=0;return{sec:Q,nsec:0}}case 8:{let Q=J.getUint32(0),I=J.getUint32(4),V=(Q&3)*4294967296+I,Z=Q>>>2;return{sec:V,nsec:Z}}case 12:{let Q=j$(J,4),I=J.getUint32(0);return{sec:Q,nsec:I}}default:throw new Y0(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${$.length}`)}}function uV($){let J=bV($);return new Date(J.sec*1000+J.nsec/1e6)}var hQ={type:fV,encode:yV,decode:uV};class $${static defaultCodec=new $$;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(hQ)}register({type:$,encode:J,decode:Q}){if($>=0)this.encoders[$]=J,this.decoders[$]=Q;else{let I=-1-$;this.builtInEncoders[I]=J,this.builtInDecoders[I]=Q}}tryToEncode($,J){for(let Q=0;Q<this.builtInEncoders.length;Q++){let I=this.builtInEncoders[Q];if(I!=null){let V=I($,J);if(V!=null){let Z=-1-Q;return new t0(Z,V)}}}for(let Q=0;Q<this.encoders.length;Q++){let I=this.encoders[Q];if(I!=null){let V=I($,J);if(V!=null)return new t0(Q,V)}}if($ instanceof t0)return $;return null}decode($,J,Q){let I=J<0?this.builtInDecoders[-1-J]:this.decoders[J];if(I)return I($,J,Q);else return new t0(J,$)}}function iV($){return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer}function M$($){if($ instanceof Uint8Array)return $;else if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);else if(iV($))return new Uint8Array($);else return Uint8Array.from($)}var pV=100,cV=2048;class k${extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??$$.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.maxDepth=$?.maxDepth??pV,this.initialBufferSize=$?.initialBufferSize??cV,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 k$({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($,J){if(J>this.maxDepth)throw Error(`Too deep objects in depth ${J}`);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($,J)}ensureBufferSizeToWrite($){let J=this.pos+$;if(this.view.byteLength<J)this.resizeBuffer(J*2)}resizeBuffer($){let J=new ArrayBuffer($),Q=new Uint8Array(J),I=new DataView(J);Q.set(this.bytes),this.view=I,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=pQ($);this.ensureBufferSizeToWrite(5+Q),this.writeStringHeader(Q),cQ($,this.bytes,this.pos),this.pos+=Q}encodeObject($,J){let Q=this.extensionCodec.tryToEncode($,this.context);if(Q!=null)this.encodeExtension(Q);else if(Array.isArray($))this.encodeArray($,J);else if(ArrayBuffer.isView($))this.encodeBinary($);else if(typeof $==="object")this.encodeMap($,J);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply($)}`)}encodeBinary($){let J=$.byteLength;if(J<256)this.writeU8(196),this.writeU8(J);else if(J<65536)this.writeU8(197),this.writeU16(J);else if(J<4294967296)this.writeU8(198),this.writeU32(J);else throw Error(`Too large binary: ${J}`);let Q=M$($);this.writeU8a(Q)}encodeArray($,J){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 I of $)this.doEncode(I,J+1)}countWithoutUndefined($,J){let Q=0;for(let I of J)if($[I]!==void 0)Q++;return Q}encodeMap($,J){let Q=Object.keys($);if(this.sortKeys)Q.sort();let I=this.ignoreUndefined?this.countWithoutUndefined($,Q):Q.length;if(I<16)this.writeU8(128+I);else if(I<65536)this.writeU8(222),this.writeU16(I);else if(I<4294967296)this.writeU8(223),this.writeU32(I);else throw Error(`Too large map object: ${I}`);for(let V of Q){let Z=$[V];if(!(this.ignoreUndefined&&Z===void 0))this.encodeString(V),this.doEncode(Z,J+1)}}encodeExtension($){if(typeof $.data==="function"){let Q=$.data(this.pos+6),I=Q.length;if(I>=4294967296)throw Error(`Too large extension object: ${I}`);this.writeU8(201),this.writeU32(I),this.writeI8($.type),this.writeU8a(Q);return}let J=$.data.length;if(J===1)this.writeU8(212);else if(J===2)this.writeU8(213);else if(J===4)this.writeU8(214);else if(J===8)this.writeU8(215);else if(J===16)this.writeU8(216);else if(J<256)this.writeU8(199),this.writeU8(J);else if(J<65536)this.writeU8(200),this.writeU16(J);else if(J<4294967296)this.writeU8(201),this.writeU32(J);else throw Error(`Too large extension object: ${J}`);this.writeI8($.type),this.writeU8a($.data)}writeU8($){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,$),this.pos++}writeU8a($){let J=$.length;this.ensureBufferSizeToWrite(J),this.bytes.set($,this.pos),this.pos+=J}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),rQ(this.view,this.pos,$),this.pos+=8}writeI64($){this.ensureBufferSizeToWrite(8),P$(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 S$($,J){return new k$(J).encodeSharedRef($)}function L$($){return`${$<0?"-":""}0x${Math.abs($).toString(16).padStart(2,"0")}`}var lV=16,rV=16;class MJ{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor($=lV,J=rV){this.maxKeyLength=$,this.maxLengthPerKey=J,this.caches=[];for(let Q=0;Q<this.maxKeyLength;Q++)this.caches.push([])}canBeCached($){return $>0&&$<=this.maxKeyLength}find($,J,Q){let I=this.caches[Q-1];$:for(let V of I){let Z=V.bytes;for(let X=0;X<Q;X++)if(Z[X]!==$[J+X])continue $;return V.str}return null}store($,J){let Q=this.caches[$.length-1],I={bytes:$,str:J};if(Q.length>=this.maxLengthPerKey)Q[Math.random()*Q.length|0]=I;else Q.push(I)}decode($,J,Q){let I=this.find($,J,Q);if(I!=null)return this.hit++,I;this.miss++;let V=NJ($,J,Q),Z=Uint8Array.prototype.slice.call($,J,J+Q);return this.store(Z,V),V}}var qJ="array",U$="map_key",oQ="map_value",nV=($)=>{if(typeof $==="string"||typeof $==="number")return $;throw new Y0("The type of key must be string or number but "+typeof $)};class aQ{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState($){let J=this.getUninitializedStateFromPool();J.type=qJ,J.position=0,J.size=$,J.array=Array($)}pushMapState($){let J=this.getUninitializedStateFromPool();J.type=U$,J.readCount=0,J.size=$,J.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===qJ){let Q=$;Q.size=0,Q.array=void 0,Q.position=0,Q.type=void 0}if($.type===U$||$.type===oQ){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 q$=-1,UJ=new DataView(new ArrayBuffer(0)),hV=new Uint8Array(UJ.buffer);try{UJ.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 dQ=RangeError("Insufficient data"),dV=new MJ;class _${extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=UJ;bytes=hV;headByte=q$;stack=new aQ;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??$$.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.rawStrings=$?.rawStrings??!1,this.maxStrLength=$?.maxStrLength??e0,this.maxBinLength=$?.maxBinLength??e0,this.maxArrayLength=$?.maxArrayLength??e0,this.maxMapLength=$?.maxMapLength??e0,this.maxExtLength=$?.maxExtLength??e0,this.keyDecoder=$?.keyDecoder!==void 0?$.keyDecoder:dV,this.mapKeyConverter=$?.mapKeyConverter??nV}clone(){return new _$({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=q$,this.stack.reset()}setBuffer($){let J=M$($);this.bytes=J,this.view=new DataView(J.buffer,J.byteOffset,J.byteLength),this.pos=0}appendBuffer($){if(this.headByte===q$&&!this.hasRemaining(1))this.setBuffer($);else{let J=this.bytes.subarray(this.pos),Q=M$($),I=new Uint8Array(J.length+Q.length);I.set(J),I.set(Q,J.length),this.setBuffer(I)}}hasRemaining($){return this.view.byteLength-this.pos>=$}createExtraByteError($){let{view:J,pos:Q}=this;return RangeError(`Extra ${J.byteLength-Q} of ${J.byteLength} byte(s) found at buffer[${$}]`)}decode($){if(this.entered)return this.clone().decode($);try{this.entered=!0,this.reinitializeState(),this.setBuffer($);let J=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return J}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 J=!1,Q;for await(let X of $){if(J)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(X);try{Q=this.doDecodeSync(),J=!0}catch(Y){if(!(Y instanceof RangeError))throw Y}this.totalPos+=this.pos}if(J){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Q}let{headByte:I,pos:V,totalPos:Z}=this;throw RangeError(`Insufficient data in parsing ${L$(I)} at ${Z} (${V} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream($){return this.decodeMultiAsync($,!0)}decodeStream($){return this.decodeMultiAsync($,!1)}async*decodeMultiAsync($,J){if(this.entered){yield*this.clone().decodeMultiAsync($,J);return}try{this.entered=!0;let Q=J,I=-1;for await(let V of $){if(J&&I===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(V),Q)I=this.readArraySize(),Q=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--I===0)break}catch(Z){if(!(Z instanceof RangeError))throw Z}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){$:while(!0){let $=this.readHeadByte(),J;if($>=224)J=$-256;else if($<192)if($<128)J=$;else if($<144){let I=$-128;if(I!==0){this.pushMapState(I),this.complete();continue $}else J={}}else if($<160){let I=$-144;if(I!==0){this.pushArrayState(I),this.complete();continue $}else J=[]}else{let I=$-160;J=this.decodeString(I,0)}else if($===192)J=null;else if($===194)J=!1;else if($===195)J=!0;else if($===202)J=this.readF32();else if($===203)J=this.readF64();else if($===204)J=this.readU8();else if($===205)J=this.readU16();else if($===206)J=this.readU32();else if($===207)if(this.useBigInt64)J=this.readU64AsBigInt();else J=this.readU64();else if($===208)J=this.readI8();else if($===209)J=this.readI16();else if($===210)J=this.readI32();else if($===211)if(this.useBigInt64)J=this.readI64AsBigInt();else J=this.readI64();else if($===217){let I=this.lookU8();J=this.decodeString(I,1)}else if($===218){let I=this.lookU16();J=this.decodeString(I,2)}else if($===219){let I=this.lookU32();J=this.decodeString(I,4)}else if($===220){let I=this.readU16();if(I!==0){this.pushArrayState(I),this.complete();continue $}else J=[]}else if($===221){let I=this.readU32();if(I!==0){this.pushArrayState(I),this.complete();continue $}else J=[]}else if($===222){let I=this.readU16();if(I!==0){this.pushMapState(I),this.complete();continue $}else J={}}else if($===223){let I=this.readU32();if(I!==0){this.pushMapState(I),this.complete();continue $}else J={}}else if($===196){let I=this.lookU8();J=this.decodeBinary(I,1)}else if($===197){let I=this.lookU16();J=this.decodeBinary(I,2)}else if($===198){let I=this.lookU32();J=this.decodeBinary(I,4)}else if($===212)J=this.decodeExtension(1,0);else if($===213)J=this.decodeExtension(2,0);else if($===214)J=this.decodeExtension(4,0);else if($===215)J=this.decodeExtension(8,0);else if($===216)J=this.decodeExtension(16,0);else if($===199){let I=this.lookU8();J=this.decodeExtension(I,1)}else if($===200){let I=this.lookU16();J=this.decodeExtension(I,2)}else if($===201){let I=this.lookU32();J=this.decodeExtension(I,4)}else throw new Y0(`Unrecognized type byte: ${L$($)}`);this.complete();let Q=this.stack;while(Q.length>0){let I=Q.top();if(I.type===qJ)if(I.array[I.position]=J,I.position++,I.position===I.size)J=I.array,Q.release(I);else continue $;else if(I.type===U$){if(J==="__proto__")throw new Y0("The key __proto__ is not allowed");I.key=this.mapKeyConverter(J),I.type=oQ;continue $}else if(I.map[I.key]=J,I.readCount++,I.readCount===I.size)J=I.map,Q.release(I);else{I.key=null,I.type=U$;continue $}}return J}}readHeadByte(){if(this.headByte===q$)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=q$}readArraySize(){let $=this.readHeadByte();switch($){case 220:return this.readU16();case 221:return this.readU32();default:if($<160)return $-144;else throw new Y0(`Unrecognized array type byte: ${L$($)}`)}}pushMapState($){if($>this.maxMapLength)throw new Y0(`Max length exceeded: map length (${$}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState($)}pushArrayState($){if($>this.maxArrayLength)throw new Y0(`Max length exceeded: array length (${$}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState($)}decodeString($,J){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String($,J);return this.decodeBinary($,J)}decodeUtf8String($,J){if($>this.maxStrLength)throw new Y0(`Max length exceeded: UTF-8 byte length (${$}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+J+$)throw dQ;let Q=this.pos+J,I;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached($))I=this.keyDecoder.decode(this.bytes,Q,$);else I=lQ(this.bytes,Q,$);return this.pos+=J+$,I}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===U$;return!1}decodeBinary($,J){if($>this.maxBinLength)throw new Y0(`Max length exceeded: bin length (${$}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining($+J))throw dQ;let Q=this.pos+J,I=this.bytes.subarray(Q,Q+$);return this.pos+=J+$,I}decodeExtension($,J){if($>this.maxExtLength)throw new Y0(`Max length exceeded: ext length (${$}) > maxExtLength (${this.maxExtLength})`);let Q=this.view.getInt8(this.pos+J),I=this.decodeBinary($,J+1);return this.extensionCodec.decode(I,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 $=nQ(this.view,this.pos);return this.pos+=8,$}readI64(){let $=j$(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 zJ($,J){return new _$(J).decode($)}class v0{listeners=new Map;addEventListener($,J){let Q=this.listeners.get($);if(!Q)Q=new Set,this.listeners.set($,Q);return Q.add(J),()=>{this.removeEventListener($,J)}}removeEventListener($,J){let Q=this.listeners.get($);if(Q){if(Q.delete(J),Q.size===0)this.listeners.delete($)}}emit($,J){let Q=this.listeners.get($);if(Q){let I=Array.from(Q);for(let V of I)V(J)}}emitAll($){let J=Array.from(this.listeners.keys());for(let Q of J)this.emit(Q,$)}}class A0{getter;static eventName="update";emitter;constructor($){this.getter=$;this.emitter=new v0}get=()=>this.getter();async emit(){let $=await this.getter();queueMicrotask(()=>this.emitter.emit(A0.eventName,$))}listen($){return this.emitter.addEventListener(A0.eventName,$),()=>{this.emitter.removeEventListener(A0.eventName,$)}}}var y0=64;var sQ=32,b0=8;var E$=32;var tQ=30000,eQ=512,L;((H)=>{H[H.Success=0]="Success";H[H.InvalidSignature=3]="InvalidSignature";H[H.ClockOutOfSync=4]="ClockOutOfSync";H[H.UserNotRegistered=5]="UserNotRegistered";H[H.ServerMisconfigured=6]="ServerMisconfigured";H[H.MissingBody=7]="MissingBody";H[H.ExtraBodyContent=8]="ExtraBodyContent";H[H.MissingParam=9]="MissingParam";H[H.InvalidParam=10]="InvalidParam";H[H.InvalidRequest=11]="InvalidRequest";H[H.InternalError=12]="InternalError";H[H.NotFound=13]="NotFound";H[H.InvalidMessage=14]="InvalidMessage";H[H.NoChange=15]="NoChange";H[H.DatabaseClosed=16]="DatabaseClosed";H[H.StorageError=17]="StorageError";H[H.DatabaseError=18]="DatabaseError";H[H.HashMismatch=19]="HashMismatch";H[H.DecryptionError=20]="DecryptionError";H[H.NotImplemented=21]="NotImplemented";H[H.MissingSeed=22]="MissingSeed";H[H.OutOfBounds=23]="OutOfBounds";H[H.HostError=24]="HostError";H[H.CommunicationError=25]="CommunicationError";H[H.VarLimitExceeded=26]="VarLimitExceeded";H[H.InvalidResponse=27]="InvalidResponse";H[H.ConnectionClosed=28]="ConnectionClosed"})(L||={});function j($){return[$,0]}function q($){return[void 0,$]}function oV($){if($<0)console.info("N",$),console.trace();if(typeof $!=="bigint")$=BigInt($);if($<0n)return q(10);let J=[];while($>0n){let Q=Number($&0x7fn);if($>>=7n,$>0n)J.push(Q|128);else J.push(Q)}if(J.length===0)return j(new Uint8Array([0]));if(J.length>8)return q(26);return j(new Uint8Array(J))}function aV($,J=0){let Q=0n,I=0,V=J;while(!0){if(V>=$.length)return q(14);let Z=$[V++];if(Z===void 0)return q(14);if(Q|=BigInt(Z&127)<<BigInt(I),(Z&128)===0){if(V-J>8)return q(26);return j({value:Q>0x1fffffffffffffn?Q:Number(Q),bytesRead:V-J})}if(I+=7,I>=56)return q(26)}}class h{data;pos=0;constructor($){this.data=$}static async fromResponse($){let J=await $.arrayBuffer(),Q=new Uint8Array(J);return new h(Q)}readBigInt(){if(this.pos+8>this.data.length)return q(7);let $=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,j($)}readDate(){let[$,J]=this.readVarInt();if(J!==0)return q(J);return j(new Date($))}readVarInt(){let[$,J]=aV(this.data,this.pos);if(J!==0)return q(J);this.pos+=$.bytesRead;let Q=$.value;return j(typeof Q==="bigint"?Number(Q):Q)}readVarString(){let[$,J]=this.readVarInt();if(J!==0)return q(J);let[Q,I]=this.readBytes($);if(I!==0)return q(I);let V=new TextDecoder().decode(Q);return j(V)}readBytes($){if($<0)return q(10);if(this.pos+$>this.data.length)return q(23);let J=this.data.slice(this.pos,this.pos+$);return this.pos+=$,j(J)}readVarBytes(){let[$,J]=this.readVarInt();if(J!==0)return q(J);return this.readBytes($)}readStruct($){return $.decode(this)}readStructs($){let J=[];while(!this.done()){let[Q,I]=this.readStruct($);if(I!==0)return q(I);J.push(Q)}return j(J)}readBytesSeq($){let J=[];while(!this.done()){let[Q,I]=this.readBytes($);if(I!==0)return q(I);J.push(Q)}return j(J)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class l{parts=[];writeBigInt($){let J=new Uint8Array(8);new DataView(J.buffer).setBigUint64(0,$,!1),this.parts.push(J)}writeDate($){let J=$.getTime();return this.writeVarInt(J)}writeVarInt($){let[J,Q]=oV($);if(Q!==0)return Q;return this.parts.push(J),0}writeVarString($){let J=new TextEncoder().encode($),Q=this.writeVarInt(J.length);if(Q!==0)return Q;return this.writeBytes(J),0}prependBytes($){this.parts.unshift($)}writeBytes($){this.parts.push($)}writeVarBytes($){let J=this.writeVarInt($.length);if(J!==0)return J;return this.writeBytes($),0}writeStruct($,J){return $.encode(this,J)}writeStructs($,J){for(let Q of J){let I=this.writeStruct($,Q);if(I!==0)return I}return 0}writeBytesSeq($){for(let J of $)this.writeBytes(J)}result(){let $=this.parts.reduce((I,V)=>I+V.length,0),J=new Uint8Array($),Q=0;for(let I of this.parts)J.set(I,Q),Q+=I.length;return J}*scan(){for(let $ of this.parts)yield $}}async function OJ($,J,Q){let I=new l,V=I.writeDate(J);if(V!==0)return q(V);let Z=I.result(),X=await Q.signEd25519(Z,$.privateKey);return j({pubKey:$.publicKey,sig:X,timestamp:J})}async function u0($,J,Q){let I=Q.now().getTime(),V=$.timestamp.getTime();if(Math.abs(I-V)>tQ)return 4;let X=new l;X.writeDate($.timestamp);let Y=X.result();if(!await J.checkSigEd25519($.sig,Y,$.pubKey))return 3;return 0}var q0={encode($,J){let Q=$.writeVarBytes(J.id);if(Q!==0)return Q;let I=$.writeDate(J.ts);if(I!==0)return I;return 0},decode($){let[J,Q]=$.readVarBytes();if(Q!==0)return q(Q);let[I,V]=$.readDate();if(V!==0)return q(V);return j({id:J,ts:I})}};function J$($){let J=new l,Q=J.writeStruct(q0,$);if(Q!==0)return q(Q);let I=J.result();return j(I)}async function sV($){return J$({id:$,ts:new Date(0)})}var R0={encode($,J){let Q=$.writeVarBytes(J.eid);if(Q!==0)return Q;let I=$.writeVarInt(J.off);if(I!==0)return I;let V=$.writeVarInt(J.ctr);if(V!==0)return V;let Z=$.writeVarInt(J.len);if(Z!==0)return Z;if(J.hsh)$.writeBytes(J.hsh);return 0},decode($){let[J,Q]=$.readVarBytes();if(Q!==0)return q(Q);let I=new h(J),[,V]=q0.decode(I);if(V!==0)return q(V);let[Z,X]=$.readVarInt();if(X!==0)return q(X);let[Y,K]=$.readVarInt();if(K!==0)return q(K);let[W,G]=$.readVarInt();if(G!==0)return q(G);let N;if(W>0){let[U,M]=$.readBytes(E$);if(M!==0)return q(M);N=U}return j({eid:J,off:Z,ctr:Y,len:W,hsh:N})}};function C0($){return Array.from($).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}function i0($){if($.length%2!==0)throw Error("Invalid hex string");let J=new Uint8Array($.length/2);for(let Q=0;Q<$.length;Q+=2)J[Q/2]=Number.parseInt($.substr(Q,2),16);return J}function w0($,J){if($===J)return!0;if($.byteLength!==J.byteLength)return!1;return $.every((Q,I)=>Q===J[I])}var d;if(typeof Uint8Array.prototype.toBase64==="function")d=($)=>$.toBase64();else d=($)=>btoa(String.fromCharCode(...$));var U0;if(typeof Uint8Array.fromBase64==="function")U0=($)=>Uint8Array.fromBase64($);else U0=($)=>Uint8Array.from(atob($),(J)=>J.charCodeAt(0));function z$($,J){let Q=new Uint8Array($.length+J.length);return Q.set($,0),Q.set(J,$.length),Q}function $I($,J,Q){return Q.checkSigEd25519($.sig,$.headCph,J)}async function HJ($,J,Q){let I=z$(J.privateKey,$);return(await Q.blake3(I)).slice(0,b0)}async function JI($,J,Q,I){let V;if($.bod&&$.len>0)V=await Q.blake3($.bod);let Z=new l,X=R0.encode(Z,{...$,hsh:V});if(X!==0)return q(X);let Y=Z.result(),K=await HJ(Y,J,Q),W=await I.deriveFromKDM(K),G=await Q.encryptXSalsa20Poly1305Combined(Y,W),N=$.bod?await Q.encryptXSalsa20Poly1305Combined($.bod,W):new Uint8Array(0),U=await Q.signEd25519(G,J.privateKey);return j({sig:U,kdm:K,headCph:G,bodyCph:N})}async function RJ($,J,Q,I){let V=new h($),[Z,X]=R0.decode(V);if(X!==0)return q(14);let Y;try{Y=J&&J.length>0?await I.decryptXSalsa20Poly1305Combined(J,Q):void 0}catch{return q(20)}let K=Z.hsh&&Y===void 0,W=Z.hsh===void 0&&Y!==void 0;if(K||W)return q(19);if(Z.hsh&&Y){let N=await I.blake3(Y);if(!w0(N,Z.hsh))return q(19)}let G=await I.blake3($);return j({msgHead:Z,bod:Y,headHash:G})}class L0{now(){return new Date}}function QI($,J,Q,I){let V=J.getTime()-$.getTime(),Z=Q.getTime()-I.getTime();return(V+Z)/2}var O$={encode($,J){if($.writeVarInt(J.quota),J.quota>0){if(J.usage===void 0)return 9;$.writeVarInt(J.usage)}return 0},decode($){let[J,Q]=$.readVarInt();if(Q!==0)return q(Q);let I;if(J>0){let[V,Z]=$.readVarInt();if(Z!==0)return q(Z);I=V}return j({quota:J,usage:I})}};var CJ={encode($,J){$.writeBytes(new Uint8Array([J.status]));let Q=$.writeDate(J.timeRcvd);if(Q!==0)return Q;let I=$.writeDate(J.timeSent);if(I!==0)return I;let V=$.writeVarInt(J.subscription.term);if(V!==0)return V;let Z=$.writeVarInt(J.subscription.elapsed);if(Z!==0)return Z;let X=$.writeStruct(O$,J.subscription.stat);if(X!==0)return X;let Y=$.writeStruct(O$,J.subscription.dyn);if(Y!==0)return Y;return 0},decode($){let[J,Q]=$.readBytes(1);if(Q!==0)return q(Q);let I=J[0],[V,Z]=$.readDate();if(Z!==0)return q(Z);let[X,Y]=$.readDate();if(Y!==0)return q(Y);let[K,W]=$.readVarInt();if(W!==0)return q(W);let[G,N]=$.readVarInt();if(N!==0)return q(N);let[U,M]=$.readStruct(O$);if(M!==0)return q(M);let[O,z]=$.readStruct(O$);if(z!==0)return q(z);return j({status:I,timeRcvd:V,timeSent:X,subscription:{term:K,elapsed:G,stat:U,dyn:O}})}};async function wJ($,J,Q){let{crypto:I,enclave:V}=$,Z=await V.derive(J,Q);return await I.deriveEd25519KeyPair(Z)}var TJ={encode($,J){let Q=$.writeVarBytes(J.headCph);if(Q!==0)return Q;let I=$.writeVarInt(J.seq);if(I!==0)return I;return 0},decode($){let[J,Q]=$.readVarBytes();if(Q!==0)return q(Q);let[I,V]=$.readVarInt();if(V!==0)return q(V);return j({headCph:J,seq:I})}};var W0={encode($,J){$.writeBytes(J.pubKey),$.writeBytes(J.sig);let Q=$.writeDate(J.timestamp);if(Q!==0)return Q;return 0},decode($){let[J,Q]=$.readBytes(sQ);if(Q!==0)return q(Q);let[I,V]=$.readBytes(y0);if(V!==0)return q(V);let[Z,X]=$.readDate();if(X!==0)return q(X);return j({pubKey:J,sig:I,timestamp:Z})}};var II={async encodeReq($,J,Q,I,V){let Z=V.writeStruct(W0,Q);if(Z!==0)return Z;for(let X of I)V.writeVarInt(X);return 0},async handleReq($,J,Q){let{clock:I,crypto:V,storage:Z}=$,[X,Y]=J.readStruct(W0);if(Y!==0)return Y;let K=await u0(X,V,I);if(K!==0)return K;let{pubKey:W}=X,[G,N]=await Z.hasUser(W);if(N!==0)return N;if(!G)return 5;let[U,M]=J.readVarInt();if(M!==0)return M;if(!J.done())return 8;let[O,z]=await Z.listHeads(W,U);if(z!==0)return z;return Q.writeStructs(TJ,O)},decodeResp($){return $.readStructs(TJ)}};var DJ={encode($,J){$.writeVarInt(J.seq);let Q=$.writeVarBytes(J.bodyCph);if(Q!==0)return Q;return 0},decode($){let[J,Q]=$.readVarInt();if(Q!==0)return q(Q);let[I,V]=$.readVarBytes();if(V!==0)return q(V);return j({seq:J,bodyCph:I})}};var VI={async encodeReq($,J,Q,I,V){let Z=V.writeStruct(W0,Q);if(Z!==0)return Z;for(let X of I){let Y=V.writeVarInt(X);if(Y!==0)return Y}return 0},async handleReq($,J,Q){let{clock:I,crypto:V,storage:Z}=$,[X,Y]=J.readStruct(W0);if(Y!==0)return Y;let K=await u0(X,V,I);if(K!==0)return K;let{pubKey:W}=X,[G,N]=await Z.hasUser(W);if(N!==0)return N;if(!G)return 5;let U=[];while(!J.done()){let[z,R]=J.readVarInt();if(R!==0)return R;U.push(z)}console.info(`PULL: ${U.length} bags`);let[M,O]=await Z.getBodies(W,U);if(O!==0)return O;if(!M)return 17;for(let{seq:z,bodyCph:R}of M){let D={seq:z,bodyCph:R},w=Q.writeStruct(DJ,D);if(w!==0)return w}return 0},decodeResp($){return $.readStructs(DJ)}};var FJ={encode($,J){$.writeBytes(J.sig),$.writeBytes(J.kdm);let Q=$.writeVarBytes(J.headCph);if(Q!==0)return Q;let I=$.writeVarBytes(J.bodyCph);if(I!==0)return I;return 0},decode($){let[J,Q]=$.readBytes(y0);if(Q!==0)return q(Q);let[I,V]=$.readBytes(b0);if(V!==0)return q(V);let[Z,X]=$.readVarBytes();if(X!==0)return q(X);let[Y,K]=$.readVarBytes();if(K!==0)return q(K);return j({sig:J,kdm:I,headCph:Z,bodyCph:Y})}};var B$={encode($,J){let Q=$.writeVarInt(J.seq);if(Q!==0)return Q;let I=$.writeVarBytes(J.headCph);if(I!==0)return I;let V=J.bodyCph?J.bodyCph.length:0,Z=$.writeVarInt(V);if(Z!==0)return Z;if(V>0){if(!J.bodyCph)return 10;$.writeBytes(J.bodyCph)}return 0},decode($){let[J,Q]=$.readVarInt();if(Q!==0)return q(Q);let[I,V]=$.readVarBytes();if(V!==0)return q(V);let[Z,X]=$.readVarInt();if(X!==0)return q(X);let Y;if(Z>0){let[K,W]=$.readBytes(Z);if(W!==0)return q(W);Y=K}return j({seq:J,headCph:I,bodyCph:Y})}};var f$={encode($,J){$.writeBytes(J.sig),$.writeBytes(J.kdm);let Q=$.writeVarBytes(J.headCph);if(Q!==0)return Q;return 0},decode($){let[J,Q]=$.readBytes(y0);if(Q!==0)return q(Q);let[I,V]=$.readBytes(b0);if(V!==0)return q(V);let[Z,X]=$.readVarBytes();if(X!==0)return q(X);return j({sig:J,kdm:I,headCph:Z})}};var x$={encode($,J){if($.writeVarInt(J.idx),$.writeBytes(new Uint8Array([J.status])),J.status===0)$.writeVarInt(J.seq);return 0},decode($){let[J,Q]=$.readVarInt();if(Q!==0)return q(Q);let[I,V]=$.readBytes(1);if(V!==0)return q(V);let Z=I[0];if(Z!==0)return j({idx:J,status:Z});let[X,Y]=$.readVarInt();if(Y!==0)return q(Y);return j({idx:J,status:Z,seq:X})}};var ZI={async encodeReq($,J,Q,I,V){let Z=V.writeStruct(W0,Q);if(Z!==0)return Z;let X=V.writeStructs(FJ,I);if(X!==0)return X;return 0},async handleReq($,J,Q){let{clock:I,crypto:V,storage:Z,notifier:X}=$,[Y,K]=J.readStruct(W0);if(K!==0)return K;let W=await u0(Y,V,I);if(W!==0)return W;let{pubKey:G}=Y,[N,U]=await Z.hasUser(G);if(U!==0)return U;if(!N)return 5;let[M,O]=J.readStructs(FJ);if(O!==0)return O;console.info(`PUSH: ${M.length} bags`);let z=[],R=[];for(let A=0;A<M.length;A++){let S=M[A];if(!await $I(S,G,V)){let f={idx:A,status:3},B=Q.writeStruct(x$,f);if(B!==0)return B;continue}z.push(A),R.push(S)}let[D,w]=await Z.setBags(G,R);if(w!==0)return w;if(!D||D.length!==R.length)return 17;let F=[];for(let A=0;A<R.length;A++){let S=R[A],y=z[A],f=D[A],B=new l,m=B.writeStruct(f$,S);if(m!==0)return m;let u=B.result(),H={seq:f,headCph:u};if(M.length===1&&S.bodyCph.length<=eQ)H.bodyCph=S.bodyCph;F.push(H);let g={idx:y,status:0,seq:f},p=Q.writeStruct(x$,g);if(p!==0)return p}if(F.length>0){let A=new l,S=A.writeStructs(B$,F);if(S!==0)return S;let y=A.result();await Promise.resolve(X.push(G,y))}return 0},decodeResp($){return $.readStructs(x$)}};var XI={async encodeReq($,J,Q,I,V){return V.writeStruct(W0,Q)},async handleReq($,J,Q){let{clock:I,crypto:V,storage:Z}=$,[X,Y]=J.readStruct(W0);if(Y!==0)return Y;let K=await u0(X,V,I);if(K!==0)return K;let{pubKey:W}=X;if(!J.done())return 8;let[G,N]=await Z.addUser(W);if(N!==0)return N;return 0},decodeResp($){return j(void 0)}};class AJ{url;websocket;constructor($){this.url=$}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect($,J,Q=()=>{},I=()=>{}){let{url:V}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let Z=new l;Z.writeStruct(W0,$);let X=Z.result(),Y=C0(X);return V.searchParams.set("t",Y),this.websocket=new WebSocket(V),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),I()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Q()},this.websocket.onmessage=(K)=>{let W=new Uint8Array(K.data);J(W)},this.websocket.onerror=(K)=>{console.log(`ERROR: ${JSON.stringify(K)}`),this.websocket=void 0,Q()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var Z0={user:{path:"/user",endpoint:XI,name:0},push:{path:"/push",endpoint:ZI,name:2},peek:{path:"/peek",endpoint:II,name:1},pull:{path:"/pull",endpoint:VI,name:3}},tV={0:Z0.user,2:Z0.push,1:Z0.peek,3:Z0.pull},bK={[Z0.user.path]:Z0.user,[Z0.push.path]:Z0.push,[Z0.peek.path]:Z0.peek,[Z0.pull.path]:Z0.pull};class PJ{url;listener;constructor($){this.url=$;this.listener=new AJ($)}async call($,J){let{path:Q}=tV[$],I=new URL(Q,this.url);try{return await eV(I,J)}catch{return q(25)}}}var g$=($)=>{return new PJ($.handle)};async function eV($,J){let Q=await fetch($,{method:"POST",body:J.result().slice()});if(!Q.ok)return q(24);let I=await h.fromResponse(Q);return j(I)}class m${enclave;crypto;host;clock;transport;updateHostMeta;constructor($,J,Q,I,V,Z){this.enclave=$;this.crypto=J;this.host=Q;this.clock=I;this.transport=V;this.updateHostMeta=Z}async call($,J){let{clock:Q,crypto:I,transport:V}=this,{endpoint:Z,name:X}=$,Y=await this.keys(),K=Q.now(),[W,G]=await OJ(Y,K,I);if(G!==0)return q(G);let N=new l,U=await Z.encodeReq(this,Y,W,J,N);if(U!==0)return q(U);let M=Q.now(),[O,z]=await V.call(X,N),R=Q.now();if(z!==0)return q(z);let[D,w]=O.readStruct(CJ);if(w!==0)return q(w);if(D.status!==0)return q(D.status);let A={clockOffset:QI(M,D.timeRcvd,D.timeSent,R),subscription:D.subscription},S=await this.updateHostMeta(A);if(S!==0)return q(S);return Z.decodeResp(O)}keys=()=>{let{host:$}=this;return wJ(this,$.label,$.idx)};seal=async($)=>{let{crypto:J,enclave:Q}=this,I=await this.keys();return JI($,I,J,Q)};register=()=>this.call(Z0.user,[]);peek=($)=>this.call(Z0.peek,[$]);push=($)=>this.call(Z0.push,$);pull=($)=>this.call(Z0.pull,$);listen=async($,J,Q)=>{let{clock:I,crypto:V,host:Z,transport:X}=this,{listener:Y}=X,K=await wJ(this,Z.label,Z.idx),W=I.now(),[G,N]=await OJ(K,W,V);if(N!==0)return N;return await Y.connect(G,$,J,Q)};isConnected(){let $=this.transport?.listener;if($&&typeof $.connected==="function")return $.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var jJ={encode($,J){let Q=$.writeVarString(J.lbl);if(Q!==0)return Q;let I=$.writeVarInt(J.idx);if(I!==0)return I;let V=$.writeVarInt(J.num);if(V!==0)return V;return $.writeBytes(J.hsh),$.writeBytes(J.sig),0},decode($){let[J,Q]=$.readVarString();if(Q!==0)return q(Q);let[I,V]=$.readVarInt();if(V!==0)return q(V);let[Z,X]=$.readVarInt();if(X!==0)return q(X);let[Y,K]=$.readBytes(E$);if(K!==0)return q(K);let[W,G]=$.readBytes(y0);if(G!==0)return q(G);return j({lbl:J,idx:I,num:Z,hsh:Y,sig:W})}};var kJ={encode($,J){let Q=$.writeStruct(jJ,J.head);if(Q!==0)return Q;let I=$.writeVarBytes(J.indexEnc);if(I!==0)return I;let V=$.writeVarBytes(J.bodyEnc);if(V!==0)return V;return 0},decode($){let[J,Q]=$.readStruct(jJ);if(Q!==0)return q(Q);let[I,V]=$.readVarBytes();if(V!==0)return q(V);let[Z,X]=$.readVarBytes();if(X!==0)return q(X);return j({head:J,indexEnc:I,bodyEnc:Z})}};var SJ={encode($,J){$.writeBytes(J.kdm);let Q=$.writeVarBytes(J.headCph);if(Q!==0)return Q;let I=$.writeVarInt(J.lenBody);if(I!==0)return I;if(J.lenBody>0&&J.offBody!==void 0){let V=$.writeVarInt(J.offBody);if(V!==0)return V}return 0},decode($){let[J,Q]=$.readBytes(b0);if(Q!==0)return q(Q);let[I,V]=$.readVarBytes();if(V!==0)return q(V);let[Z,X]=$.readVarInt();if(X!==0)return q(X);let Y;if(Z>0){let[K,W]=$.readVarInt();if(W!==0)return q(W);Y=K}return j({kdm:J,headCph:I,lenBody:Z,offBody:Y})}};async function YI($,J,Q,I,V){let Z=await V.derive($,J),X=await I.deriveEd25519KeyPair(Z),Y=new l,K=new l,W=0,G=0;for(let w of Q){let F=new l,A=F.writeStruct(R0,w.head);if(A!==0)return q(A);let S=F.result(),y=await HJ(S,X,I),f=await V.deriveFromKDM(y),B=await I.encryptXSalsa20Poly1305Combined(S,f),m=w.body?await I.encryptXSalsa20Poly1305Combined(w.body,f):new Uint8Array(0),u=w.head.len>0&&w.head.hsh!==void 0?m.length:0,H={kdm:y,headCph:B,lenBody:u,offBody:u>0?G:void 0},g=Y.writeStruct(SJ,H);if(g!==0)return q(g);if(w.body)K.writeBytes(m),G+=m.length;W++}let N=K.result(),U=Y.result(),M=await I.blake3(U),O=await I.signEd25519(M,X.privateKey),z={lbl:$,idx:J,num:W,hsh:M,sig:O},R=new l;R.writeStruct(kJ,{head:z,indexEnc:U,bodyEnc:N});let D=R.result();return j(D)}async function KI($,J,Q){let[I,V]=kJ.decode(new h($));if(V!==0)return q(V);let{head:Z,indexEnc:X,bodyEnc:Y}=I,K=await Q.derive(Z.lbl,Z.idx),W=await J.deriveEd25519KeyPair(K);if(!await J.checkSigEd25519(Z.sig,Z.hsh,W.publicKey))return q(3);let N=await J.blake3(X);if(!w0(N,Z.hsh))return q(19);let U=new h(X),M=[];for(let z=0;z<Z.num;z++){let[R,D]=U.readStruct(SJ);if(D!==0)return q(D);M.push(R)}if(M.length!==Z.num)return q(14);let O=[];for(let z of M){let R=await Q.deriveFromKDM(z.kdm),D=await J.decryptXSalsa20Poly1305Combined(z.headCph,R),[w,F]=R0.decode(new h(D));if(F!==0)return q(F);let A;if(z.lenBody>0&&z.offBody!==void 0){if(w.hsh===void 0)return q(14);let S=Y.slice(z.offBody,z.offBody+z.lenBody);A=await J.decryptXSalsa20Poly1305Combined(S,R);let y=await J.blake3(A);if(!w0(y,w.hsh))return q(19)}O.push({head:w,body:A})}return j(O)}async function GI({now:$,bod:J,crypto:Q}){let I=await Q.genRandomBytes(8),V=new l,Z=V.writeStruct(q0,{id:I,ts:$});if(Z!==0)return q(Z);let X=V.result();return v$({now:$,eid:X,ctr:0,bod:J,crypto:Q})}async function v$({now:$,eid:J,ctr:Q,bod:I,crypto:V}){let Z=new h(J),[X,Y]=q0.decode(Z);if(Y!==0)return q(Y);let K=$.getTime()-X.ts.getTime(),W,G=I?.length??0;if(I&&G>0)W=await V.blake3(I);return j({eid:J,off:K,ctr:Q,len:G,hsh:W})}class y${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 J=await $();while(this.again)this.again=!1,J=await $();return J}finally{this.inflight=null}}}var b$=100;class H${timer=null;delayMs;work;tail=new y$;constructor($,J){this.delayMs=$<0?0:$,this.work=J}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)}}var Q$={phase:"idle"},R$=50;function I$($,J,Q){if($<=0||J<=0)return!1;if($===1||$===J)return!0;return $%Q===0}function u$($,J){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob($,J);return}let Q=URL.createObjectURL($),I=document.createElement("a");I.href=Q,I.download=J,document.body.appendChild(I),I.click(),document.body.removeChild(I),URL.revokeObjectURL(Q)}async function LJ($,J,Q,I){let V=new h($.headCph),[Z,X]=V.readStruct(f$);if(X!==0)return q(X);let{sig:Y,kdm:K,headCph:W}=Z;if(!await I.checkSigEd25519(Y,W,J.publicKey))return q(3);let N=await Q.deriveFromKDM(K),U;try{U=await I.decryptXSalsa20Poly1305Combined(W,N)}catch{return q(20)}return j({kdm:K,headEnc:U})}var _J=1048576,EJ=1048576;function $Z($){return $.sig.length+$.kdm.length+$.headCph.length+$.bodyCph.length}async function JZ($,J,Q,I,V){if(I.length<1)return 0;let[Z,X]=await $.push(I);if(X!==0)return X;if(!Z)return 27;for(let K of Z){if(K.status!==0){console.error("push err",K);continue}let W=V[K.idx];if(!W){console.error("no hash",K);continue}await J.uploads.deq(Q,[W])}let Y=await J.hosts.get(Q);if(Y){let K=Y.lastSeq,W=K,G=[];for(let N of Z)if(N.status===0)G.push(N.seq);G.sort((N,U)=>N-U);for(let N of G)if(N===K+1)K=N;if(K>W)await J.hosts.touch(Q,K)}return 0}async function QZ($,J,Q,I,V,Z,X){if(Z.length<1)return 0;let Y=new Map,K=[];for(let R of Z)Y.set(R.seq,R),K.push(R.seq);let[W,G]=await $.pull(K);if(G!==0)return G;if(!W)return 27;let N=[],U=[],M=[];for(let{seq:R,bodyCph:D}of W){let w=Y.get(R);if(!w)continue;let{head:F}=w,A=new l;A.writeStruct(R0,F);let S=A.result(),y=await V.blake3(S),f=await Q.deriveFromKDM(w.kdm),[B,m]=await RJ(S,D,f,V);if(m!==0){await J.downloads.deq(I,[R]);continue}let u={head:F,body:B.bod},H=MI(u);U.push({key:y,data:H}),N.push(u),M.push(R)}let O=await J.messages.add(U);await J.downloads.deq(I,M);let z=await X(N,{enqueueUpload:!1,triggerUpload:!1});for(let R=0;R<z.length;R++){let D=O[R];if(D!==0&&D!==15)console.error("ERR storing",L[D],"for message",R);let w=z[R];if(w!==0&&w!==15)console.error("ERR applying",L[w],"for message",R)}return 0}async function WI({conn:$,store:J,enclave:Q,host:I,crypto:V,onProgress:Z,peekProgressEvery:X}){let Y=await $.keys(),K=[],[W,G]=await $.peek(I.lastSeq);if(G!==0)return G;let N=W.length,U=X??R$;if(Z&&N>0)Z({phase:"peek",host:I.label,done:0,total:N});let M=0;for(let O of W){let[z,R]=await LJ(O,Y,Q,V);if(R!==0){if(console.error("peek: decrypting item head",R),M+=1,Z&&I$(M,N,U))Z({phase:"peek",host:I.label,done:M,total:N});continue}let D=await V.blake3(z.headEnc);if(await J.messages.has(D)){if(console.info("peek: skipping download enqueue"),await J.uploads.deq(I.label,[D]),M+=1,Z&&I$(M,N,U))Z({phase:"peek",host:I.label,done:M,total:N});continue}let F=new h(z.headEnc),[A,S]=F.readStruct(R0);if(S!==0){if(console.error("peek: reading item head",S),M+=1,Z&&I$(M,N,U))Z({phase:"peek",host:I.label,done:M,total:N});continue}if(K.push({kdm:z.kdm,head:A,seq:O.seq,host:I.label}),M+=1,Z&&I$(M,N,U))Z({phase:"peek",host:I.label,done:M,total:N})}if(await J.downloads.enq(K),W.length>0){let O=Math.max(...W.map((z)=>z.seq));await J.hosts.touch(I.label,O)}if(Z)Z({phase:"peek",host:I.label,done:N,total:N});return 0}async function NI({conn:$,store:J,host:Q,maxPushBytes:I,onProgress:V}){let Z=I??_J,X=await J.uploads.list(Q.label),Y=X.length,K=0;if(V&&Y>0)V({phase:"push",host:Q.label,done:0,total:Y});let W=[],G=[],N=0,U=async()=>{if(W.length<1)return 0;let M=W.length,O=await JZ($,J,Q.label,W,G);if(W=[],G=[],N=0,O===0){if(K+=M,V)V({phase:"push",host:Q.label,done:K,total:Y})}return O};for(let M of X){let O=await J.messages.get(M);if(!O){K+=1;continue}let z={...O.head,bod:O.body},[R,D]=await $.seal(z);if(D!==0)return D;if(!R)return 12;let w=$Z(R);if(W.length>0&&N+w>Z){let F=await U();if(F!==0)return F}if(W.push(R),G.push(M),N+=w,N>=Z){let F=await U();if(F!==0)return F}}return U()}async function BJ({conn:$,store:J,enclave:Q,host:I,crypto:V,maxPullBytes:Z,onProgress:X},Y){let K=Z??EJ,W=await J.downloads.list(),G=Array.from(W).filter((R)=>R.host===I.label);if(G.length<1)return 15;let N=G.length,U=0;if(X)X({phase:"pull",host:I.label,done:0,total:N});let M=[],O=0,z=async()=>{if(M.length<1)return 0;let R=M.length,D=await QZ($,J,Q,I.label,V,M,Y);if(M=[],O=0,D===0){if(U+=R,X)X({phase:"pull",host:I.label,done:U,total:N}),X({phase:"apply",host:I.label,done:U,total:N})}return D};for(let R of G){let D=R.head.len;if(M.length>0&&O+D>K){let w=await z();if(w!==0)return w}if(M.push(R),O+=D,O>=K){let w=await z();if(w!==0)return w}}return z()}function MI({head:$,body:J}){return{eid:$.eid,...$.off!==0?{off:$.off}:{},...$.ctr!==0?{ctr:$.ctr}:{},body:J,apld:!1}}async function qI($,{conn:J,store:Q,enclave:I,host:V,crypto:Z,clock:X,maxPullBytes:Y,maxPushBytes:K,onProgress:W,peekProgressEvery:G},N,U){let M=V.label,O=await J.keys(),z=new h($),[R,D]=z.readStructs(B$);if(D!==0){console.error("Failed decoding notif",L[D]);return}let w=!1,A=(await Q.hosts.get(M))?.lastSeq,S=[],y=[];for(let H of R){let[g,p]=await LJ({seq:H.seq,headCph:H.headCph},O,I,Z);if(p!==0){console.error("Failed decrypting notif",L[p]);continue}let r=await Z.blake3(g.headEnc);if(await Q.messages.has(r))continue;let o=new h(g.headEnc),[C,P]=o.readStruct(R0);if(P!==0){console.error("Failed to parse head",L[P]);continue}if(!H.bodyCph&&C.len>0){y.push(H.seq);let _={seq:H.seq,host:M,kdm:g.kdm,head:C};await Q.downloads.enq([_])}else S.push({...g,head:C,bodyCph:H.bodyCph,headEncHash:r});if(A===void 0||H.seq!==A+1)console.log("out of seq",H.seq,A),w=!0;else A=H.seq}if(A!==void 0)await Q.hosts.touch(V.label,A);let f=[],B=[];for(let H of S){let g=await I.deriveFromKDM(H.kdm),[p,r]=await RJ(H.headEnc,H.bodyCph,g,Z);if(r!==0){console.error("Failed to open body",L[r]);continue}let o={head:H.head,body:p.bod},C=MI(o),P={key:H.headEncHash,data:C};B.push(P),f.push(o)}let m=await Q.messages.add(B),u=await N(f,{enqueueUpload:!1,triggerUpload:!1});if(W&&f.length>0)W({phase:"apply",host:V.label,done:f.length,total:f.length});for(let H=0;H<u.length;H++){let g=m[H];if(g!==0&&g!==15)console.error("ERR storing",L[g],"for message",H);let p=u[H];if(p!==0&&p!==15)console.error("ERR applying",L[p],"for message",H)}if(w)U();else await BJ({conn:J,store:Q,enclave:I,host:V,crypto:Z,clock:X,maxPullBytes:Y,maxPushBytes:K,onProgress:W,peekProgressEvery:G},N)}class r0{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;syncRuns=new y$;applyChain=Promise.resolve();clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=R$;lastProgress=Q$;scheduledSync;constructor($,J,Q,I,V,Z=!0,X=_J,Y=EJ,K){this.clock=$;this.state=J;this.store=Q;this.transport=I;this.crypto=V;this.forceSkewHandlingByDefault=Z;this.onScheduleSync=K;this.maxPushBytes=X,this.maxPullBytes=Y,this.clientState=new A0(()=>this.getClientState()),this.xferState=new A0(()=>this.getXferState()),this.scheduledSync=new H$(b$,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(W){console.error("Debounced sync failed:",W)}})}emitProgress=($)=>{this.lastProgress=$,this.xferState.emit()};async setSeed($){await this.store.seed.save($),this.clientState.emit()}async getClientState(){let{store:$,connections:J}=this,Q=await $.seed.load(),I=await $.hosts.list(),V=!1;for(let Z of J.values())if(Z.isConnected()){V=!0;break}return{hasSeed:Q!==void 0,hasHost:Array.from(I).length>0,connected:V}}async getXferState(){let{uploads:$,downloads:J}=this.store,Q=await $.count();return{numDownloads:await J.count(),numUploads:Q,progress:this.lastProgress}}apply=async($,J={enqueueUpload:!0,triggerUpload:!0})=>{let Q=[],I=[];for(let{head:Z,body:X}of $){let Y=new l;Y.writeStruct(R0,Z);let K=Y.result(),W=await this.crypto.blake3(K),G={eid:Z.eid,...Z.off!==0?{off:Z.off}:{},...Z.ctr!==0?{ctr:Z.ctr}:{},body:X,apld:!1};Q.push(W),I.push({key:W,data:G})}await this.store.messages.add(I);let V=await this.applyHashes(Q);if(J.enqueueUpload){let Z=[];for(let X=0;X<Q.length;X++){let Y=V[X];if(Y===0||Y===15)Z.push(Q[X])}if(Z.length>0){let X=await this.store.hosts.list();for(let Y of X)await this.store.uploads.enq(Y.label,Z);this.xferState.emit()}}if(J.triggerUpload)this.scheduleSync();return V};enqueueApplyJob($){let J=this.applyChain.then($,$);return this.applyChain=J.then(()=>{return},()=>{return}),J}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let $=await this.store.messages.listUnapplied();if($.length<1)return[];return this.applyStored($)}applyHashes=($)=>{return this.enqueueApplyJob(async()=>{let J=[];for(let V of $){let Z=await this.store.messages.get(V);if(Z)J.push(Z)}let Q=await this.applyStored(J),I=new Map;for(let V=0;V<J.length;V++)I.set(d(J[V].hash),Q[V]??12);return $.map((V)=>I.get(d(V))??13)})};async applyStored($){if($.length<1)return[];let J=$.map((V)=>({...V.head,bod:V.body})),Q=await this.state.apply(J),I=[];for(let V=0;V<$.length;V++){let Z=Q[V];if(Z===0||Z===15)I.push($[V].hash)}if(I.length>0)await this.store.messages.markApplied(I);return Q}async insertRaw($){let{clock:J,crypto:Q}=this,[I,V]=await GI({now:J.now(),bod:$,crypto:Q});if(V!==0)return q(V);return await this.apply([{head:I,body:$}]),j(I)}async upsertRaw($,J,Q=!1){let{clock:I,crypto:V,store:Z}=this,X=I.now(),Y=await Z.messages.last($);if(Y){let M=new h($),[O,z]=M.readStruct(q0);if(z!==0)return q(z);if(O.ts.getTime()+Y.head.off>X.getTime()){if(Q===!1)return q(4);let D=Y.head.off+1,w=Y.head.ctr+1,F={eid:$,off:D,ctr:w,len:0},S=(await this.apply([{head:F,body:void 0}]))[0];if(S!==0)return q(S);if(J===void 0)return j(F);let[y,f]=J$({id:O.id,ts:X});if(f!==0)return q(f);let B={now:X,eid:y,ctr:0,bod:J,crypto:V},[m,u]=await v$(B);if(u!==0)return q(u);let g=(await this.apply([{head:m,body:J}]))[0];if(g!==0)return q(g);return j(m)}}let K=(Y?.head.ctr??-1)+1,[W,G]=await v$({now:X,eid:$,ctr:K,bod:J,crypto:V});if(G!==0)return q(G);let U=(await this.apply([{head:W,body:J}]))[0];if(U!==0)return q(U);return j(W)}async insert($){let{body:J,type:Q,gid:I,pid:V}=$,X=S$({body:J,type:Q,gid:I,pid:V});return this.insertRaw(X)}async upsert($,J=this.forceSkewHandlingByDefault){let{eid:Q,body:I,type:V,gid:Z,pid:X}=$;if(Q===void 0)return this.insert($);let K=S$({body:I,type:V,gid:Z,pid:X});return this.upsertRaw(Q,K,J)}async delete($){return this.upsertRaw($,void 0,!0)}async genEID($){let{clock:J,crypto:Q}=this,I=J.now();if($!==void 0)return J$({id:$,ts:I});let V=await Q.genRandomBytes(8);return J$({id:V,ts:I})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{clock:$,connections:J,crypto:Q,store:I}=this,V=await I.seed.load();if(!V)return 22;await this.drainApplyQueue();for(let[Z,X]of J){let Y=await I.hosts.get(Z);if(!Y)continue;let K={conn:X,store:I,enclave:V,clock:$,host:Y,crypto:Q,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},W=await WI(K);if(W!==0)return console.error(`Failed to peek: ${W}`),W;this.xferState.emit();let G=await NI(K);if(G!==0)return console.error(`Failed to push: ${G}`),G;this.xferState.emit();let N=await BJ(K,this.apply.bind(this));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=Q$,this.clientState.emit(),this.xferState.emit()}import=async($,J)=>{let{crypto:Q,store:I}=this,V=J?.onProgress,Z=await I.seed.load();if(!Z)return 22;console.time("import: decoding file...");let X=await $.bytes(),[Y,K]=await KI(X,Q,Z);if(K!==0)return K;console.timeEnd("import: decoding file...");let W=0;while(W<Y.length){let G=0,N=0,U=W;for(let z=W;z<Y.length&&N<100&&G<102400;z++)G+=Y[z].head.len,N++,U=z+1;let M=Y.slice(W,U);console.time(`import: applying [${W}, ${U}]`);let O=await this.apply(M,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${W}, ${U}]`);for(let z=0;z<M.length;z++){let R=O[z];if(R!==0&&R!==15)console.warn(`failed to import msg ${W+z}: ${L[R]}`)}if(V)queueMicrotask(()=>V(U,Y.length,0));this.emitProgress({phase:"import",done:U,total:Y.length}),W=U}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:$,store:J}=this,Q=await J.seed.load();if(!Q)return q(22);let I=await J.messages.list();return YI("export",0,I,$,Q)}async export($){let[J,Q]=await this.exportBytes();if(Q!==0)return Q;if(!J)return 12;let I=new Blob([J.slice()]);return u$(I,$),0}async link($,J=!0){if(await this.store.hosts.add($),this.clientState.emit(),J){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($,J=!0,Q=!0)=>{let{clock:I,connections:V,crypto:Z,store:X,transport:Y}=this,K=V.get($.label);if(K){if(K.isConnected())return;try{K.closeListener()}catch{}V.delete($.label)}let W=await X.seed.load();if(!W)return;console.info(`Connecting to ${$.handle} (${$.label})`);let G=new m$(W,Z,$,I,Y($),(N)=>X.hosts.set($.label,N));if(await G.register(),J)await G.listen(async(N)=>{let U={conn:G,store:X,enclave:W,host:$,crypto:Z,clock:I,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return qI(N,U,this.apply,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(V.set($.label,G),this.clientState.emit(),Q)this.scheduleSync()};async connect($=!0,J=!0){let{connectToHost:Q,scheduleSync:I,store:V}=this;if(!await V.seed.load())return;await this.drainApplyQueue();let X=await V.hosts.list();for(let Y of X)await Q(Y,$,!1);if(J)I()}disconnect=async()=>{for(let $ of this.connections.values())try{$.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var n0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function i$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function fJ($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function I0($,...J){if(!fJ($))throw Error("Uint8Array expected");if(J.length>0&&!J.includes($.length))throw Error("Uint8Array expected of length "+J+", got length="+$.length)}function xJ($,J=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(J&&$.finished)throw Error("Hash#digest() has already been called")}function UI($,J){I0($);let Q=J.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function gJ($){if(typeof $!=="boolean")throw Error(`boolean expected, not ${$}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var _0=($)=>new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4));var IZ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!IZ)throw Error("Non little-endian hardware is not supported");function VZ($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function p$($){if(typeof $==="string")$=VZ($);else if(fJ($))$=c$($);else throw Error("Uint8Array expected, got "+typeof $);return $}function zI($,J){if(J==null||typeof J!=="object")throw Error("options must be defined");return Object.assign($,J)}function OI($,J){if($.length!==J.length)return!1;let Q=0;for(let I=0;I<$.length;I++)Q|=$[I]^J[I];return Q===0}var HI=($,J)=>{function Q(I,...V){if(I0(I),$.nonceLength!==void 0){let G=V[0];if(!G)throw Error("nonce / iv required");if($.varSizeNonce)I0(G);else I0(G,$.nonceLength)}let Z=$.tagLength;if(Z&&V[1]!==void 0)I0(V[1]);let X=J(I,...V),Y=(G,N)=>{if(N!==void 0){if(G!==2)throw Error("cipher output not supported");I0(N)}},K=!1;return{encrypt(G,N){if(K)throw Error("cannot encrypt() twice with same key + nonce");return K=!0,I0(G),Y(X.encrypt.length,N),X.encrypt(G,N)},decrypt(G,N){if(I0(G),Z&&G.length<Z)throw Error("invalid ciphertext length: smaller than tagLength="+Z);return Y(X.decrypt.length,N),X.decrypt(G,N)}}}return Object.assign(Q,$),Q};function mJ($,J,Q=!0){if(J===void 0)return new Uint8Array($);if(J.length!==$)throw Error("invalid output length, expected "+$+", got: "+J.length);if(Q&&!ZZ(J))throw Error("invalid output, must be aligned");return J}function ZZ($){return $.byteOffset%4===0}function c$($){return Uint8Array.from($)}function P0(...$){for(let J=0;J<$.length;J++)$[J].fill(0)}function l$($=32){if(n0&&typeof n0.getRandomValues==="function")return n0.getRandomValues(new Uint8Array($));if(n0&&typeof n0.randomBytes==="function")return n0.randomBytes($);throw Error("crypto.getRandomValues must be defined")}var CI=($)=>Uint8Array.from($.split("").map((J)=>J.charCodeAt(0))),XZ=CI("expand 16-byte k"),YZ=CI("expand 32-byte k"),KZ=_0(XZ),GZ=_0(YZ);function k($,J){return $<<J|$>>>32-J}function vJ($){return $.byteOffset%4===0}var r$=64,WZ=16,wI=4294967295,RI=new Uint32Array;function NZ($,J,Q,I,V,Z,X,Y){let K=V.length,W=new Uint8Array(r$),G=_0(W),N=vJ(V)&&vJ(Z),U=N?_0(V):RI,M=N?_0(Z):RI;for(let O=0;O<K;X++){if($(J,Q,I,G,X,Y),X>=wI)throw Error("arx: counter overflow");let z=Math.min(r$,K-O);if(N&&z===r$){let R=O/4;if(O%4!==0)throw Error("arx: invalid block position");for(let D=0,w;D<WZ;D++)w=R+D,M[w]=U[w]^G[D];O+=r$;continue}for(let R=0,D;R<z;R++)D=O+R,Z[D]=V[D]^W[R];O+=z}}function TI($,J){let{allowShortKeys:Q,extendNonceFn:I,counterLength:V,counterRight:Z,rounds:X}=zI({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},J);if(typeof $!=="function")throw Error("core must be a function");return i$(V),i$(X),gJ(Z),gJ(Q),(Y,K,W,G,N=0)=>{I0(Y),I0(K),I0(W);let U=W.length;if(G===void 0)G=new Uint8Array(U);if(I0(G),i$(N),N<0||N>=wI)throw Error("arx: counter overflow");if(G.length<U)throw Error(`arx: output (${G.length}) is shorter than data (${U})`);let M=[],O=Y.length,z,R;if(O===32)M.push(z=c$(Y)),R=GZ;else if(O===16&&Q)z=new Uint8Array(32),z.set(Y),z.set(Y,16),R=KZ,M.push(z);else throw Error(`arx: invalid 32-byte key, got length=${O}`);if(!vJ(K))M.push(K=c$(K));let D=_0(z);if(I){if(K.length!==24)throw Error("arx: extended nonce must be 24 bytes");I(R,D,_0(K.subarray(0,16)),D),K=K.subarray(16)}let w=16-V;if(w!==K.length)throw Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){let A=new Uint8Array(12);A.set(K,Z?0:12-K.length),K=A,M.push(K)}let F=_0(K);return NZ($,R,D,F,W,G,N,X),P0(...M),G}}var X0=($,J)=>$[J++]&255|($[J++]&255)<<8;class DI{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,$=p$($),I0($,32);let J=X0($,0),Q=X0($,2),I=X0($,4),V=X0($,6),Z=X0($,8),X=X0($,10),Y=X0($,12),K=X0($,14);this.r[0]=J&8191,this.r[1]=(J>>>13|Q<<3)&8191,this.r[2]=(Q>>>10|I<<6)&7939,this.r[3]=(I>>>7|V<<9)&8191,this.r[4]=(V>>>4|Z<<12)&255,this.r[5]=Z>>>1&8190,this.r[6]=(Z>>>14|X<<2)&8191,this.r[7]=(X>>>11|Y<<5)&8065,this.r[8]=(Y>>>8|K<<8)&8191,this.r[9]=K>>>5&127;for(let W=0;W<8;W++)this.pad[W]=X0($,16+2*W)}process($,J,Q=!1){let I=Q?0:2048,{h:V,r:Z}=this,X=Z[0],Y=Z[1],K=Z[2],W=Z[3],G=Z[4],N=Z[5],U=Z[6],M=Z[7],O=Z[8],z=Z[9],R=X0($,J+0),D=X0($,J+2),w=X0($,J+4),F=X0($,J+6),A=X0($,J+8),S=X0($,J+10),y=X0($,J+12),f=X0($,J+14),B=V[0]+(R&8191),m=V[1]+((R>>>13|D<<3)&8191),u=V[2]+((D>>>10|w<<6)&8191),H=V[3]+((w>>>7|F<<9)&8191),g=V[4]+((F>>>4|A<<12)&8191),p=V[5]+(A>>>1&8191),r=V[6]+((A>>>14|S<<2)&8191),o=V[7]+((S>>>11|y<<5)&8191),C=V[8]+((y>>>8|f<<8)&8191),P=V[9]+(f>>>5|I),T=0,_=T+B*X+m*(5*z)+u*(5*O)+H*(5*M)+g*(5*U);T=_>>>13,_&=8191,_+=p*(5*N)+r*(5*G)+o*(5*W)+C*(5*K)+P*(5*Y),T+=_>>>13,_&=8191;let v=T+B*Y+m*X+u*(5*z)+H*(5*O)+g*(5*M);T=v>>>13,v&=8191,v+=p*(5*U)+r*(5*N)+o*(5*G)+C*(5*W)+P*(5*K),T+=v>>>13,v&=8191;let x=T+B*K+m*Y+u*X+H*(5*z)+g*(5*O);T=x>>>13,x&=8191,x+=p*(5*M)+r*(5*U)+o*(5*N)+C*(5*G)+P*(5*W),T+=x>>>13,x&=8191;let E=T+B*W+m*K+u*Y+H*X+g*(5*z);T=E>>>13,E&=8191,E+=p*(5*O)+r*(5*M)+o*(5*U)+C*(5*N)+P*(5*G),T+=E>>>13,E&=8191;let i=T+B*G+m*W+u*K+H*Y+g*X;T=i>>>13,i&=8191,i+=p*(5*z)+r*(5*O)+o*(5*M)+C*(5*U)+P*(5*N),T+=i>>>13,i&=8191;let c=T+B*N+m*G+u*W+H*K+g*Y;T=c>>>13,c&=8191,c+=p*X+r*(5*z)+o*(5*O)+C*(5*M)+P*(5*U),T+=c>>>13,c&=8191;let n=T+B*U+m*N+u*G+H*W+g*K;T=n>>>13,n&=8191,n+=p*Y+r*X+o*(5*z)+C*(5*O)+P*(5*M),T+=n>>>13,n&=8191;let a=T+B*M+m*U+u*N+H*G+g*W;T=a>>>13,a&=8191,a+=p*K+r*Y+o*X+C*(5*z)+P*(5*O),T+=a>>>13,a&=8191;let Q0=T+B*O+m*M+u*U+H*N+g*G;T=Q0>>>13,Q0&=8191,Q0+=p*W+r*K+o*Y+C*X+P*(5*z),T+=Q0>>>13,Q0&=8191;let V0=T+B*z+m*O+u*M+H*U+g*N;T=V0>>>13,V0&=8191,V0+=p*G+r*W+o*K+C*Y+P*X,T+=V0>>>13,V0&=8191,T=(T<<2)+T|0,T=T+_|0,_=T&8191,T=T>>>13,v+=T,V[0]=_,V[1]=v,V[2]=x,V[3]=E,V[4]=i,V[5]=c,V[6]=n,V[7]=a,V[8]=Q0,V[9]=V0}finalize(){let{h:$,pad:J}=this,Q=new Uint16Array(10),I=$[1]>>>13;$[1]&=8191;for(let X=2;X<10;X++)$[X]+=I,I=$[X]>>>13,$[X]&=8191;$[0]+=I*5,I=$[0]>>>13,$[0]&=8191,$[1]+=I,I=$[1]>>>13,$[1]&=8191,$[2]+=I,Q[0]=$[0]+5,I=Q[0]>>>13,Q[0]&=8191;for(let X=1;X<10;X++)Q[X]=$[X]+I,I=Q[X]>>>13,Q[X]&=8191;Q[9]-=8192;let V=(I^1)-1;for(let X=0;X<10;X++)Q[X]&=V;V=~V;for(let X=0;X<10;X++)$[X]=$[X]&V|Q[X];$[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 Z=$[0]+J[0];$[0]=Z&65535;for(let X=1;X<8;X++)Z=($[X]+J[X]|0)+(Z>>>16)|0,$[X]=Z&65535;P0(Q)}update($){xJ(this);let{buffer:J,blockLen:Q}=this;$=p$($);let I=$.length;for(let V=0;V<I;){let Z=Math.min(Q-this.pos,I-V);if(Z===Q){for(;Q<=I-V;V+=Q)this.process($,V);continue}if(J.set($.subarray(V,V+Z),this.pos),this.pos+=Z,V+=Z,this.pos===Q)this.process(J,0,!1),this.pos=0}return this}destroy(){P0(this.h,this.r,this.buffer,this.pad)}digestInto($){xJ(this),UI($,this),this.finished=!0;let{buffer:J,h:Q}=this,{pos:I}=this;if(I){J[I++]=1;for(;I<16;I++)J[I]=0;this.process(J,0,!0)}this.finalize();let V=0;for(let Z=0;Z<8;Z++)$[V++]=Q[Z]>>>0,$[V++]=Q[Z]>>>8;return $}digest(){let{buffer:$,outputLen:J}=this;this.digestInto($);let Q=$.slice(0,J);return this.destroy(),Q}}function MZ($){let J=(I,V)=>$(V).update(p$(I)).digest(),Q=$(new Uint8Array(32));return J.outputLen=Q.outputLen,J.blockLen=Q.blockLen,J.create=(I)=>$(I),J}var yJ=MZ(($)=>new DI($));function qZ($,J,Q,I,V,Z=20){let X=$[0],Y=J[0],K=J[1],W=J[2],G=J[3],N=$[1],U=Q[0],M=Q[1],O=V,z=0,R=$[2],D=J[4],w=J[5],F=J[6],A=J[7],S=$[3],y=X,f=Y,B=K,m=W,u=G,H=N,g=U,p=M,r=O,o=z,C=R,P=D,T=w,_=F,v=A,x=S;for(let i=0;i<Z;i+=2)u^=k(y+T|0,7),r^=k(u+y|0,9),T^=k(r+u|0,13),y^=k(T+r|0,18),o^=k(H+f|0,7),_^=k(o+H|0,9),f^=k(_+o|0,13),H^=k(f+_|0,18),v^=k(C+g|0,7),B^=k(v+C|0,9),g^=k(B+v|0,13),C^=k(g+B|0,18),m^=k(x+P|0,7),p^=k(m+x|0,9),P^=k(p+m|0,13),x^=k(P+p|0,18),f^=k(y+m|0,7),B^=k(f+y|0,9),m^=k(B+f|0,13),y^=k(m+B|0,18),g^=k(H+u|0,7),p^=k(g+H|0,9),u^=k(p+g|0,13),H^=k(u+p|0,18),P^=k(C+o|0,7),r^=k(P+C|0,9),o^=k(r+P|0,13),C^=k(o+r|0,18),T^=k(x+v|0,7),_^=k(T+x|0,9),v^=k(_+T|0,13),x^=k(v+_|0,18);let E=0;I[E++]=X+y|0,I[E++]=Y+f|0,I[E++]=K+B|0,I[E++]=W+m|0,I[E++]=G+u|0,I[E++]=N+H|0,I[E++]=U+g|0,I[E++]=M+p|0,I[E++]=O+r|0,I[E++]=z+o|0,I[E++]=R+C|0,I[E++]=D+P|0,I[E++]=w+T|0,I[E++]=F+_|0,I[E++]=A+v|0,I[E++]=S+x|0}function UZ($,J,Q,I){let V=$[0],Z=J[0],X=J[1],Y=J[2],K=J[3],W=$[1],G=Q[0],N=Q[1],U=Q[2],M=Q[3],O=$[2],z=J[4],R=J[5],D=J[6],w=J[7],F=$[3];for(let S=0;S<20;S+=2)K^=k(V+R|0,7),U^=k(K+V|0,9),R^=k(U+K|0,13),V^=k(R+U|0,18),M^=k(W+Z|0,7),D^=k(M+W|0,9),Z^=k(D+M|0,13),W^=k(Z+D|0,18),w^=k(O+G|0,7),X^=k(w+O|0,9),G^=k(X+w|0,13),O^=k(G+X|0,18),Y^=k(F+z|0,7),N^=k(Y+F|0,9),z^=k(N+Y|0,13),F^=k(z+N|0,18),Z^=k(V+Y|0,7),X^=k(Z+V|0,9),Y^=k(X+Z|0,13),V^=k(Y+X|0,18),G^=k(W+K|0,7),N^=k(G+W|0,9),K^=k(N+G|0,13),W^=k(K+N|0,18),z^=k(O+M|0,7),U^=k(z+O|0,9),M^=k(U+z|0,13),O^=k(M+U|0,18),R^=k(F+w|0,7),D^=k(R+F|0,9),w^=k(D+R|0,13),F^=k(w+D|0,18);let A=0;I[A++]=V,I[A++]=W,I[A++]=O,I[A++]=F,I[A++]=G,I[A++]=N,I[A++]=U,I[A++]=M}var bJ=TI(qZ,{counterRight:!0,extendNonceFn:UZ}),uJ=HI({blockSize:64,nonceLength:24,tagLength:16},($,J)=>{return{encrypt(Q,I){I=mJ(Q.length+32,I,!1);let V=I.subarray(0,32),Z=I.subarray(32);I.set(Q,32),P0(V),bJ($,J,I,I);let X=yJ(Z,V);return I.set(X,16),P0(I.subarray(0,16),X),I.subarray(16)},decrypt(Q,I){I0(Q),I=mJ(Q.length+32,I,!1);let V=I.subarray(0,32),Z=I.subarray(32,48),X=I.subarray(48);I.set(Q,32),P0(V);let Y=bJ($,J,V,V),K=yJ(X,Y);if(!OI(Z,K))throw Error("invalid tag");return bJ($,J,I.subarray(16),I.subarray(16)),P0(V,Z,K),X}}});function zZ($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function iJ($,...J){if(!zZ($))throw Error("Uint8Array expected");if(J.length>0&&!J.includes($.length))throw Error("Uint8Array expected of length "+J+", got length="+$.length)}function pJ($,J=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(J&&$.finished)throw Error("Hash#digest() has already been called")}function FI($,J){iJ($);let Q=J.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}var h0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */var n$=($)=>new DataView($.buffer,$.byteOffset,$.byteLength);function AI($){if(typeof $!=="string")throw Error("utf8ToBytes expected string, got "+typeof $);return new Uint8Array(new TextEncoder().encode($))}function cJ($){if(typeof $==="string")$=AI($);return iJ($),$}class lJ{clone(){return this._cloneInto()}}function PI($){let J=(I)=>$().update(cJ(I)).digest(),Q=$();return J.outputLen=Q.outputLen,J.blockLen=Q.blockLen,J.create=()=>$(),J}function jI($=32){if(h0&&typeof h0.getRandomValues==="function")return h0.getRandomValues(new Uint8Array($));if(h0&&typeof h0.randomBytes==="function")return h0.randomBytes($);throw Error("crypto.getRandomValues must be defined")}function OZ($,J,Q,I){if(typeof $.setBigUint64==="function")return $.setBigUint64(J,Q,I);let V=BigInt(32),Z=BigInt(4294967295),X=Number(Q>>V&Z),Y=Number(Q&Z),K=I?4:0,W=I?0:4;$.setUint32(J+K,X,I),$.setUint32(J+W,Y,I)}class rJ extends lJ{constructor($,J,Q,I){super();this.blockLen=$,this.outputLen=J,this.padOffset=Q,this.isLE=I,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array($),this.view=n$(this.buffer)}update($){pJ(this);let{view:J,buffer:Q,blockLen:I}=this;$=cJ($);let V=$.length;for(let Z=0;Z<V;){let X=Math.min(I-this.pos,V-Z);if(X===I){let Y=n$($);for(;I<=V-Z;Z+=I)this.process(Y,Z);continue}if(Q.set($.subarray(Z,Z+X),this.pos),this.pos+=X,Z+=X,this.pos===I)this.process(J,0),this.pos=0}return this.length+=$.length,this.roundClean(),this}digestInto($){pJ(this),FI($,this),this.finished=!0;let{buffer:J,view:Q,blockLen:I,isLE:V}=this,{pos:Z}=this;if(J[Z++]=128,this.buffer.subarray(Z).fill(0),this.padOffset>I-Z)this.process(Q,0),Z=0;for(let G=Z;G<I;G++)J[G]=0;OZ(Q,I-8,BigInt(this.length*8),V),this.process(Q,0);let X=n$($),Y=this.outputLen;if(Y%4)throw Error("_sha2: outputLen should be aligned to 32bit");let K=Y/4,W=this.get();if(K>W.length)throw Error("_sha2: outputLen bigger than state");for(let G=0;G<K;G++)X.setUint32(4*G,W[G],V)}digest(){let{buffer:$,outputLen:J}=this;this.digestInto($);let Q=$.slice(0,J);return this.destroy(),Q}_cloneInto($){$||($=new this.constructor),$.set(...this.get());let{blockLen:J,buffer:Q,length:I,finished:V,destroyed:Z,pos:X}=this;if($.length=I,$.pos=X,$.finished=V,$.destroyed=Z,I%J)$.buffer.set(Q);return $}}var h$=BigInt(4294967295),nJ=BigInt(32);function kI($,J=!1){if(J)return{h:Number($&h$),l:Number($>>nJ&h$)};return{h:Number($>>nJ&h$)|0,l:Number($&h$)|0}}function HZ($,J=!1){let Q=new Uint32Array($.length),I=new Uint32Array($.length);for(let V=0;V<$.length;V++){let{h:Z,l:X}=kI($[V],J);[Q[V],I[V]]=[Z,X]}return[Q,I]}var RZ=($,J)=>BigInt($>>>0)<<nJ|BigInt(J>>>0),CZ=($,J,Q)=>$>>>Q,wZ=($,J,Q)=>$<<32-Q|J>>>Q,TZ=($,J,Q)=>$>>>Q|J<<32-Q,DZ=($,J,Q)=>$<<32-Q|J>>>Q,FZ=($,J,Q)=>$<<64-Q|J>>>Q-32,AZ=($,J,Q)=>$>>>Q-32|J<<64-Q,PZ=($,J)=>J,jZ=($,J)=>$,kZ=($,J,Q)=>$<<Q|J>>>32-Q,SZ=($,J,Q)=>J<<Q|$>>>32-Q,LZ=($,J,Q)=>J<<Q-32|$>>>64-Q,_Z=($,J,Q)=>$<<Q-32|J>>>64-Q;function EZ($,J,Q,I){let V=(J>>>0)+(I>>>0);return{h:$+Q+(V/4294967296|0)|0,l:V|0}}var BZ=($,J,Q)=>($>>>0)+(J>>>0)+(Q>>>0),fZ=($,J,Q,I)=>J+Q+I+($/4294967296|0)|0,xZ=($,J,Q,I)=>($>>>0)+(J>>>0)+(Q>>>0)+(I>>>0),gZ=($,J,Q,I,V)=>J+Q+I+V+($/4294967296|0)|0,mZ=($,J,Q,I,V)=>($>>>0)+(J>>>0)+(Q>>>0)+(I>>>0)+(V>>>0),vZ=($,J,Q,I,V,Z)=>J+Q+I+V+Z+($/4294967296|0)|0;var yZ={fromBig:kI,split:HZ,toBig:RZ,shrSH:CZ,shrSL:wZ,rotrSH:TZ,rotrSL:DZ,rotrBH:FZ,rotrBL:AZ,rotr32H:PZ,rotr32L:jZ,rotlSH:kZ,rotlSL:SZ,rotlBH:LZ,rotlBL:_Z,add:EZ,add3L:BZ,add3H:fZ,add4L:xZ,add4H:gZ,add5H:vZ,add5L:mZ},b=yZ;var[bZ,uZ]=(()=>b.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(($)=>BigInt($))))(),p0=new Uint32Array(80),c0=new Uint32Array(80);class SI extends rJ{constructor(){super(128,64,16,!1);this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:$,Al:J,Bh:Q,Bl:I,Ch:V,Cl:Z,Dh:X,Dl:Y,Eh:K,El:W,Fh:G,Fl:N,Gh:U,Gl:M,Hh:O,Hl:z}=this;return[$,J,Q,I,V,Z,X,Y,K,W,G,N,U,M,O,z]}set($,J,Q,I,V,Z,X,Y,K,W,G,N,U,M,O,z){this.Ah=$|0,this.Al=J|0,this.Bh=Q|0,this.Bl=I|0,this.Ch=V|0,this.Cl=Z|0,this.Dh=X|0,this.Dl=Y|0,this.Eh=K|0,this.El=W|0,this.Fh=G|0,this.Fl=N|0,this.Gh=U|0,this.Gl=M|0,this.Hh=O|0,this.Hl=z|0}process($,J){for(let w=0;w<16;w++,J+=4)p0[w]=$.getUint32(J),c0[w]=$.getUint32(J+=4);for(let w=16;w<80;w++){let F=p0[w-15]|0,A=c0[w-15]|0,S=b.rotrSH(F,A,1)^b.rotrSH(F,A,8)^b.shrSH(F,A,7),y=b.rotrSL(F,A,1)^b.rotrSL(F,A,8)^b.shrSL(F,A,7),f=p0[w-2]|0,B=c0[w-2]|0,m=b.rotrSH(f,B,19)^b.rotrBH(f,B,61)^b.shrSH(f,B,6),u=b.rotrSL(f,B,19)^b.rotrBL(f,B,61)^b.shrSL(f,B,6),H=b.add4L(y,u,c0[w-7],c0[w-16]),g=b.add4H(H,S,m,p0[w-7],p0[w-16]);p0[w]=g|0,c0[w]=H|0}let{Ah:Q,Al:I,Bh:V,Bl:Z,Ch:X,Cl:Y,Dh:K,Dl:W,Eh:G,El:N,Fh:U,Fl:M,Gh:O,Gl:z,Hh:R,Hl:D}=this;for(let w=0;w<80;w++){let F=b.rotrSH(G,N,14)^b.rotrSH(G,N,18)^b.rotrBH(G,N,41),A=b.rotrSL(G,N,14)^b.rotrSL(G,N,18)^b.rotrBL(G,N,41),S=G&U^~G&O,y=N&M^~N&z,f=b.add5L(D,A,y,uZ[w],c0[w]),B=b.add5H(f,R,F,S,bZ[w],p0[w]),m=f|0,u=b.rotrSH(Q,I,28)^b.rotrBH(Q,I,34)^b.rotrBH(Q,I,39),H=b.rotrSL(Q,I,28)^b.rotrBL(Q,I,34)^b.rotrBL(Q,I,39),g=Q&V^Q&X^V&X,p=I&Z^I&Y^Z&Y;R=O|0,D=z|0,O=U|0,z=M|0,U=G|0,M=N|0,{h:G,l:N}=b.add(K|0,W|0,B|0,m|0),K=X|0,W=Y|0,X=V|0,Y=Z|0,V=Q|0,Z=I|0;let r=b.add3L(m,H,p);Q=b.add3H(r,B,u,g),I=r|0}({h:Q,l:I}=b.add(this.Ah|0,this.Al|0,Q|0,I|0)),{h:V,l:Z}=b.add(this.Bh|0,this.Bl|0,V|0,Z|0),{h:X,l:Y}=b.add(this.Ch|0,this.Cl|0,X|0,Y|0),{h:K,l:W}=b.add(this.Dh|0,this.Dl|0,K|0,W|0),{h:G,l:N}=b.add(this.Eh|0,this.El|0,G|0,N|0),{h:U,l:M}=b.add(this.Fh|0,this.Fl|0,U|0,M|0),{h:O,l:z}=b.add(this.Gh|0,this.Gl|0,O|0,z|0),{h:R,l:D}=b.add(this.Hh|0,this.Hl|0,R|0,D|0),this.set(Q,I,V,Z,X,Y,K,W,G,N,U,M,O,z,R,D)}roundClean(){p0.fill(0),c0.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}var LI=PI(()=>new SI);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var dJ=BigInt(0),EI=BigInt(1),iZ=BigInt(2);function oJ($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function aJ($){if(!oJ($))throw Error("Uint8Array expected")}function d$($,J){if(typeof J!=="boolean")throw Error($+" boolean expected, got "+J)}var pZ=Array.from({length:256},($,J)=>J.toString(16).padStart(2,"0"));function o$($){aJ($);let J="";for(let Q=0;Q<$.length;Q++)J+=pZ[$[Q]];return J}function BI($){if(typeof $!=="string")throw Error("hex string expected, got "+typeof $);return $===""?dJ:BigInt("0x"+$)}var E0={_0:48,_9:57,A:65,F:70,a:97,f:102};function _I($){if($>=E0._0&&$<=E0._9)return $-E0._0;if($>=E0.A&&$<=E0.F)return $-(E0.A-10);if($>=E0.a&&$<=E0.f)return $-(E0.a-10);return}function fI($){if(typeof $!=="string")throw Error("hex string expected, got "+typeof $);let J=$.length,Q=J/2;if(J%2)throw Error("hex string expected, got unpadded hex of length "+J);let I=new Uint8Array(Q);for(let V=0,Z=0;V<Q;V++,Z+=2){let X=_I($.charCodeAt(Z)),Y=_I($.charCodeAt(Z+1));if(X===void 0||Y===void 0){let K=$[Z]+$[Z+1];throw Error('hex string expected, got non-hex character "'+K+'" at index '+Z)}I[V]=X*16+Y}return I}function xI($){return BI(o$($))}function V$($){return aJ($),BI(o$(Uint8Array.from($).reverse()))}function sJ($,J){return fI($.toString(16).padStart(J*2,"0"))}function C$($,J){return sJ($,J).reverse()}function T0($,J,Q){let I;if(typeof J==="string")try{I=fI(J)}catch(Z){throw Error($+" must be hex string or Uint8Array, cause: "+Z)}else if(oJ(J))I=Uint8Array.from(J);else throw Error($+" must be hex string or Uint8Array");let V=I.length;if(typeof Q==="number"&&V!==Q)throw Error($+" of length "+Q+" expected, got "+V);return I}function tJ(...$){let J=0;for(let I=0;I<$.length;I++){let V=$[I];aJ(V),J+=V.length}let Q=new Uint8Array(J);for(let I=0,V=0;I<$.length;I++){let Z=$[I];Q.set(Z,V),V+=Z.length}return Q}var hJ=($)=>typeof $==="bigint"&&dJ<=$;function cZ($,J,Q){return hJ($)&&hJ(J)&&hJ(Q)&&J<=$&&$<Q}function Z$($,J,Q,I){if(!cZ(J,Q,I))throw Error("expected valid "+$+": "+Q+" <= n < "+I+", got "+J)}function gI($){let J;for(J=0;$>dJ;$>>=EI,J+=1);return J}var mI=($)=>(iZ<<BigInt($-1))-EI;var lZ={bigint:($)=>typeof $==="bigint",function:($)=>typeof $==="function",boolean:($)=>typeof $==="boolean",string:($)=>typeof $==="string",stringOrUint8Array:($)=>typeof $==="string"||oJ($),isSafeInteger:($)=>Number.isSafeInteger($),array:($)=>Array.isArray($),field:($,J)=>J.Fp.isValid($),hash:($)=>typeof $==="function"&&Number.isSafeInteger($.outputLen)};function X$($,J,Q={}){let I=(V,Z,X)=>{let Y=lZ[Z];if(typeof Y!=="function")throw Error("invalid validator function");let K=$[V];if(X&&K===void 0)return;if(!Y(K,$))throw Error("param "+String(V)+" is invalid. Expected "+Z+", got "+K)};for(let[V,Z]of Object.entries(J))I(V,Z,!1);for(let[V,Z]of Object.entries(Q))I(V,Z,!0);return $}function eJ($){let J=new WeakMap;return(Q,...I)=>{let V=J.get(Q);if(V!==void 0)return V;let Z=$(Q,...I);return J.set(Q,Z),Z}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var $0=BigInt(0),s=BigInt(1),d0=BigInt(2),nZ=BigInt(3),$Q=BigInt(4),vI=BigInt(5),yI=BigInt(8),hZ=BigInt(9),dZ=BigInt(16);function t($,J){let Q=$%J;return Q>=$0?Q:J+Q}function oZ($,J,Q){if(J<$0)throw Error("invalid exponent, negatives unsupported");if(Q<=$0)throw Error("invalid modulus");if(Q===s)return $0;let I=s;while(J>$0){if(J&s)I=I*$%Q;$=$*$%Q,J>>=s}return I}function D0($,J,Q){let I=$;while(J-- >$0)I*=I,I%=Q;return I}function bI($,J){if($===$0)throw Error("invert: expected non-zero number");if(J<=$0)throw Error("invert: expected positive modulus, got "+J);let Q=t($,J),I=J,V=$0,Z=s,X=s,Y=$0;while(Q!==$0){let W=I/Q,G=I%Q,N=V-X*W,U=Z-Y*W;I=Q,Q=G,V=X,Z=Y,X=N,Y=U}if(I!==s)throw Error("invert: does not exist");return t(V,J)}function aZ($){let J=($-s)/d0,Q,I,V;for(Q=$-s,I=0;Q%d0===$0;Q/=d0,I++);for(V=d0;V<$&&oZ(V,J,$)!==$-s;V++)if(V>1000)throw Error("Cannot find square root: likely non-prime P");if(I===1){let X=($+s)/$Q;return function(K,W){let G=K.pow(W,X);if(!K.eql(K.sqr(G),W))throw Error("Cannot find square root");return G}}let Z=(Q+s)/d0;return function(Y,K){if(Y.pow(K,J)===Y.neg(Y.ONE))throw Error("Cannot find square root");let W=I,G=Y.pow(Y.mul(Y.ONE,V),Q),N=Y.pow(K,Z),U=Y.pow(K,Q);while(!Y.eql(U,Y.ONE)){if(Y.eql(U,Y.ZERO))return Y.ZERO;let M=1;for(let z=Y.sqr(U);M<W;M++){if(Y.eql(z,Y.ONE))break;z=Y.sqr(z)}let O=Y.pow(G,s<<BigInt(W-M-1));G=Y.sqr(O),N=Y.mul(N,O),U=Y.mul(U,G),W=M}return N}}function sZ($){if($%$Q===nZ){let J=($+s)/$Q;return function(I,V){let Z=I.pow(V,J);if(!I.eql(I.sqr(Z),V))throw Error("Cannot find square root");return Z}}if($%yI===vI){let J=($-vI)/yI;return function(I,V){let Z=I.mul(V,d0),X=I.pow(Z,J),Y=I.mul(V,X),K=I.mul(I.mul(Y,d0),X),W=I.mul(Y,I.sub(K,I.ONE));if(!I.eql(I.sqr(W),V))throw Error("Cannot find square root");return W}}if($%dZ===hZ);return aZ($)}var uI=($,J)=>(t($,J)&s)===s,tZ=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function iI($){let J={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},Q=tZ.reduce((I,V)=>{return I[V]="function",I},J);return X$($,Q)}function eZ($,J,Q){if(Q<$0)throw Error("invalid exponent, negatives unsupported");if(Q===$0)return $.ONE;if(Q===s)return J;let I=$.ONE,V=J;while(Q>$0){if(Q&s)I=$.mul(I,V);V=$.sqr(V),Q>>=s}return I}function $8($,J){let Q=Array(J.length),I=J.reduce((Z,X,Y)=>{if($.is0(X))return Z;return Q[Y]=Z,$.mul(Z,X)},$.ONE),V=$.inv(I);return J.reduceRight((Z,X,Y)=>{if($.is0(X))return Z;return Q[Y]=$.mul(Z,Q[Y]),$.mul(Z,X)},V),Q}function JQ($,J){let Q=J!==void 0?J:$.toString(2).length,I=Math.ceil(Q/8);return{nBitLength:Q,nByteLength:I}}function a$($,J,Q=!1,I={}){if($<=$0)throw Error("invalid field: expected ORDER > 0, got "+$);let{nBitLength:V,nByteLength:Z}=JQ($,J);if(Z>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let X,Y=Object.freeze({ORDER:$,isLE:Q,BITS:V,BYTES:Z,MASK:mI(V),ZERO:$0,ONE:s,create:(K)=>t(K,$),isValid:(K)=>{if(typeof K!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof K);return $0<=K&&K<$},is0:(K)=>K===$0,isOdd:(K)=>(K&s)===s,neg:(K)=>t(-K,$),eql:(K,W)=>K===W,sqr:(K)=>t(K*K,$),add:(K,W)=>t(K+W,$),sub:(K,W)=>t(K-W,$),mul:(K,W)=>t(K*W,$),pow:(K,W)=>eZ(Y,K,W),div:(K,W)=>t(K*bI(W,$),$),sqrN:(K)=>K*K,addN:(K,W)=>K+W,subN:(K,W)=>K-W,mulN:(K,W)=>K*W,inv:(K)=>bI(K,$),sqrt:I.sqrt||((K)=>{if(!X)X=sZ($);return X(Y,K)}),invertBatch:(K)=>$8(Y,K),cmov:(K,W,G)=>G?W:K,toBytes:(K)=>Q?C$(K,Z):sJ(K,Z),fromBytes:(K)=>{if(K.length!==Z)throw Error("Field.fromBytes: expected "+Z+" bytes, got "+K.length);return Q?V$(K):xI(K)}});return Object.freeze(Y)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var pI=BigInt(0),s$=BigInt(1);function QQ($,J){let Q=J.negate();return $?Q:J}function cI($,J){if(!Number.isSafeInteger($)||$<=0||$>J)throw Error("invalid window size, expected [1.."+J+"], got W="+$)}function IQ($,J){cI($,J);let Q=Math.ceil(J/$)+1,I=2**($-1);return{windows:Q,windowSize:I}}function J8($,J){if(!Array.isArray($))throw Error("array expected");$.forEach((Q,I)=>{if(!(Q instanceof J))throw Error("invalid point at index "+I)})}function Q8($,J){if(!Array.isArray($))throw Error("array of scalars expected");$.forEach((Q,I)=>{if(!J.isValid(Q))throw Error("invalid scalar at index "+I)})}var VQ=new WeakMap,lI=new WeakMap;function ZQ($){return lI.get($)||1}function rI($,J){return{constTimeNegate:QQ,hasPrecomputes(Q){return ZQ(Q)!==1},unsafeLadder(Q,I,V=$.ZERO){let Z=Q;while(I>pI){if(I&s$)V=V.add(Z);Z=Z.double(),I>>=s$}return V},precomputeWindow(Q,I){let{windows:V,windowSize:Z}=IQ(I,J),X=[],Y=Q,K=Y;for(let W=0;W<V;W++){K=Y,X.push(K);for(let G=1;G<Z;G++)K=K.add(Y),X.push(K);Y=K.double()}return X},wNAF(Q,I,V){let{windows:Z,windowSize:X}=IQ(Q,J),Y=$.ZERO,K=$.BASE,W=BigInt(2**Q-1),G=2**Q,N=BigInt(Q);for(let U=0;U<Z;U++){let M=U*X,O=Number(V&W);if(V>>=N,O>X)O-=G,V+=s$;let z=M,R=M+Math.abs(O)-1,D=U%2!==0,w=O<0;if(O===0)K=K.add(QQ(D,I[z]));else Y=Y.add(QQ(w,I[R]))}return{p:Y,f:K}},wNAFUnsafe(Q,I,V,Z=$.ZERO){let{windows:X,windowSize:Y}=IQ(Q,J),K=BigInt(2**Q-1),W=2**Q,G=BigInt(Q);for(let N=0;N<X;N++){let U=N*Y;if(V===pI)break;let M=Number(V&K);if(V>>=G,M>Y)M-=W,V+=s$;if(M===0)continue;let O=I[U+Math.abs(M)-1];if(M<0)O=O.negate();Z=Z.add(O)}return Z},getPrecomputes(Q,I,V){let Z=VQ.get(I);if(!Z){if(Z=this.precomputeWindow(I,Q),Q!==1)VQ.set(I,V(Z))}return Z},wNAFCached(Q,I,V){let Z=ZQ(Q);return this.wNAF(Z,this.getPrecomputes(Z,Q,V),I)},wNAFCachedUnsafe(Q,I,V,Z){let X=ZQ(Q);if(X===1)return this.unsafeLadder(Q,I,Z);return this.wNAFUnsafe(X,this.getPrecomputes(X,Q,V),I,Z)},setWindowSize(Q,I){cI(I,J),lI.set(Q,I),VQ.delete(Q)}}}function nI($,J,Q,I){if(J8(Q,$),Q8(I,J),Q.length!==I.length)throw Error("arrays of points and scalars must have equal length");let V=$.ZERO,Z=gI(BigInt(Q.length)),X=Z>12?Z-3:Z>4?Z-2:Z?2:1,Y=(1<<X)-1,K=Array(Y+1).fill(V),W=Math.floor((J.BITS-1)/X)*X,G=V;for(let N=W;N>=0;N-=X){K.fill(V);for(let M=0;M<I.length;M++){let O=I[M],z=Number(O>>BigInt(N)&BigInt(Y));K[z]=K[z].add(Q[M])}let U=V;for(let M=K.length-1,O=V;M>0;M--)O=O.add(K[M]),U=U.add(O);if(G=G.add(U),N!==0)for(let M=0;M<X;M++)G=G.double()}return G}function hI($){return iI($.Fp),X$($,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...JQ($.n,$.nBitLength),...$,...{p:$.Fp.ORDER}})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var F0=BigInt(0),N0=BigInt(1),t$=BigInt(2),I8=BigInt(8),V8={zip215:!0};function Z8($){let J=hI($);return X$($,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...J})}function dI($){let J=Z8($),{Fp:Q,n:I,prehash:V,hash:Z,randomBytes:X,nByteLength:Y,h:K}=J,W=t$<<BigInt(Y*8)-N0,G=Q.create,N=a$(J.n,J.nBitLength),U=J.uvRatio||((C,P)=>{try{return{isValid:!0,value:Q.sqrt(C*Q.inv(P))}}catch(T){return{isValid:!1,value:F0}}}),M=J.adjustScalarBytes||((C)=>C),O=J.domain||((C,P,T)=>{if(d$("phflag",T),P.length||T)throw Error("Contexts/pre-hash are not supported");return C});function z(C,P){Z$("coordinate "+C,P,F0,W)}function R(C){if(!(C instanceof F))throw Error("ExtendedPoint expected")}let D=eJ((C,P)=>{let{ex:T,ey:_,ez:v}=C,x=C.is0();if(P==null)P=x?I8:Q.inv(v);let E=G(T*P),i=G(_*P),c=G(v*P);if(x)return{x:F0,y:N0};if(c!==N0)throw Error("invZ was invalid");return{x:E,y:i}}),w=eJ((C)=>{let{a:P,d:T}=J;if(C.is0())throw Error("bad point: ZERO");let{ex:_,ey:v,ez:x,et:E}=C,i=G(_*_),c=G(v*v),n=G(x*x),a=G(n*n),Q0=G(i*P),V0=G(n*G(Q0+c)),M0=G(a+G(T*G(i*c)));if(V0!==M0)throw Error("bad point: equation left != right (1)");let m0=G(_*v),S0=G(x*E);if(m0!==S0)throw Error("bad point: equation left != right (2)");return!0});class F{constructor(C,P,T,_){this.ex=C,this.ey=P,this.ez=T,this.et=_,z("x",C),z("y",P),z("z",T),z("t",_),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(C){if(C instanceof F)throw Error("extended point not allowed");let{x:P,y:T}=C||{};return z("x",P),z("y",T),new F(P,T,N0,G(P*T))}static normalizeZ(C){let P=Q.invertBatch(C.map((T)=>T.ez));return C.map((T,_)=>T.toAffine(P[_])).map(F.fromAffine)}static msm(C,P){return nI(F,N,C,P)}_setWindowSize(C){y.setWindowSize(this,C)}assertValidity(){w(this)}equals(C){R(C);let{ex:P,ey:T,ez:_}=this,{ex:v,ey:x,ez:E}=C,i=G(P*E),c=G(v*_),n=G(T*E),a=G(x*_);return i===c&&n===a}is0(){return this.equals(F.ZERO)}negate(){return new F(G(-this.ex),this.ey,this.ez,G(-this.et))}double(){let{a:C}=J,{ex:P,ey:T,ez:_}=this,v=G(P*P),x=G(T*T),E=G(t$*G(_*_)),i=G(C*v),c=P+T,n=G(G(c*c)-v-x),a=i+x,Q0=a-E,V0=i-x,M0=G(n*Q0),m0=G(a*V0),S0=G(n*V0),A$=G(Q0*a);return new F(M0,m0,A$,S0)}add(C){R(C);let{a:P,d:T}=J,{ex:_,ey:v,ez:x,et:E}=this,{ex:i,ey:c,ez:n,et:a}=C;if(P===BigInt(-1)){let gQ=G((v-_)*(c+i)),mQ=G((v+_)*(c-i)),WJ=G(mQ-gQ);if(WJ===F0)return this.double();let vQ=G(x*t$*a),yQ=G(E*t$*n),bQ=yQ+vQ,uQ=mQ+gQ,iQ=yQ-vQ,TV=G(bQ*WJ),DV=G(uQ*iQ),FV=G(bQ*iQ),AV=G(WJ*uQ);return new F(TV,DV,AV,FV)}let Q0=G(_*i),V0=G(v*c),M0=G(E*T*a),m0=G(x*n),S0=G((_+v)*(i+c)-Q0-V0),A$=m0-M0,fQ=m0+M0,xQ=G(V0-P*Q0),HV=G(S0*A$),RV=G(fQ*xQ),CV=G(S0*xQ),wV=G(A$*fQ);return new F(HV,RV,wV,CV)}subtract(C){return this.add(C.negate())}wNAF(C){return y.wNAFCached(this,C,F.normalizeZ)}multiply(C){let P=C;Z$("scalar",P,N0,I);let{p:T,f:_}=this.wNAF(P);return F.normalizeZ([T,_])[0]}multiplyUnsafe(C,P=F.ZERO){let T=C;if(Z$("scalar",T,F0,I),T===F0)return S;if(this.is0()||T===N0)return this;return y.wNAFCachedUnsafe(this,T,F.normalizeZ,P)}isSmallOrder(){return this.multiplyUnsafe(K).is0()}isTorsionFree(){return y.unsafeLadder(this,I).is0()}toAffine(C){return D(this,C)}clearCofactor(){let{h:C}=J;if(C===N0)return this;return this.multiplyUnsafe(C)}static fromHex(C,P=!1){let{d:T,a:_}=J,v=Q.BYTES;C=T0("pointHex",C,v),d$("zip215",P);let x=C.slice(),E=C[v-1];x[v-1]=E&-129;let i=V$(x),c=P?W:Q.ORDER;Z$("pointHex.y",i,F0,c);let n=G(i*i),a=G(n-N0),Q0=G(T*n-_),{isValid:V0,value:M0}=U(a,Q0);if(!V0)throw Error("Point.fromHex: invalid y coordinate");let m0=(M0&N0)===N0,S0=(E&128)!==0;if(!P&&M0===F0&&S0)throw Error("Point.fromHex: x=0 and x_0=1");if(S0!==m0)M0=G(-M0);return F.fromAffine({x:M0,y:i})}static fromPrivateKey(C){return m(C).point}toRawBytes(){let{x:C,y:P}=this.toAffine(),T=C$(P,Q.BYTES);return T[T.length-1]|=C&N0?128:0,T}toHex(){return o$(this.toRawBytes())}}F.BASE=new F(J.Gx,J.Gy,N0,G(J.Gx*J.Gy)),F.ZERO=new F(F0,N0,N0,F0);let{BASE:A,ZERO:S}=F,y=rI(F,Y*8);function f(C){return t(C,I)}function B(C){return f(V$(C))}function m(C){let P=Q.BYTES;C=T0("private key",C,P);let T=T0("hashed private key",Z(C),2*P),_=M(T.slice(0,P)),v=T.slice(P,2*P),x=B(_),E=A.multiply(x),i=E.toRawBytes();return{head:_,prefix:v,scalar:x,point:E,pointBytes:i}}function u(C){return m(C).pointBytes}function H(C=new Uint8Array,...P){let T=tJ(...P);return B(Z(O(T,T0("context",C),!!V)))}function g(C,P,T={}){if(C=T0("message",C),V)C=V(C);let{prefix:_,scalar:v,pointBytes:x}=m(P),E=H(T.context,_,C),i=A.multiply(E).toRawBytes(),c=H(T.context,i,x,C),n=f(E+c*v);Z$("signature.s",n,F0,I);let a=tJ(i,C$(n,Q.BYTES));return T0("result",a,Q.BYTES*2)}let p=V8;function r(C,P,T,_=p){let{context:v,zip215:x}=_,E=Q.BYTES;if(C=T0("signature",C,2*E),P=T0("message",P),T=T0("publicKey",T,E),x!==void 0)d$("zip215",x);if(V)P=V(P);let i=V$(C.slice(E,2*E)),c,n,a;try{c=F.fromHex(T,x),n=F.fromHex(C.slice(0,E),x),a=A.multiplyUnsafe(i)}catch(M0){return!1}if(!x&&c.isSmallOrder())return!1;let Q0=H(v,n.toRawBytes(),c.toRawBytes(),P);return n.add(c.multiplyUnsafe(Q0)).subtract(a).clearCofactor().equals(F.ZERO)}return A._setWindowSize(8),{CURVE:J,getPublicKey:u,sign:g,verify:r,ExtendedPoint:F,utils:{getExtendedPublicKey:m,randomPrivateKey:()=>X(Q.BYTES),precompute(C=8,P=F.BASE){return P._setWindowSize(C),P.multiply(BigInt(3)),P}}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var XQ=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),oI=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),ZN=BigInt(0),X8=BigInt(1),aI=BigInt(2),XN=BigInt(3),Y8=BigInt(5),K8=BigInt(8);function G8($){let J=BigInt(10),Q=BigInt(20),I=BigInt(40),V=BigInt(80),Z=XQ,Y=$*$%Z*$%Z,K=D0(Y,aI,Z)*Y%Z,W=D0(K,X8,Z)*$%Z,G=D0(W,Y8,Z)*W%Z,N=D0(G,J,Z)*G%Z,U=D0(N,Q,Z)*N%Z,M=D0(U,I,Z)*U%Z,O=D0(M,V,Z)*M%Z,z=D0(O,V,Z)*M%Z,R=D0(z,J,Z)*G%Z;return{pow_p_5_8:D0(R,aI,Z)*$%Z,b2:Y}}function W8($){return $[0]&=248,$[31]&=127,$[31]|=64,$}function N8($,J){let Q=XQ,I=t(J*J*J,Q),V=t(I*I*J,Q),Z=G8($*V).pow_p_5_8,X=t($*I*Z,Q),Y=t(J*X*X,Q),K=X,W=t(X*oI,Q),G=Y===$,N=Y===t(-$,Q),U=Y===t(-$*oI,Q);if(G)X=K;if(N||U)X=W;if(uI(X,Q))X=t(-X,Q);return{isValid:G||N,value:X}}var M8=(()=>a$(XQ,void 0,!0))(),q8=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:M8,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:K8,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:LI,randomBytes:jI,adjustScalarBytes:W8,uvRatio:N8}))(),e$=(()=>dI(q8))();/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function U8($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function w$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function o0($,...J){if(!U8($))throw Error("Uint8Array expected");if(J.length>0&&!J.includes($.length))throw Error("Uint8Array expected of length "+J+", got length="+$.length)}function T$($,J=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(J&&$.finished)throw Error("Hash#digest() has already been called")}function $J($,J){o0($);let Q=J.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function sI($){return new Uint8Array($.buffer,$.byteOffset,$.byteLength)}function Y$($){return new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4))}function K$(...$){for(let J=0;J<$.length;J++)$[J].fill(0)}function D$($,J){return $<<32-J|$>>>J}var tI=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function eI($){return $<<24&4278190080|$<<8&16711680|$>>>8&65280|$>>>24&255}var $V=tI?($)=>$:($)=>eI($);function z8($){for(let J=0;J<$.length;J++)$[J]=eI($[J]);return $}var K0=tI?($)=>$:z8;function O8($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function G$($){if(typeof $==="string")$=O8($);return o0($),$}class YQ{}function JV($){let J=(I,V)=>$(V).update(G$(I)).digest(),Q=$({});return J.outputLen=Q.outputLen,J.blockLen=Q.blockLen,J.create=(I)=>$(I),J}var QV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var JJ=BigInt(4294967295),IV=BigInt(32);function KQ($,J=!1){if(J)return{h:Number($&JJ),l:Number($>>IV&JJ)};return{h:Number($>>IV&JJ)|0,l:Number($&JJ)|0}}function B0($,J,Q,I,V){return $=$+J+V|0,I=D$(I^$,16),Q=Q+I|0,J=D$(J^Q,12),{a:$,b:J,c:Q,d:I}}function f0($,J,Q,I,V){return $=$+J+V|0,I=D$(I^$,8),Q=Q+I|0,J=D$(J^Q,7),{a:$,b:J,c:Q,d:I}}class GQ extends YQ{constructor($,J){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,w$($),w$(J),this.blockLen=$,this.outputLen=J,this.buffer=new Uint8Array($),this.buffer32=Y$(this.buffer)}update($){T$(this),$=G$($),o0($);let{blockLen:J,buffer:Q,buffer32:I}=this,V=$.length,Z=$.byteOffset,X=$.buffer;for(let Y=0;Y<V;){if(this.pos===J)K0(I),this.compress(I,0,!1),K0(I),this.pos=0;let K=Math.min(J-this.pos,V-Y),W=Z+Y;if(K===J&&!(W%4)&&Y+K<V){let G=new Uint32Array(X,W,Math.floor((V-Y)/4));K0(G);for(let N=0;Y+J<V;N+=I.length,Y+=J)this.length+=J,this.compress(G,N,!1);K0(G);continue}Q.set($.subarray(Y,Y+K),this.pos),this.pos+=K,this.length+=K,Y+=K}return this}digestInto($){T$(this),$J($,this);let{pos:J,buffer32:Q}=this;this.finished=!0,K$(this.buffer.subarray(J)),K0(Q),this.compress(Q,0,!0),K0(Q);let I=Y$($);this.get().forEach((V,Z)=>I[Z]=$V(V))}digest(){let{buffer:$,outputLen:J}=this;this.digestInto($);let Q=$.slice(0,J);return this.destroy(),Q}_cloneInto($){let{buffer:J,length:Q,finished:I,destroyed:V,outputLen:Z,pos:X}=this;return $||($=new this.constructor({dkLen:Z})),$.set(...this.get()),$.buffer.set(J),$.destroyed=V,$.finished=I,$.length=Q,$.pos=X,$.outputLen=Z,$}clone(){return this._cloneInto()}}function WQ($,J,Q,I,V,Z,X,Y,K,W,G,N,U,M,O,z,R,D,w,F){let A=0;for(let S=0;S<I;S++)({a:V,b:K,c:U,d:R}=B0(V,K,U,R,Q[J+$[A++]])),{a:V,b:K,c:U,d:R}=f0(V,K,U,R,Q[J+$[A++]]),{a:Z,b:W,c:M,d:D}=B0(Z,W,M,D,Q[J+$[A++]]),{a:Z,b:W,c:M,d:D}=f0(Z,W,M,D,Q[J+$[A++]]),{a:X,b:G,c:O,d:w}=B0(X,G,O,w,Q[J+$[A++]]),{a:X,b:G,c:O,d:w}=f0(X,G,O,w,Q[J+$[A++]]),{a:Y,b:N,c:z,d:F}=B0(Y,N,z,F,Q[J+$[A++]]),{a:Y,b:N,c:z,d:F}=f0(Y,N,z,F,Q[J+$[A++]]),{a:V,b:W,c:O,d:F}=B0(V,W,O,F,Q[J+$[A++]]),{a:V,b:W,c:O,d:F}=f0(V,W,O,F,Q[J+$[A++]]),{a:Z,b:G,c:z,d:R}=B0(Z,G,z,R,Q[J+$[A++]]),{a:Z,b:G,c:z,d:R}=f0(Z,G,z,R,Q[J+$[A++]]),{a:X,b:N,c:U,d:D}=B0(X,N,U,D,Q[J+$[A++]]),{a:X,b:N,c:U,d:D}=f0(X,N,U,D,Q[J+$[A++]]),{a:Y,b:K,c:M,d:w}=B0(Y,K,M,w,Q[J+$[A++]]),{a:Y,b:K,c:M,d:w}=f0(Y,K,M,w,Q[J+$[A++]]);return{v0:V,v1:Z,v2:X,v3:Y,v4:K,v5:W,v6:G,v7:N,v8:U,v9:M,v10:O,v11:z,v12:R,v13:D,v14:w,v15:F}}var j0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},x0=QV.slice(),VV=(()=>{let $=Array.from({length:16},(I,V)=>V),J=(I)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((V)=>I[V]),Q=[];for(let I=0,V=$;I<7;I++,V=J(V))Q.push(...V);return Uint8Array.from(Q)})();class NQ extends GQ{constructor($={},J=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:I}=$,V=I!==void 0;if(Q!==void 0){if(V)throw Error('Only "key" or "context" can be specified at same time');let Z=G$(Q).slice();o0(Z,32),this.IV=Y$(Z),K0(this.IV),this.flags=J|j0.KEYED_HASH}else if(V){let Z=G$(I),X=new NQ({dkLen:32},j0.DERIVE_KEY_CONTEXT).update(Z).digest();this.IV=Y$(X),K0(this.IV),this.flags=J|j0.DERIVE_KEY_MATERIAL}else this.IV=x0.slice(),this.flags=J;this.state=this.IV.slice(),this.bufferOut=sI(this.bufferOut32)}get(){return[]}set(){}b2Compress($,J,Q,I=0){let{state:V,pos:Z}=this,{h:X,l:Y}=KQ(BigInt($),!0),{v0:K,v1:W,v2:G,v3:N,v4:U,v5:M,v6:O,v7:z,v8:R,v9:D,v10:w,v11:F,v12:A,v13:S,v14:y,v15:f}=WQ(VV,I,Q,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],x0[0],x0[1],x0[2],x0[3],X,Y,Z,J);V[0]=K^R,V[1]=W^D,V[2]=G^w,V[3]=N^F,V[4]=U^A,V[5]=M^S,V[6]=O^y,V[7]=z^f}compress($,J=0,Q=!1){let I=this.flags;if(!this.chunkPos)I|=j0.CHUNK_START;if(this.chunkPos===15||Q)I|=j0.CHUNK_END;if(!Q)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,I,$,J),this.chunkPos+=1,this.chunkPos===16||Q){let V=this.state;this.state=this.IV.slice();for(let Z,X=this.chunksDone+1;Q||!(X&1);X>>=1){if(!(Z=this.stack.pop()))break;this.buffer32.set(Z,0),this.buffer32.set(V,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|j0.PARENT,this.buffer32,0),V=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(V)}this.pos=0}_cloneInto($){$=super._cloneInto($);let{IV:J,flags:Q,state:I,chunkPos:V,posOut:Z,chunkOut:X,stack:Y,chunksDone:K}=this;return $.state.set(I.slice()),$.stack=Y.map((W)=>Uint32Array.from(W)),$.IV.set(J),$.flags=Q,$.chunkPos=V,$.chunksDone=K,$.posOut=Z,$.chunkOut=X,$.enableXOF=this.enableXOF,$.bufferOut32.set(this.bufferOut32),$}destroy(){this.destroyed=!0,K$(this.state,this.buffer32,this.IV,this.bufferOut32),K$(...this.stack)}b2CompressOut(){let{state:$,pos:J,flags:Q,buffer32:I,bufferOut32:V}=this,{h:Z,l:X}=KQ(BigInt(this.chunkOut++));K0(I);let{v0:Y,v1:K,v2:W,v3:G,v4:N,v5:U,v6:M,v7:O,v8:z,v9:R,v10:D,v11:w,v12:F,v13:A,v14:S,v15:y}=WQ(VV,0,I,7,$[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],x0[0],x0[1],x0[2],x0[3],X,Z,J,Q);V[0]=Y^z,V[1]=K^R,V[2]=W^D,V[3]=G^w,V[4]=N^F,V[5]=U^A,V[6]=M^S,V[7]=O^y,V[8]=$[0]^z,V[9]=$[1]^R,V[10]=$[2]^D,V[11]=$[3]^w,V[12]=$[4]^F,V[13]=$[5]^A,V[14]=$[6]^S,V[15]=$[7]^y,K0(I),K0(V),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,K$(this.buffer.subarray(this.pos));let $=this.flags|j0.ROOT;if(this.stack.length)$|=j0.PARENT,K0(this.buffer32),this.compress(this.buffer32,0,!0),K0(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else $|=(!this.chunkPos?j0.CHUNK_START:0)|j0.CHUNK_END;this.flags=$,this.b2CompressOut()}writeInto($){T$(this,!1),o0($),this.finish();let{blockLen:J,bufferOut:Q}=this;for(let I=0,V=$.length;I<V;){if(this.posOut>=J)this.b2CompressOut();let Z=Math.min(J-this.posOut,V-I);$.set(Q.subarray(this.posOut,this.posOut+Z),I),this.posOut+=Z,I+=Z}return $}xofInto($){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto($)}xof($){return w$($),this.xofInto(new Uint8Array($))}digestInto($){if($J($,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 ZV=JV(($)=>new NQ($));class MQ{async genRandomBytes($){return l$($)}async gen256BitSecureRandomSeed(){return l$(32)}async encryptXSalsa20Poly1305Combined($,J){let Q=l$(24),V=uJ(J,Q).encrypt($);return new Uint8Array([...Q,...V])}async decryptXSalsa20Poly1305Combined($,J){let Q=$.slice(0,24),I=$.slice(24);return uJ(J,Q).decrypt(I)}async deriveEd25519KeyPair($){let J=$,Q=e$.getPublicKey(J),I=new Uint8Array(64);return I.set(J,0),I.set(Q,32),{keyType:"ed25519",privateKey:I,publicKey:Q}}async signEd25519($,J){let Q=typeof $==="string"?new TextEncoder().encode($):$,I=J.slice(0,32);return e$.sign(Q,I)}async checkSigEd25519($,J,Q){let I=typeof J==="string"?new TextEncoder().encode(J):J;return e$.verify($,I,Q)}async blake3($){return ZV($)}}var H8=new MQ,z0=H8;var _N=Symbol("EntityID");function XV($){return"type"in $}var EN=Symbol("MasterSeed"),BN=Symbol("DerivationSeed"),fN=Symbol("PublicKey"),xN=Symbol("PrivateKey"),gN=Symbol("HostSpecificKeyPair"),mN=Symbol("Hash");function R8($){if(!$)return!1;if(typeof $!=="object")return!1;if("body"in $===!1)return!1;if("type"in $===!1)return!1;return!0}function C8($){if(!$.bod||$.bod.length===0){let I={off:$.off,ctr:$.ctr,eid:$.eid};return j(I)}let J=zJ($.bod);if(R8(J)===!1)return console.warn("msg body invalid",J),q(14);let Q={off:$.off,ctr:$.ctr,eid:$.eid,gid:J.gid,pid:J.pid,type:J.type,body:J.body};return j(Q)}class QJ{applier;emitter=new v0;clearer;onTypes;constructor($,J,Q){this.applier=$;this.clearer=J,this.onTypes=Q}apply=async($)=>{let J=[],Q=[];for(let X of $){let[Y,K]=C8(X);if(Q.push(K),K!==0)continue;J.push(Y)}let{stats:I,types:V}=await this.applier(J),Z=[];for(let X=0;X<$.length;X++){let Y=Q[X],K=I[X];if(Y!==0){Z.push(Y);continue}if(K!==0){Z.push(K);continue}Z.push(0)}for(let X of V)this.emitter.emit(X,null);if(V.size>0)this.onTypes?.(V);return Z};clear=async()=>{let $=await this.clearer();if($!==0)return $;return this.emitter.emitAll(null),$};notify=($)=>{for(let J of $)this.emitter.emit(J,null)};on=($,J)=>{this.emitter.addEventListener($,J)};off=($,J)=>{this.emitter.removeEventListener($,J)}}var qQ={apply:async function($){return $.map(()=>0)},clear:async function(){return 0},notify:function($){},on:function($,J){},off:function($,J){}};function UQ($){return new QJ((J)=>$.apply(J),()=>$.clear())}function IJ($,J){let Q=new h(J.eid),[I,V]=Q.readStruct(q0);if(V!==0)return q(V);let Z=new Date(I.ts.getTime()+J.off);if($!==void 0&&Z<=$.updatedAt)return q(15);if(XV(J))return j({eid:J.eid,gid:J.gid,pid:J.pid,type:J.type,createdAt:I.ts,updatedAt:Z,ctr:J.ctr,body:J.body});else return j(void 0)}var w8={getEnt:async()=>q(21),getEntities:async($)=>q(21),countEntities:async()=>q(21),apply:async($)=>({stats:$.map(()=>21),types:new Set}),clear:async()=>21};var J0="entities",VJ="entity_type_created_at",zQ="entity_type_updated_at",OQ="entity_type_group_id",HQ="entity_type_parent_id";function T8($){let J={bod:$.body,crd:$.createdAt,...$.ctr!==0?{ctr:$.ctr}:{},eid:d($.eid),gid:$.gid,pid:$.pid?d($.pid):void 0,typ:$.type,upd:$.updatedAt};if(J.gid===void 0)delete J.gid;if(J.pid===void 0)delete J.pid;if(J.ctr===void 0)delete J.ctr;return J}function W$($){return{body:$.bod,createdAt:$.crd,updatedAt:$.upd,ctr:$.ctr??0,type:$.typ,eid:U0($.eid),gid:$.gid,pid:$.pid?U0($.pid):void 0}}class RQ{db;async init(){this.db=await new Promise(($,J)=>{let Q=indexedDB.open("db",11);Q.onupgradeneeded=()=>{let{result:I,transaction:V}=Q;if(!V)throw Error("Transaction is null during upgrade");if(!I.objectStoreNames.contains(J0))I.createObjectStore(J0,{keyPath:"eid",autoIncrement:!1});let Z=V.objectStore(J0);if(!Z.indexNames.contains(VJ))Z.createIndex(VJ,["typ","crd"],{unique:!1});if(!Z.indexNames.contains(zQ))Z.createIndex(zQ,["typ","upd"],{unique:!1});if(!Z.indexNames.contains(OQ))Z.createIndex(OQ,["typ","gid"],{unique:!1});if(!Z.indexNames.contains(HQ))Z.createIndex(HQ,["typ","pid"],{unique:!1})},Q.onsuccess=()=>$(Q.result),Q.onerror=()=>J(Q.error)})}apply=async($)=>{let J=new Set;if(!this.db)return{stats:$.map(()=>16),types:J};let Q=this.db.transaction(J0,"readwrite"),I=Q.objectStore(J0);return new Promise((V)=>{let Z=Array($.length).fill(0);if($.length<1){V({stats:[],types:J});return}Q.oncomplete=()=>{V({stats:Z,types:J})},Q.onerror=()=>{for(let Y=0;Y<Z.length;Y++)if(Z[Y]===void 0)Z[Y]=18;V({stats:Z,types:J})};let X=new Map;for(let Y=0;Y<$.length;Y++){let K=$[Y],W=d(K.eid),G={op:K,index:Y},N=X.get(W);if(N)N.push(G);else X.set(W,[G])}for(let[Y,K]of X){if(K.length<1)continue;let W=I.get(Y);W.onsuccess=()=>{let G=W.result,N=G?W$(G):void 0;for(let{op:U,index:M}of K){let[O,z]=IJ(N,U);if(z!==0){Z[M]=z;continue}if(O)J.add(O.type);else if(N)J.add(N.type);N=O}if(N){let U=T8(N),M=I.put(U);M.onerror=(O)=>{O.preventDefault();for(let{index:z}of K)Z[z]=18}}else{let U=I.delete(Y);U.onerror=()=>{for(let{index:M}of K)Z[M]=18}}},W.onerror=()=>{for(let{index:G}of K)Z[G]=18}}})};async clear(){if(!this.db)return 16;let $=this.db.transaction(J0,"readwrite"),J=$.objectStore(J0);return new Promise((Q)=>{$.oncomplete=()=>Q(0),$.onerror=()=>Q(18),J.clear()})}async getEnt($){if(!this.db)return q(16);let J=d($),I=this.db.transaction(J0,"readonly").objectStore(J0);return new Promise((V)=>{let Z=I.get(J);Z.onsuccess=()=>{let X=Z.result;if(!X)V(j(void 0));else{let Y=W$(X);V(j(Y))}},Z.onerror=()=>V(q(18))})}async getAllOfTypeUpdatedBetween($,J,Q){if(!this.db)return q(16);let V=this.db.transaction(J0,"readonly").objectStore(J0).index(zQ);return new Promise((Z)=>{let X=V.getAll(IDBKeyRange.bound([$,J],[$,Q]));X.onsuccess=()=>{let Y=X.result;Z(j(Y.map(W$)))},X.onerror=()=>Z(q(18))})}async getGroupMembers($,J){if(!this.db)return q(16);let I=this.db.transaction(J0,"readonly").objectStore(J0).index(OQ);return new Promise((V)=>{let Z=I.getAll(IDBKeyRange.only([$,J]));Z.onsuccess=()=>{let X=Z.result;V(j(X.map(W$)))},Z.onerror=()=>V(q(18))})}async getAllOfType($){if(!this.db)return q(16);let Q=this.db.transaction(J0,"readonly").objectStore(J0).index(VJ);return new Promise((I)=>{let V=Q.getAll(IDBKeyRange.bound([$],[$,[]]));V.onsuccess=()=>{let Z=V.result;I(j(Z.map(W$)))},V.onerror=()=>I(q(18))})}async getAllEntities($){if(!this.db)return q(16);if("pid"in $){let J=d($.pid),I=this.db.transaction(J0,"readonly").objectStore(J0).index(HQ);return new Promise((V)=>{let Z=I.getAll(IDBKeyRange.only([$.type,J]));Z.onsuccess=()=>{let Y=Z.result.map(W$);V(j(Y))},Z.onerror=()=>V(q(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[J,Q]=await this.getAllEntities($);if(Q!==0)return q(Q);return j(J)}async countEntities({type:$}){if(!this.db)return q(16);let Q=this.db.transaction(J0,"readonly").objectStore(J0).index(VJ);return new Promise((I)=>{let V=IDBKeyRange.bound([$],[$,[]]),Z=Q.count(V);Z.onsuccess=()=>I(j(Z.result)),Z.onerror=()=>I(q(18))})}}async function CQ(){let $=new RQ;return await $.init(),$}class YV{ents=new Map;constructor($=[]){for(let J of $){let Q=d(J.eid);this.ents.set(Q,J)}}async apply($){let J=new Set,Q=[];for(let I of $){let V=d(I.eid),Z=this.ents.get(V),[X,Y]=IJ(Z,I);if(Y!==0){Q.push(Y);continue}if(X)J.add(X.type);else if(Z)J.add(Z.type);if(X)this.ents.set(V,X);else this.ents.delete(V);Q.push(0)}return{stats:Q,types:J}}async clear(){return this.ents.clear(),0}async getEnt($){let J=d($),Q=this.ents.get(J);return j(Q)}async getAllEntities({type:$,gid:J,pid:Q,updatedBetween:I}){let V=[];if(Q!==void 0){for(let Z of this.ents.values())if(Z.type===$&&Z.pid&&w0(Z.pid,Q))V.push(Z)}else if(J!==void 0){for(let Z of this.ents.values())if(Z.type===$&&(typeof Z.gid==="string"&&Z.gid===J))V.push(Z)}else if(I!==void 0){for(let Z of this.ents.values())if(Z.type===$&&Z.updatedAt>=I.start&&Z.updatedAt<=I.end)V.push(Z)}else for(let Z of this.ents.values())if(Z.type===$)V.push(Z);return j(V)}async getEntities($){let[J,Q]=await this.getAllEntities($);if(Q!==0)return q(Q);return j(J)}async countEntities({type:$}){let J=0;for(let Q of this.ents.values())if(Q.type===$)J+=1;return j(J)}}import{useEffect as GJ,useState as kQ}from"react";class wQ{db;constructor($){this.db=$}async enq($){let J=[...$];if(J.length===0)return;let Q=this.db.transaction(O0,"readwrite"),I=Q.objectStore(O0);return new Promise((V,Z)=>{Q.oncomplete=()=>V(),Q.onerror=()=>Z(Q.error);for(let X of J){let Y=`${X.host}:${X.seq}`;I.put(X,Y)}})}async deq($,J){let Q=[...J];if(Q.length===0)return;let I=this.db.transaction(O0,"readwrite"),V=I.objectStore(O0);return new Promise((Z,X)=>{I.oncomplete=()=>Z(),I.onerror=()=>X(I.error);for(let Y of Q){let K=`${$}:${Y}`;V.delete(K)}})}async list(){let J=this.db.transaction(O0,"readonly").objectStore(O0);return new Promise((Q,I)=>{let V=J.getAll();V.onsuccess=()=>Q(V.result),V.onerror=()=>I(V.error)})}async count(){let J=this.db.transaction(O0,"readonly").objectStore(O0);return new Promise((Q,I)=>{let V=J.count();V.onsuccess=()=>Q(V.result),V.onerror=()=>I(V.error)})}async wipe(){let $=this.db.transaction(O0,"readwrite"),J=$.objectStore(O0);return new Promise((Q,I)=>{$.oncomplete=()=>Q(),$.onerror=()=>I($.error),J.clear()})}}function KV($){return{label:$.label,handle:new URL($.handle),idx:$.idx,lastSeq:$.lastSeq||0,clockOffset:$.clockOffset,subscription:$.subscription}}class TQ{db;constructor($){this.db=$}async add($){return this.put($)}async put($){let J={...$,handle:$.handle.toString(),lastSeq:$.lastSeq??0},Q=this.db.transaction(G0,"readwrite"),I=Q.objectStore(G0);return new Promise((V,Z)=>{Q.oncomplete=()=>V(),Q.onerror=()=>Z(Q.error),I.put(J)})}async touch($,J){let Q=this.db.transaction(G0,"readwrite"),I=Q.objectStore(G0);return new Promise((V,Z)=>{Q.oncomplete=()=>V(),Q.onerror=()=>Z(Q.error);let X=I.get($);X.onsuccess=()=>{let Y=X.result;if(!Y)return;let K=Y.lastSeq||0;if(J<=K)return;I.put({...Y,lastSeq:J})}})}async get($){let Q=this.db.transaction(G0,"readonly").objectStore(G0);return new Promise((I,V)=>{let Z=Q.get($);Z.onsuccess=()=>{let X=Z.result;if(!X)I(void 0);else I(KV(X))},Z.onerror=()=>V(Z.error)})}async set($,J){let Q=await this.get($);if(!Q)return 13;try{return await this.put({...Q,...J}),0}catch{return 18}}async del($){let J=this.db.transaction(G0,"readwrite"),Q=J.objectStore(G0);return new Promise((I,V)=>{J.oncomplete=()=>I(),J.onerror=()=>V(J.error),Q.delete($)})}async list(){let J=this.db.transaction(G0,"readonly").objectStore(G0);return new Promise((Q,I)=>{let V=J.getAll();V.onsuccess=()=>{let Z=V.result;Q(Z.map(KV))},V.onerror=()=>I(V.error)})}async wipe(){let $=this.db.transaction(G0,"readwrite"),J=$.objectStore(G0);return new Promise((Q,I)=>{$.oncomplete=()=>Q(),$.onerror=()=>I($.error),J.clear()})}}function a0($){return{eid:$.eid,...$.off!==void 0?{off:$.off}:{},...$.ctr!==void 0?{ctr:$.ctr}:{},...$.body!==void 0?{body:$.body}:{},apld:$.apld??!1}}function DQ($){return a0($).apld===!1}async function k0($,J,Q){let I=a0(J),V=I.body?.length??0,Z;if(I.body&&V>0)Z=await Q.blake3(I.body);let X={eid:I.eid,off:I.off??0,ctr:I.ctr??0,len:V,hsh:Z};return{hash:$,head:X,body:I.body,applied:I.apld}}class FQ{crypto;db;constructor($,J){this.crypto=J;this.db=$}async add($){let J=this.db.transaction(e,"readwrite"),Q=J.objectStore(e);return new Promise((I)=>{if($.length===0){I([]);return}let V=Array($.length).fill(0);J.oncomplete=()=>I(V),J.onerror=()=>{for(let Z=0;Z<V.length;Z++)V[Z]=18;I(V)};for(let Z=0;Z<$.length;Z++){let{key:X,data:Y}=$[Z],K=d(X),W=Q.put(Y,K);W.onerror=(G)=>{G.preventDefault(),V[Z]=18}}})}async del($){let J=[...$];if(J.length===0)return;let Q=this.db.transaction(e,"readwrite"),I=Q.objectStore(e);return new Promise((V,Z)=>{Q.oncomplete=()=>V(),Q.onerror=()=>Z(Q.error);for(let X of J){let Y=d(X);I.delete(Y)}})}async get($){let Q=this.db.transaction(e,"readonly").objectStore(e);return new Promise((I,V)=>{let Z=d($),X=Q.get(Z);X.onsuccess=async()=>{let Y=X.result;if(Y)I(await k0($,Y,this.crypto));else I(void 0)},X.onerror=()=>V(X.error)})}async has($){return await this.get($)!==void 0}async list(){let J=this.db.transaction(e,"readonly").objectStore(e);return new Promise((Q,I)=>{let V=[],Z=J.openCursor();Z.onsuccess=async(X)=>{let Y=X.target.result;if(Y){let{key:K,value:W}=Y,G=U0(K),N=await k0(G,W,this.crypto);V.push(N),Y.continue()}else Q(V)},Z.onerror=()=>I(Z.error)})}async last($){let Q=this.db.transaction(e,"readonly").objectStore(e);return new Promise((I,V)=>{let Z,X=Q.openCursor();X.onsuccess=async(Y)=>{let K=Y.target.result;if(K){let{key:W,value:G}=K;if(w0($,G.eid)){if(!Z||(G.ctr??0)>(Z.data.ctr??0)||(G.ctr??0)===(Z.data.ctr??0)&&(G.off??0)>(Z.data.off??0))Z={key:W,data:G}}K.continue()}else if(Z){let W=U0(Z.key);I(await k0(W,Z.data,this.crypto))}else I(void 0)},X.onerror=()=>V(X.error)})}async listUnapplied(){let Q=this.db.transaction(e,"readonly").objectStore(e).index(ZJ);return new Promise((I,V)=>{let Z=[],X=Q.openCursor(IDBKeyRange.only(!1));X.onsuccess=(Y)=>{let K=Y.target.result;if(K){let{primaryKey:W,value:G}=K;Z.push({hash:U0(W),data:G}),K.continue()}else Promise.all(Z.map(({hash:W,data:G})=>k0(W,G,this.crypto))).then(I).catch(V)},X.onerror=()=>V(X.error)})}async markApplied($){let J=[...$];if(J.length===0)return;let Q=this.db.transaction(e,"readwrite"),I=Q.objectStore(e);return new Promise((V,Z)=>{Q.oncomplete=()=>V(),Q.onerror=()=>Z(Q.error);for(let X of J){let Y=d(X),K=I.get(Y);K.onsuccess=()=>{let W=K.result;if(!W)return;I.put({...a0(W),apld:!0},Y)},K.onerror=(W)=>{W.preventDefault()}}})}async wipe(){let $=this.db.transaction(e,"readwrite"),J=$.objectStore(e);return new Promise((Q,I)=>{$.oncomplete=()=>Q(),$.onerror=()=>I($.error),J.clear()})}}class N${seed;crypto;constructor($,J){this.seed=$,this.crypto=J}async deriveFromKDM($){let J=z$(this.seed,$);return await this.crypto.blake3(J)}async derive($,J=0){let Q=new TextEncoder().encode($),I=new Uint8Array(8);new DataView(I.buffer).setBigUint64(0,BigInt(J),!1);let V=z$(Q,I);return await this.deriveFromKDM(V)}}class AQ{enclave;db;constructor($){this.db=$}async save($){let J=C0($),Q=this.db.transaction(g0,"readwrite"),I=Q.objectStore(g0);return new Promise((V,Z)=>{Q.oncomplete=()=>{this.enclave=new N$($,z0),V(this.enclave)},Q.onerror=()=>Z(Q.error),I.put(J,"seed")})}async load(){if(this.enclave)return this.enclave;let J=this.db.transaction(g0,"readonly").objectStore(g0);return new Promise((Q,I)=>{let V=J.get("seed");V.onsuccess=()=>{let Z=V.result;if(!Z)Q(void 0);else{let X=i0(Z);this.enclave=new N$(X,z0),Q(this.enclave)}},V.onerror=()=>I(V.error)})}async wipe(){this.enclave=void 0;let $=this.db.transaction(g0,"readwrite"),J=$.objectStore(g0);return new Promise((Q,I)=>{$.oncomplete=()=>Q(),$.onerror=()=>I($.error),J.delete("seed")})}}class PQ{db;constructor($){this.db=$}async enq($,J){let Q=[...J];if(Q.length===0)return;let I=this.db.transaction(H0,"readwrite"),V=I.objectStore(H0);return new Promise((Z,X)=>{I.oncomplete=()=>Z(),I.onerror=()=>X(I.error);for(let Y of Q){let K=C0(Y);V.put({host:$,hash:K})}})}async deq($,J){let Q=[...J];if(Q.length===0)return;let I=this.db.transaction(H0,"readwrite"),V=I.objectStore(H0);return new Promise((Z,X)=>{I.oncomplete=()=>Z(),I.onerror=()=>X(I.error);for(let Y of Q){let K=C0(Y);V.delete([$,K])}})}async list($){let Q=this.db.transaction(H0,"readonly").objectStore(H0);return new Promise((I,V)=>{let Z=Q.getAll();Z.onsuccess=()=>{let Y=Z.result.filter((K)=>K.host===$).map((K)=>K.hash);I(Y.map((K)=>i0(K)))},Z.onerror=()=>V(Z.error)})}async count(){let J=this.db.transaction(H0,"readonly").objectStore(H0);return new Promise((Q,I)=>{let V=J.count();V.onsuccess=()=>Q(V.result),V.onerror=()=>I(V.error)})}async wipe(){let $=this.db.transaction(H0,"readwrite"),J=$.objectStore(H0);return new Promise((Q,I)=>{$.oncomplete=()=>Q(),$.onerror=()=>I($.error),J.clear()})}}var g0="seedMeta",G0="hosts",H0="uploadQueue",O0="downloadQueue",e="messages",ZJ="apld",D8=3;class jQ{seed;hosts;uploads;downloads;messages;db;constructor($,J){this.db=$,this.seed=new AQ($),this.hosts=new TQ($),this.uploads=new PQ($),this.downloads=new wQ($),this.messages=new FQ($,J)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function F8(){return new Promise(($,J)=>{let Q=indexedDB.open("diplomatic-store-db",D8);Q.onupgradeneeded=()=>{let{result:I,transaction:V}=Q;if(!I.objectStoreNames.contains(g0))I.createObjectStore(g0);if(!I.objectStoreNames.contains(G0))I.createObjectStore(G0,{keyPath:"label"});if(!I.objectStoreNames.contains(H0))I.createObjectStore(H0,{keyPath:["host","hash"]});if(!I.objectStoreNames.contains(O0))I.createObjectStore(O0);let Z;if(!I.objectStoreNames.contains(e))Z=I.createObjectStore(e);else{if(!V)throw Error("missing upgrade transaction for messages store");Z=V.objectStore(e)}if(!Z.indexNames.contains(ZJ))Z.createIndex(ZJ,"apld",{unique:!1})},Q.onsuccess=()=>$(Q.result),Q.onerror=()=>J(Q.error)})}async function XJ($){let J=await F8();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new jQ(J,$)}function GV($){if(!$||typeof $!=="object")return!1;if(!("kind"in $))return!1;return typeof $.kind==="string"}function WV($){if(typeof $!=="number")return;return $}var l0="[DIPLOMATIC]";class F${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:Q$};clientState;xferState;constructor($,J,Q,I,V){this.worker=$,this.state=J,this.clientState=new A0(async()=>this.cachedClientState),this.xferState=new A0(async()=>this.cachedXferState),this.scheduledSync=new H$(V,async()=>{try{await this.request({id:this.allocId(),op:"sync"})}catch(Z){console.error(`${l0} worker sync after local write failed`,Z)}}),this.local=new r0(I,J,Q,()=>{throw Error(`${l0} local writer has no transport (use worker for network)`)},z0,!0,void 0,void 0,()=>{this.scheduledSync.schedule()}),this.ready=new Promise((Z,X)=>{this.resolveReady=Z,this.rejectReady=X}),this.worker.onmessage=(Z)=>{this.onMessage(Z.data)},this.worker.onerror=(Z)=>{console.error(`${l0} worker error`,Z),this.failReady(Error(`${l0} worker failed to load`))},this.worker.onmessageerror=()=>{this.failReady(Error(`${l0} worker message error`))}}failReady($){let J=this.rejectReady;if(this.rejectReady=void 0,this.resolveReady=void 0,J)J($)}async flushScheduledSync(){await this.scheduledSync.flush()}static async connect($,J,Q){let I=Q.clock??new L0,V=Q.syncDebounceMs??b$,Z=new F$(Q.worker,$,J,I,V),X=Q.readyTimeoutMs??15000,Y;try{await Promise.race([Z.ready,new Promise((K,W)=>{Y=setTimeout(()=>{W(Error(`${l0} worker ready timeout after ${X}ms`))},X)})])}catch(K){throw Z.terminate(),K}finally{if(Y!==void 0)clearTimeout(Y)}return Z}async ping(){if(await this.ready,await this.request({id:this.allocId(),op:"ping"})!=="pong")throw Error(`${l0} worker ping failed`)}terminate(){this.scheduledSync.cancel(),this.worker.terminate();for(let[,$]of this.pending)$.reject(Error(`${l0} worker terminated`));this.pending.clear()}onMessage($){if(!GV($))return;let J=$;switch(J.kind){case"ready":{let Q=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,Q)Q();return}case"clientState":{this.cachedClientState=J.state,this.clientState.emit();return}case"xferState":{this.cachedXferState=J.state,this.xferState.emit();return}case"dirty":{this.state.notify(J.types);return}case"wiped":{this.state.clear();return}case"reply":{let Q=this.pending.get(J.id);if(!Q)return;if(this.pending.delete(J.id),J.ok)Q.resolve(J.result);else Q.reject(new YJ(J.status));return}default:return}}allocId(){let $=this.nextId;return this.nextId+=1,$}request($,J){return new Promise((Q,I)=>{if(this.pending.set($.id,{resolve:Q,reject:I}),J&&J.length>0)this.worker.postMessage($,J);else this.worker.postMessage($)})}async requestStatus($,J){try{let Q=await this.request($,J),I=WV(Q);if(I!==void 0)return I;return 0}catch(Q){if(Q instanceof YJ)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 J=$.slice();await this.request({id:this.allocId(),op:"setSeed",seed:J},[J.buffer])}async link($,J=!0){await this.ready,await this.local.link($,!1),await this.request({id:this.allocId(),op:"link",host:this.serializeHost($),connect:J})}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,J=!0){await this.ready,await this.request({id:this.allocId(),op:"connect",listen:$,sync:J})}async disconnect(){await this.ready,await this.request({id:this.allocId(),op:"disconnect"})}async insertRaw($){return await this.ready,this.local.insertRaw($)}async upsertRaw($,J,Q){return await this.ready,this.local.upsertRaw($,J,Q)}async insert($){return await this.ready,this.local.insert($)}async upsert($,J){return await this.ready,this.local.upsert($,J)}async delete($){return await this.ready,this.local.delete($)}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 J=new Uint8Array(await $.arrayBuffer());return this.requestStatus({id:this.allocId(),op:"import",bytes:J},[J.buffer])}async export($,J){await this.ready;try{let Q=await this.request({id:this.allocId(),op:"export"});if(!(Q instanceof Uint8Array))return 12;let I=new Blob([Q.slice()]);return u$(I,$),0}catch(Q){if(Q instanceof YJ)return Q.status;return 12}}}class YJ extends Error{status;constructor($){super(`WorkerReplyError: ${L[$]}`);this.status=$;this.name="WorkerReplyError"}}var s0="[DIPLOMATIC]";async function KJ($){let J=$.clock??new L0;if($.worker!==void 0&&A8($)!==void 0)throw Error(`${s0} worker path requires IndexedDB on both sides; do not pass store (got a custom store)`);if($.worker===void 0){console.info(`${s0} sync on main thread `+"(no worker — app did not request a worker)");let V=await NV($.store);return P8(J,$.state,V)}if(typeof Worker>"u")throw Error(`${s0} worker was provided but Worker API is unavailable`);let Q=await NV(void 0);console.info(`${s0} attaching app-provided sync worker…`);let I=await F$.connect($.state,Q,{worker:$.worker,readyTimeoutMs:$.readyTimeoutMs,clock:J,syncDebounceMs:$.syncDebounceMs});return await I.ping(),console.info(`${s0} sync worker active (network + EntDB writes off main; local mutates on main; dirty signals only)`),{client:I,mode:"worker",dispose:()=>{console.info(`${s0} terminating sync worker`),I.terminate()}}}function A8($){if("store"in $)return $.store;return}async function P8($,J,Q){let I=new r0($,J,Q,g$,z0);return{client:I,mode:"main",dispose:()=>{I.disconnect()}}}async function NV($){if($!==void 0)return $;if(typeof indexedDB>"u")throw Error(`${s0} IndexedDB is unavailable; pass store explicitly (e.g. new MemoryStore(crypto))`);return XJ(z0)}function j8($){let[J,Q]=kQ();return GJ(()=>{async function I(){let Z=await $.clientState.get();Q(Z)}let V=$.clientState.listen(I);return I(),()=>{V()}},[$]),J}function k8($){let[J,Q]=kQ();return GJ(()=>{async function I(){let Z=await $.xferState.get();Q(Z)}let V=$.xferState.listen(I);return I(),()=>{V()}},[$]),J}function S8($){GJ(()=>{async function J(){try{await $.connect(),await $.sync()}catch(Z){console.error("reconnectAndSync failed",Z)}}function Q(){J()}function I(){if(typeof document<"u"&&document.visibilityState==="visible")J()}function V(){J()}if(globalThis.addEventListener("online",Q),typeof document<"u")document.addEventListener("visibilitychange",I);return globalThis.addEventListener("focus",V),globalThis.addEventListener("pageshow",V),()=>{if(globalThis.removeEventListener("online",Q),typeof document<"u")document.removeEventListener("visibilitychange",I);globalThis.removeEventListener("focus",V),globalThis.removeEventListener("pageshow",V)}},[$])}function L8($={}){let J=$.clock??new L0,{seed:Q,host:I,readyTimeoutMs:V}=$,Z=$.worker,X="store"in $?$.store:void 0,[Y,K]=kQ({stateMgr:qQ});return GJ(()=>{let W=!1,G;return(async()=>{let N=await CQ();if(W)return;let U=UQ(N),M=Z!==void 0?await KJ({state:U,clock:J,worker:Z,readyTimeoutMs:V}):await KJ({state:U,clock:J,store:X,readyTimeoutMs:V});if(W){M.dispose();return}G=M.dispose;let{client:O,mode:z}=M;if(Q)await O.setSeed(Q);if(I)await O.link(I);if(W){G();return}K({client:O,entDB:N,stateMgr:U,mode:z,error:void 0})})().catch((N)=>{let U=N instanceof Error?N:Error(String(N));if(console.error("[DIPLOMATIC] useClient init failed",U),!W)K((M)=>({...M,client:void 0,error:U}))}),()=>{W=!0,G?.()}},[J,Q,I,Z,X,V]),Y}import{use as _8,useEffect as MV,useRef as E8,useState as B8}from"react";function qV($,J,Q){let[I,V]=B8();return MV(()=>{async function Z(){let X=await Q();V(X)}return Z(),$.on(J,Z),()=>{$.off(J,Z)}},[$,J,Q]),I}function f8($,J,Q){let I=E8(Q());return MV(()=>{async function V(){I.current=Q()}return $.on(J,V),()=>{$.off(J,V)}},[$,J,Q]),_8(I.current)}function UV($,J){return`${$}:${J}`}class SQ{queue=new Map;async enq($){for(let J of $){let Q=UV(J.host,J.seq);this.queue.set(Q,J)}}async deq($,J){for(let Q of J){let I=UV($,Q);this.queue.delete(I)}}async list(){let $=[];for(let J of this.queue.values())$.push(J);return $}async count(){return this.queue.size}async wipe(){this.queue.clear()}}class LQ{hosts=new Map;async add($){let J={...$,lastSeq:0};this.hosts.set($.label,J)}async touch($,J){let Q=this.hosts.get($);if(!Q||J<=Q.lastSeq)return;this.hosts.set($,{...Q,lastSeq:J})}async get($){return this.hosts.get($)}async set($,J){let Q=this.hosts.get($);if(!Q)return 13;return this.hosts.set($,{...Q,...J}),0}async del($){this.hosts.delete($)}async list(){return this.hosts.values()}async wipe(){this.hosts.clear()}}class _Q{crypto;messages=new Map;constructor($){this.crypto=$}async add($){let J=[];for(let{key:Q,data:I}of $)this.messages.set(d(Q),I),J.push(0);return J}async del($){for(let J of $)this.messages.delete(d(J))}async get($){let J=this.messages.get(d($));if(J)return await k0($,J,this.crypto);return}async has($){return this.messages.has(d($))}async list(){let $=Array.from(this.messages.entries());return await Promise.all($.map(([Q,I])=>{let V=U0(Q);return k0(V,I,this.crypto)}))}async last($){let J;for(let[Q,I]of this.messages){if(w0($,I.eid)===!1)continue;let V=U0(Q);if(J===void 0)J={hash:V,data:I};else if((I.ctr??0)>(J.data.ctr??0)||(I.ctr??0)===(J.data.ctr??0)&&(I.off??0)>(J.data.off??0))J={hash:V,data:I}}if(J)return await k0(J.hash,J.data,this.crypto);return}async listUnapplied(){let $=[];for(let[J,Q]of this.messages){if(!DQ(Q))continue;let I=U0(J);$.push(await k0(I,Q,this.crypto))}return $}async markApplied($){for(let J of $){let Q=d(J),I=this.messages.get(Q);if(!I)continue;this.messages.set(Q,{...a0(I),apld:!0})}}async wipe(){this.messages.clear()}}class EQ{enclave;async save($){return this.enclave=new N$($,z0),this.enclave}async load(){return this.enclave}async wipe(){this.enclave=void 0}}class BQ{queue=new Map;async enq($,J){let Q=this.queue.get($)||new Set;this.queue.set($,Q);for(let I of J)Q.add(C0(I))}async deq($,J){let Q=this.queue.get($);if(Q)for(let I of J)Q.delete(C0(I))}async list($){let J=this.queue.get($);if(!J)return[];let Q=[];for(let I of J)Q.push(i0(I));return Q}async count(){let $=0;for(let J of this.queue.values())$+=J.size;return $}async wipe(){this.queue.clear()}}class zV{seed=new EQ;hosts=new LQ;uploads=new BQ;downloads=new SQ;messages;constructor($){this.messages=new _Q($)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}class OV{singletonType;latest;latestOff=-1;emitter=new v0;constructor($){this.singletonType=$}async apply($){for(let J of $){let Q=new h(J.eid),[I,V]=Q.readStruct(q0);if(V!==0)continue;let Z=new l;Z.writeVarString(this.singletonType);let X=Z.result();if(I.id.length===X.length&&I.id.every((Y,K)=>Y===X[K])){if(this.latest===void 0||J.off>this.latestOff)this.latestOff=J.off,this.latest=J.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 J of $)if(J===this.singletonType)this.emitter.emit(this.singletonType,null)};on=($,J)=>{this.emitter.addEventListener($,J)};off=($,J)=>{this.emitter.removeEventListener($,J)}}async function p9($,J){let Q=await XJ(z0),I=new r0(new L0,$,Q,g$,z0);return{client:I,setSeed:async(Z)=>{let X=i0(Z);await Q.seed.save(X),await Q.hosts.add({handle:J,label:"host",idx:0}),await I.connect()}}}export{S8 as useSyncOnResume,f8 as useStateWatcherSuspense,qV as useStateWatcher,k8 as useClientXferState,j8 as useClientState,L8 as useClient,I$ as shouldEmitItemProgress,XJ as openIDBStore,CQ as openEntIDB,KJ as openDiplomaticClient,qQ as nullStateManager,w8 as nullEntDB,a0 as normalizeStoredMessageData,DQ as isPendingApply,Q$ as idleProgress,i0 as htob,g$ as hostHTTPTransport,p9 as genWebClient,sV as genSingletonEID,UQ as entStateManager,q0 as eidCodec,R$ as defaultPeekProgressEvery,z0 as crypto,C0 as btoh,F$ as WorkerClient,v0 as TypedEventEmitter,r0 as SyncClient,L as Status,QJ as StateManager,OV as SingletonStateManager,zV as MemoryStore,jQ as IDBStore,PJ as HTTPTransport,RQ as EntIDB,YV as EntDBMemory,l as Encoder,h as Decoder,L0 as Clock};
1
+ function pQ($){let J=$.length,Q=0,I=0;while(I<J){let V=$.charCodeAt(I++);if((V&4294967168)===0){Q++;continue}else if((V&4294965248)===0)Q+=2;else{if(V>=55296&&V<=56319){if(I<J){let Z=$.charCodeAt(I);if((Z&64512)===56320)++I,V=((V&1023)<<10)+(Z&1023)+65536}}if((V&4294901760)===0)Q+=3;else Q+=4}}return Q}function PV($,J,Q){let I=$.length,V=Q,Z=0;while(Z<I){let X=$.charCodeAt(Z++);if((X&4294967168)===0){J[V++]=X;continue}else if((X&4294965248)===0)J[V++]=X>>6&31|192;else{if(X>=55296&&X<=56319){if(Z<I){let Y=$.charCodeAt(Z);if((Y&64512)===56320)++Z,X=((X&1023)<<10)+(Y&1023)+65536}}if((X&4294901760)===0)J[V++]=X>>12&15|224,J[V++]=X>>6&63|128;else J[V++]=X>>18&7|240,J[V++]=X>>12&63|128,J[V++]=X>>6&63|128}J[V++]=X&63|128}}var jV=new TextEncoder,kV=50;function SV($,J,Q){jV.encodeInto($,J.subarray(Q))}function cQ($,J,Q){if($.length>kV)SV($,J,Q);else PV($,J,Q)}var LV=4096;function NJ($,J,Q){let I=J,V=I+Q,Z=[],X="";while(I<V){let Y=$[I++];if((Y&128)===0)Z.push(Y);else if((Y&224)===192){let K=$[I++]&63;Z.push((Y&31)<<6|K)}else if((Y&240)===224){let K=$[I++]&63,W=$[I++]&63;Z.push((Y&31)<<12|K<<6|W)}else if((Y&248)===240){let K=$[I++]&63,W=$[I++]&63,G=$[I++]&63,N=(Y&7)<<18|K<<12|W<<6|G;if(N>65535)N-=65536,Z.push(N>>>10&1023|55296),N=56320|N&1023;Z.push(N)}else Z.push(Y);if(Z.length>=LV)X+=String.fromCharCode(...Z),Z.length=0}if(Z.length>0)X+=String.fromCharCode(...Z);return X}var _V=new TextDecoder,EV=200;function BV($,J,Q){let I=$.subarray(J,J+Q);return _V.decode(I)}function lQ($,J,Q){if(Q>EV)return BV($,J,Q);else return NJ($,J,Q)}class t0{type;data;constructor($,J){this.type=$,this.data=J}}class Y0 extends Error{constructor($){super($);let J=Object.create(Y0.prototype);Object.setPrototypeOf(this,J),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Y0.name})}}var e0=4294967295;function rQ($,J,Q){let I=Q/4294967296,V=Q;$.setUint32(J,I),$.setUint32(J+4,V)}function P$($,J,Q){let I=Math.floor(Q/4294967296),V=Q;$.setUint32(J,I),$.setUint32(J+4,V)}function j$($,J){let Q=$.getInt32(J),I=$.getUint32(J+4);return Q*4294967296+I}function hQ($,J){let Q=$.getUint32(J),I=$.getUint32(J+4);return Q*4294967296+I}var fV=-1,xV=4294967295,gV=17179869183;function mV({sec:$,nsec:J}){if($>=0&&J>=0&&$<=gV)if(J===0&&$<=xV){let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,$),Q}else{let Q=$/4294967296,I=$&4294967295,V=new Uint8Array(8),Z=new DataView(V.buffer);return Z.setUint32(0,J<<2|Q&3),Z.setUint32(4,I),V}else{let Q=new Uint8Array(12),I=new DataView(Q.buffer);return I.setUint32(0,J),P$(I,4,$),Q}}function vV($){let J=$.getTime(),Q=Math.floor(J/1000),I=(J-Q*1000)*1e6,V=Math.floor(I/1e9);return{sec:Q+V,nsec:I-V*1e9}}function yV($){if($ instanceof Date){let J=vV($);return mV(J)}else return null}function bV($){let J=new DataView($.buffer,$.byteOffset,$.byteLength);switch($.byteLength){case 4:{let Q=J.getUint32(0),I=0;return{sec:Q,nsec:0}}case 8:{let Q=J.getUint32(0),I=J.getUint32(4),V=(Q&3)*4294967296+I,Z=Q>>>2;return{sec:V,nsec:Z}}case 12:{let Q=j$(J,4),I=J.getUint32(0);return{sec:Q,nsec:I}}default:throw new Y0(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${$.length}`)}}function uV($){let J=bV($);return new Date(J.sec*1000+J.nsec/1e6)}var nQ={type:fV,encode:yV,decode:uV};class $${static defaultCodec=new $$;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(nQ)}register({type:$,encode:J,decode:Q}){if($>=0)this.encoders[$]=J,this.decoders[$]=Q;else{let I=-1-$;this.builtInEncoders[I]=J,this.builtInDecoders[I]=Q}}tryToEncode($,J){for(let Q=0;Q<this.builtInEncoders.length;Q++){let I=this.builtInEncoders[Q];if(I!=null){let V=I($,J);if(V!=null){let Z=-1-Q;return new t0(Z,V)}}}for(let Q=0;Q<this.encoders.length;Q++){let I=this.encoders[Q];if(I!=null){let V=I($,J);if(V!=null)return new t0(Q,V)}}if($ instanceof t0)return $;return null}decode($,J,Q){let I=J<0?this.builtInDecoders[-1-J]:this.decoders[J];if(I)return I($,J,Q);else return new t0(J,$)}}function iV($){return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer}function M$($){if($ instanceof Uint8Array)return $;else if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);else if(iV($))return new Uint8Array($);else return Uint8Array.from($)}var pV=100,cV=2048;class k${extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??$$.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.maxDepth=$?.maxDepth??pV,this.initialBufferSize=$?.initialBufferSize??cV,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 k$({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($,J){if(J>this.maxDepth)throw Error(`Too deep objects in depth ${J}`);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($,J)}ensureBufferSizeToWrite($){let J=this.pos+$;if(this.view.byteLength<J)this.resizeBuffer(J*2)}resizeBuffer($){let J=new ArrayBuffer($),Q=new Uint8Array(J),I=new DataView(J);Q.set(this.bytes),this.view=I,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=pQ($);this.ensureBufferSizeToWrite(5+Q),this.writeStringHeader(Q),cQ($,this.bytes,this.pos),this.pos+=Q}encodeObject($,J){let Q=this.extensionCodec.tryToEncode($,this.context);if(Q!=null)this.encodeExtension(Q);else if(Array.isArray($))this.encodeArray($,J);else if(ArrayBuffer.isView($))this.encodeBinary($);else if(typeof $==="object")this.encodeMap($,J);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply($)}`)}encodeBinary($){let J=$.byteLength;if(J<256)this.writeU8(196),this.writeU8(J);else if(J<65536)this.writeU8(197),this.writeU16(J);else if(J<4294967296)this.writeU8(198),this.writeU32(J);else throw Error(`Too large binary: ${J}`);let Q=M$($);this.writeU8a(Q)}encodeArray($,J){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 I of $)this.doEncode(I,J+1)}countWithoutUndefined($,J){let Q=0;for(let I of J)if($[I]!==void 0)Q++;return Q}encodeMap($,J){let Q=Object.keys($);if(this.sortKeys)Q.sort();let I=this.ignoreUndefined?this.countWithoutUndefined($,Q):Q.length;if(I<16)this.writeU8(128+I);else if(I<65536)this.writeU8(222),this.writeU16(I);else if(I<4294967296)this.writeU8(223),this.writeU32(I);else throw Error(`Too large map object: ${I}`);for(let V of Q){let Z=$[V];if(!(this.ignoreUndefined&&Z===void 0))this.encodeString(V),this.doEncode(Z,J+1)}}encodeExtension($){if(typeof $.data==="function"){let Q=$.data(this.pos+6),I=Q.length;if(I>=4294967296)throw Error(`Too large extension object: ${I}`);this.writeU8(201),this.writeU32(I),this.writeI8($.type),this.writeU8a(Q);return}let J=$.data.length;if(J===1)this.writeU8(212);else if(J===2)this.writeU8(213);else if(J===4)this.writeU8(214);else if(J===8)this.writeU8(215);else if(J===16)this.writeU8(216);else if(J<256)this.writeU8(199),this.writeU8(J);else if(J<65536)this.writeU8(200),this.writeU16(J);else if(J<4294967296)this.writeU8(201),this.writeU32(J);else throw Error(`Too large extension object: ${J}`);this.writeI8($.type),this.writeU8a($.data)}writeU8($){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,$),this.pos++}writeU8a($){let J=$.length;this.ensureBufferSizeToWrite(J),this.bytes.set($,this.pos),this.pos+=J}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),rQ(this.view,this.pos,$),this.pos+=8}writeI64($){this.ensureBufferSizeToWrite(8),P$(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 S$($,J){return new k$(J).encodeSharedRef($)}function L$($){return`${$<0?"-":""}0x${Math.abs($).toString(16).padStart(2,"0")}`}var lV=16,rV=16;class MJ{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor($=lV,J=rV){this.maxKeyLength=$,this.maxLengthPerKey=J,this.caches=[];for(let Q=0;Q<this.maxKeyLength;Q++)this.caches.push([])}canBeCached($){return $>0&&$<=this.maxKeyLength}find($,J,Q){let I=this.caches[Q-1];$:for(let V of I){let Z=V.bytes;for(let X=0;X<Q;X++)if(Z[X]!==$[J+X])continue $;return V.str}return null}store($,J){let Q=this.caches[$.length-1],I={bytes:$,str:J};if(Q.length>=this.maxLengthPerKey)Q[Math.random()*Q.length|0]=I;else Q.push(I)}decode($,J,Q){let I=this.find($,J,Q);if(I!=null)return this.hit++,I;this.miss++;let V=NJ($,J,Q),Z=Uint8Array.prototype.slice.call($,J,J+Q);return this.store(Z,V),V}}var qJ="array",U$="map_key",oQ="map_value",hV=($)=>{if(typeof $==="string"||typeof $==="number")return $;throw new Y0("The type of key must be string or number but "+typeof $)};class aQ{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState($){let J=this.getUninitializedStateFromPool();J.type=qJ,J.position=0,J.size=$,J.array=Array($)}pushMapState($){let J=this.getUninitializedStateFromPool();J.type=U$,J.readCount=0,J.size=$,J.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===qJ){let Q=$;Q.size=0,Q.array=void 0,Q.position=0,Q.type=void 0}if($.type===U$||$.type===oQ){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 q$=-1,UJ=new DataView(new ArrayBuffer(0)),nV=new Uint8Array(UJ.buffer);try{UJ.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 dQ=RangeError("Insufficient data"),dV=new MJ;class _${extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=UJ;bytes=nV;headByte=q$;stack=new aQ;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??$$.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.rawStrings=$?.rawStrings??!1,this.maxStrLength=$?.maxStrLength??e0,this.maxBinLength=$?.maxBinLength??e0,this.maxArrayLength=$?.maxArrayLength??e0,this.maxMapLength=$?.maxMapLength??e0,this.maxExtLength=$?.maxExtLength??e0,this.keyDecoder=$?.keyDecoder!==void 0?$.keyDecoder:dV,this.mapKeyConverter=$?.mapKeyConverter??hV}clone(){return new _$({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=q$,this.stack.reset()}setBuffer($){let J=M$($);this.bytes=J,this.view=new DataView(J.buffer,J.byteOffset,J.byteLength),this.pos=0}appendBuffer($){if(this.headByte===q$&&!this.hasRemaining(1))this.setBuffer($);else{let J=this.bytes.subarray(this.pos),Q=M$($),I=new Uint8Array(J.length+Q.length);I.set(J),I.set(Q,J.length),this.setBuffer(I)}}hasRemaining($){return this.view.byteLength-this.pos>=$}createExtraByteError($){let{view:J,pos:Q}=this;return RangeError(`Extra ${J.byteLength-Q} of ${J.byteLength} byte(s) found at buffer[${$}]`)}decode($){if(this.entered)return this.clone().decode($);try{this.entered=!0,this.reinitializeState(),this.setBuffer($);let J=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return J}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 J=!1,Q;for await(let X of $){if(J)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(X);try{Q=this.doDecodeSync(),J=!0}catch(Y){if(!(Y instanceof RangeError))throw Y}this.totalPos+=this.pos}if(J){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Q}let{headByte:I,pos:V,totalPos:Z}=this;throw RangeError(`Insufficient data in parsing ${L$(I)} at ${Z} (${V} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream($){return this.decodeMultiAsync($,!0)}decodeStream($){return this.decodeMultiAsync($,!1)}async*decodeMultiAsync($,J){if(this.entered){yield*this.clone().decodeMultiAsync($,J);return}try{this.entered=!0;let Q=J,I=-1;for await(let V of $){if(J&&I===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(V),Q)I=this.readArraySize(),Q=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--I===0)break}catch(Z){if(!(Z instanceof RangeError))throw Z}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){$:while(!0){let $=this.readHeadByte(),J;if($>=224)J=$-256;else if($<192)if($<128)J=$;else if($<144){let I=$-128;if(I!==0){this.pushMapState(I),this.complete();continue $}else J={}}else if($<160){let I=$-144;if(I!==0){this.pushArrayState(I),this.complete();continue $}else J=[]}else{let I=$-160;J=this.decodeString(I,0)}else if($===192)J=null;else if($===194)J=!1;else if($===195)J=!0;else if($===202)J=this.readF32();else if($===203)J=this.readF64();else if($===204)J=this.readU8();else if($===205)J=this.readU16();else if($===206)J=this.readU32();else if($===207)if(this.useBigInt64)J=this.readU64AsBigInt();else J=this.readU64();else if($===208)J=this.readI8();else if($===209)J=this.readI16();else if($===210)J=this.readI32();else if($===211)if(this.useBigInt64)J=this.readI64AsBigInt();else J=this.readI64();else if($===217){let I=this.lookU8();J=this.decodeString(I,1)}else if($===218){let I=this.lookU16();J=this.decodeString(I,2)}else if($===219){let I=this.lookU32();J=this.decodeString(I,4)}else if($===220){let I=this.readU16();if(I!==0){this.pushArrayState(I),this.complete();continue $}else J=[]}else if($===221){let I=this.readU32();if(I!==0){this.pushArrayState(I),this.complete();continue $}else J=[]}else if($===222){let I=this.readU16();if(I!==0){this.pushMapState(I),this.complete();continue $}else J={}}else if($===223){let I=this.readU32();if(I!==0){this.pushMapState(I),this.complete();continue $}else J={}}else if($===196){let I=this.lookU8();J=this.decodeBinary(I,1)}else if($===197){let I=this.lookU16();J=this.decodeBinary(I,2)}else if($===198){let I=this.lookU32();J=this.decodeBinary(I,4)}else if($===212)J=this.decodeExtension(1,0);else if($===213)J=this.decodeExtension(2,0);else if($===214)J=this.decodeExtension(4,0);else if($===215)J=this.decodeExtension(8,0);else if($===216)J=this.decodeExtension(16,0);else if($===199){let I=this.lookU8();J=this.decodeExtension(I,1)}else if($===200){let I=this.lookU16();J=this.decodeExtension(I,2)}else if($===201){let I=this.lookU32();J=this.decodeExtension(I,4)}else throw new Y0(`Unrecognized type byte: ${L$($)}`);this.complete();let Q=this.stack;while(Q.length>0){let I=Q.top();if(I.type===qJ)if(I.array[I.position]=J,I.position++,I.position===I.size)J=I.array,Q.release(I);else continue $;else if(I.type===U$){if(J==="__proto__")throw new Y0("The key __proto__ is not allowed");I.key=this.mapKeyConverter(J),I.type=oQ;continue $}else if(I.map[I.key]=J,I.readCount++,I.readCount===I.size)J=I.map,Q.release(I);else{I.key=null,I.type=U$;continue $}}return J}}readHeadByte(){if(this.headByte===q$)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=q$}readArraySize(){let $=this.readHeadByte();switch($){case 220:return this.readU16();case 221:return this.readU32();default:if($<160)return $-144;else throw new Y0(`Unrecognized array type byte: ${L$($)}`)}}pushMapState($){if($>this.maxMapLength)throw new Y0(`Max length exceeded: map length (${$}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState($)}pushArrayState($){if($>this.maxArrayLength)throw new Y0(`Max length exceeded: array length (${$}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState($)}decodeString($,J){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String($,J);return this.decodeBinary($,J)}decodeUtf8String($,J){if($>this.maxStrLength)throw new Y0(`Max length exceeded: UTF-8 byte length (${$}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+J+$)throw dQ;let Q=this.pos+J,I;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached($))I=this.keyDecoder.decode(this.bytes,Q,$);else I=lQ(this.bytes,Q,$);return this.pos+=J+$,I}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===U$;return!1}decodeBinary($,J){if($>this.maxBinLength)throw new Y0(`Max length exceeded: bin length (${$}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining($+J))throw dQ;let Q=this.pos+J,I=this.bytes.subarray(Q,Q+$);return this.pos+=J+$,I}decodeExtension($,J){if($>this.maxExtLength)throw new Y0(`Max length exceeded: ext length (${$}) > maxExtLength (${this.maxExtLength})`);let Q=this.view.getInt8(this.pos+J),I=this.decodeBinary($,J+1);return this.extensionCodec.decode(I,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 $=hQ(this.view,this.pos);return this.pos+=8,$}readI64(){let $=j$(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 zJ($,J){return new _$(J).decode($)}class v0{listeners=new Map;addEventListener($,J){let Q=this.listeners.get($);if(!Q)Q=new Set,this.listeners.set($,Q);return Q.add(J),()=>{this.removeEventListener($,J)}}removeEventListener($,J){let Q=this.listeners.get($);if(Q){if(Q.delete(J),Q.size===0)this.listeners.delete($)}}emit($,J){let Q=this.listeners.get($);if(Q){let I=Array.from(Q);for(let V of I)V(J)}}emitAll($){let J=Array.from(this.listeners.keys());for(let Q of J)this.emit(Q,$)}}class A0{getter;static eventName="update";emitter;constructor($){this.getter=$;this.emitter=new v0}get=()=>this.getter();async emit(){let $=await this.getter();queueMicrotask(()=>this.emitter.emit(A0.eventName,$))}listen($){return this.emitter.addEventListener(A0.eventName,$),()=>{this.emitter.removeEventListener(A0.eventName,$)}}}var y0=64;var sQ=32,b0=8;var E$=32;var tQ=30000,eQ=512,L;((H)=>{H[H.Success=0]="Success";H[H.InvalidSignature=3]="InvalidSignature";H[H.ClockOutOfSync=4]="ClockOutOfSync";H[H.UserNotRegistered=5]="UserNotRegistered";H[H.ServerMisconfigured=6]="ServerMisconfigured";H[H.MissingBody=7]="MissingBody";H[H.ExtraBodyContent=8]="ExtraBodyContent";H[H.MissingParam=9]="MissingParam";H[H.InvalidParam=10]="InvalidParam";H[H.InvalidRequest=11]="InvalidRequest";H[H.InternalError=12]="InternalError";H[H.NotFound=13]="NotFound";H[H.InvalidMessage=14]="InvalidMessage";H[H.NoChange=15]="NoChange";H[H.DatabaseClosed=16]="DatabaseClosed";H[H.StorageError=17]="StorageError";H[H.DatabaseError=18]="DatabaseError";H[H.HashMismatch=19]="HashMismatch";H[H.DecryptionError=20]="DecryptionError";H[H.NotImplemented=21]="NotImplemented";H[H.MissingSeed=22]="MissingSeed";H[H.OutOfBounds=23]="OutOfBounds";H[H.HostError=24]="HostError";H[H.CommunicationError=25]="CommunicationError";H[H.VarLimitExceeded=26]="VarLimitExceeded";H[H.InvalidResponse=27]="InvalidResponse";H[H.ConnectionClosed=28]="ConnectionClosed"})(L||={});function j($){return[$,0]}function q($){return[void 0,$]}function oV($){if($<0)console.info("N",$),console.trace();if(typeof $!=="bigint")$=BigInt($);if($<0n)return q(10);let J=[];while($>0n){let Q=Number($&0x7fn);if($>>=7n,$>0n)J.push(Q|128);else J.push(Q)}if(J.length===0)return j(new Uint8Array([0]));if(J.length>8)return q(26);return j(new Uint8Array(J))}function aV($,J=0){let Q=0n,I=0,V=J;while(!0){if(V>=$.length)return q(14);let Z=$[V++];if(Z===void 0)return q(14);if(Q|=BigInt(Z&127)<<BigInt(I),(Z&128)===0){if(V-J>8)return q(26);return j({value:Q>0x1fffffffffffffn?Q:Number(Q),bytesRead:V-J})}if(I+=7,I>=56)return q(26)}}class n{data;pos=0;constructor($){this.data=$}static async fromResponse($){let J=await $.arrayBuffer(),Q=new Uint8Array(J);return new n(Q)}readBigInt(){if(this.pos+8>this.data.length)return q(7);let $=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,j($)}readDate(){let[$,J]=this.readVarInt();if(J!==0)return q(J);return j(new Date($))}readVarInt(){let[$,J]=aV(this.data,this.pos);if(J!==0)return q(J);this.pos+=$.bytesRead;let Q=$.value;return j(typeof Q==="bigint"?Number(Q):Q)}readVarString(){let[$,J]=this.readVarInt();if(J!==0)return q(J);let[Q,I]=this.readBytes($);if(I!==0)return q(I);let V=new TextDecoder().decode(Q);return j(V)}readBytes($){if($<0)return q(10);if(this.pos+$>this.data.length)return q(23);let J=this.data.slice(this.pos,this.pos+$);return this.pos+=$,j(J)}readVarBytes(){let[$,J]=this.readVarInt();if(J!==0)return q(J);return this.readBytes($)}readStruct($){return $.decode(this)}readStructs($){let J=[];while(!this.done()){let[Q,I]=this.readStruct($);if(I!==0)return q(I);J.push(Q)}return j(J)}readBytesSeq($){let J=[];while(!this.done()){let[Q,I]=this.readBytes($);if(I!==0)return q(I);J.push(Q)}return j(J)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class l{parts=[];writeBigInt($){let J=new Uint8Array(8);new DataView(J.buffer).setBigUint64(0,$,!1),this.parts.push(J)}writeDate($){let J=$.getTime();return this.writeVarInt(J)}writeVarInt($){let[J,Q]=oV($);if(Q!==0)return Q;return this.parts.push(J),0}writeVarString($){let J=new TextEncoder().encode($),Q=this.writeVarInt(J.length);if(Q!==0)return Q;return this.writeBytes(J),0}prependBytes($){this.parts.unshift($)}writeBytes($){this.parts.push($)}writeVarBytes($){let J=this.writeVarInt($.length);if(J!==0)return J;return this.writeBytes($),0}writeStruct($,J){return $.encode(this,J)}writeStructs($,J){for(let Q of J){let I=this.writeStruct($,Q);if(I!==0)return I}return 0}writeBytesSeq($){for(let J of $)this.writeBytes(J)}result(){let $=this.parts.reduce((I,V)=>I+V.length,0),J=new Uint8Array($),Q=0;for(let I of this.parts)J.set(I,Q),Q+=I.length;return J}*scan(){for(let $ of this.parts)yield $}}async function OJ($,J,Q){let I=new l,V=I.writeDate(J);if(V!==0)return q(V);let Z=I.result(),X=await Q.signEd25519(Z,$.privateKey);return j({pubKey:$.publicKey,sig:X,timestamp:J})}async function u0($,J,Q){let I=Q.now().getTime(),V=$.timestamp.getTime();if(Math.abs(I-V)>tQ)return 4;let X=new l;X.writeDate($.timestamp);let Y=X.result();if(!await J.checkSigEd25519($.sig,Y,$.pubKey))return 3;return 0}var q0={encode($,J){let Q=$.writeVarBytes(J.id);if(Q!==0)return Q;let I=$.writeDate(J.ts);if(I!==0)return I;return 0},decode($){let[J,Q]=$.readVarBytes();if(Q!==0)return q(Q);let[I,V]=$.readDate();if(V!==0)return q(V);return j({id:J,ts:I})}};function J$($){let J=new l,Q=J.writeStruct(q0,$);if(Q!==0)return q(Q);let I=J.result();return j(I)}async function sV($){return J$({id:$,ts:new Date(0)})}var R0={encode($,J){let Q=$.writeVarBytes(J.eid);if(Q!==0)return Q;let I=$.writeVarInt(J.off);if(I!==0)return I;let V=$.writeVarInt(J.ctr);if(V!==0)return V;let Z=$.writeVarInt(J.len);if(Z!==0)return Z;if(J.hsh)$.writeBytes(J.hsh);return 0},decode($){let[J,Q]=$.readVarBytes();if(Q!==0)return q(Q);let I=new n(J),[,V]=q0.decode(I);if(V!==0)return q(V);let[Z,X]=$.readVarInt();if(X!==0)return q(X);let[Y,K]=$.readVarInt();if(K!==0)return q(K);let[W,G]=$.readVarInt();if(G!==0)return q(G);let N;if(W>0){let[U,M]=$.readBytes(E$);if(M!==0)return q(M);N=U}return j({eid:J,off:Z,ctr:Y,len:W,hsh:N})}};function C0($){return Array.from($).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}function i0($){if($.length%2!==0)throw Error("Invalid hex string");let J=new Uint8Array($.length/2);for(let Q=0;Q<$.length;Q+=2)J[Q/2]=Number.parseInt($.substr(Q,2),16);return J}function w0($,J){if($===J)return!0;if($.byteLength!==J.byteLength)return!1;return $.every((Q,I)=>Q===J[I])}var d;if(typeof Uint8Array.prototype.toBase64==="function")d=($)=>$.toBase64();else d=($)=>btoa(String.fromCharCode(...$));var U0;if(typeof Uint8Array.fromBase64==="function")U0=($)=>Uint8Array.fromBase64($);else U0=($)=>Uint8Array.from(atob($),(J)=>J.charCodeAt(0));function z$($,J){let Q=new Uint8Array($.length+J.length);return Q.set($,0),Q.set(J,$.length),Q}function $I($,J,Q){return Q.checkSigEd25519($.sig,$.headCph,J)}async function HJ($,J,Q){let I=z$(J.privateKey,$);return(await Q.blake3(I)).slice(0,b0)}async function JI($,J,Q,I){let V;if($.bod&&$.len>0)V=await Q.blake3($.bod);let Z=new l,X=R0.encode(Z,{...$,hsh:V});if(X!==0)return q(X);let Y=Z.result(),K=await HJ(Y,J,Q),W=await I.deriveFromKDM(K),G=await Q.encryptXSalsa20Poly1305Combined(Y,W),N=$.bod?await Q.encryptXSalsa20Poly1305Combined($.bod,W):new Uint8Array(0),U=await Q.signEd25519(G,J.privateKey);return j({sig:U,kdm:K,headCph:G,bodyCph:N})}async function RJ($,J,Q,I){let V=new n($),[Z,X]=R0.decode(V);if(X!==0)return q(14);let Y;try{Y=J&&J.length>0?await I.decryptXSalsa20Poly1305Combined(J,Q):void 0}catch{return q(20)}let K=Z.hsh&&Y===void 0,W=Z.hsh===void 0&&Y!==void 0;if(K||W)return q(19);if(Z.hsh&&Y){let N=await I.blake3(Y);if(!w0(N,Z.hsh))return q(19)}let G=await I.blake3($);return j({msgHead:Z,bod:Y,headHash:G})}class L0{now(){return new Date}}function QI($,J,Q,I){let V=J.getTime()-$.getTime(),Z=Q.getTime()-I.getTime();return(V+Z)/2}var O$={encode($,J){if($.writeVarInt(J.quota),J.quota>0){if(J.usage===void 0)return 9;$.writeVarInt(J.usage)}return 0},decode($){let[J,Q]=$.readVarInt();if(Q!==0)return q(Q);let I;if(J>0){let[V,Z]=$.readVarInt();if(Z!==0)return q(Z);I=V}return j({quota:J,usage:I})}};var CJ={encode($,J){$.writeBytes(new Uint8Array([J.status]));let Q=$.writeDate(J.timeRcvd);if(Q!==0)return Q;let I=$.writeDate(J.timeSent);if(I!==0)return I;let V=$.writeVarInt(J.subscription.term);if(V!==0)return V;let Z=$.writeVarInt(J.subscription.elapsed);if(Z!==0)return Z;let X=$.writeStruct(O$,J.subscription.stat);if(X!==0)return X;let Y=$.writeStruct(O$,J.subscription.dyn);if(Y!==0)return Y;return 0},decode($){let[J,Q]=$.readBytes(1);if(Q!==0)return q(Q);let I=J[0],[V,Z]=$.readDate();if(Z!==0)return q(Z);let[X,Y]=$.readDate();if(Y!==0)return q(Y);let[K,W]=$.readVarInt();if(W!==0)return q(W);let[G,N]=$.readVarInt();if(N!==0)return q(N);let[U,M]=$.readStruct(O$);if(M!==0)return q(M);let[O,z]=$.readStruct(O$);if(z!==0)return q(z);return j({status:I,timeRcvd:V,timeSent:X,subscription:{term:K,elapsed:G,stat:U,dyn:O}})}};async function wJ($,J,Q){let{crypto:I,enclave:V}=$,Z=await V.derive(J,Q);return await I.deriveEd25519KeyPair(Z)}var TJ={encode($,J){let Q=$.writeVarBytes(J.headCph);if(Q!==0)return Q;let I=$.writeVarInt(J.seq);if(I!==0)return I;return 0},decode($){let[J,Q]=$.readVarBytes();if(Q!==0)return q(Q);let[I,V]=$.readVarInt();if(V!==0)return q(V);return j({headCph:J,seq:I})}};var W0={encode($,J){$.writeBytes(J.pubKey),$.writeBytes(J.sig);let Q=$.writeDate(J.timestamp);if(Q!==0)return Q;return 0},decode($){let[J,Q]=$.readBytes(sQ);if(Q!==0)return q(Q);let[I,V]=$.readBytes(y0);if(V!==0)return q(V);let[Z,X]=$.readDate();if(X!==0)return q(X);return j({pubKey:J,sig:I,timestamp:Z})}};var II={async encodeReq($,J,Q,I,V){let Z=V.writeStruct(W0,Q);if(Z!==0)return Z;for(let X of I)V.writeVarInt(X);return 0},async handleReq($,J,Q){let{clock:I,crypto:V,storage:Z}=$,[X,Y]=J.readStruct(W0);if(Y!==0)return Y;let K=await u0(X,V,I);if(K!==0)return K;let{pubKey:W}=X,[G,N]=await Z.hasUser(W);if(N!==0)return N;if(!G)return 5;let[U,M]=J.readVarInt();if(M!==0)return M;if(!J.done())return 8;let[O,z]=await Z.listHeads(W,U);if(z!==0)return z;return Q.writeStructs(TJ,O)},decodeResp($){return $.readStructs(TJ)}};var DJ={encode($,J){$.writeVarInt(J.seq);let Q=$.writeVarBytes(J.bodyCph);if(Q!==0)return Q;return 0},decode($){let[J,Q]=$.readVarInt();if(Q!==0)return q(Q);let[I,V]=$.readVarBytes();if(V!==0)return q(V);return j({seq:J,bodyCph:I})}};var VI={async encodeReq($,J,Q,I,V){let Z=V.writeStruct(W0,Q);if(Z!==0)return Z;for(let X of I){let Y=V.writeVarInt(X);if(Y!==0)return Y}return 0},async handleReq($,J,Q){let{clock:I,crypto:V,storage:Z}=$,[X,Y]=J.readStruct(W0);if(Y!==0)return Y;let K=await u0(X,V,I);if(K!==0)return K;let{pubKey:W}=X,[G,N]=await Z.hasUser(W);if(N!==0)return N;if(!G)return 5;let U=[];while(!J.done()){let[z,R]=J.readVarInt();if(R!==0)return R;U.push(z)}console.info(`PULL: ${U.length} bags`);let[M,O]=await Z.getBodies(W,U);if(O!==0)return O;if(!M)return 17;for(let{seq:z,bodyCph:R}of M){let D={seq:z,bodyCph:R},w=Q.writeStruct(DJ,D);if(w!==0)return w}return 0},decodeResp($){return $.readStructs(DJ)}};var FJ={encode($,J){$.writeBytes(J.sig),$.writeBytes(J.kdm);let Q=$.writeVarBytes(J.headCph);if(Q!==0)return Q;let I=$.writeVarBytes(J.bodyCph);if(I!==0)return I;return 0},decode($){let[J,Q]=$.readBytes(y0);if(Q!==0)return q(Q);let[I,V]=$.readBytes(b0);if(V!==0)return q(V);let[Z,X]=$.readVarBytes();if(X!==0)return q(X);let[Y,K]=$.readVarBytes();if(K!==0)return q(K);return j({sig:J,kdm:I,headCph:Z,bodyCph:Y})}};var B$={encode($,J){let Q=$.writeVarInt(J.seq);if(Q!==0)return Q;let I=$.writeVarBytes(J.headCph);if(I!==0)return I;let V=J.bodyCph?J.bodyCph.length:0,Z=$.writeVarInt(V);if(Z!==0)return Z;if(V>0){if(!J.bodyCph)return 10;$.writeBytes(J.bodyCph)}return 0},decode($){let[J,Q]=$.readVarInt();if(Q!==0)return q(Q);let[I,V]=$.readVarBytes();if(V!==0)return q(V);let[Z,X]=$.readVarInt();if(X!==0)return q(X);let Y;if(Z>0){let[K,W]=$.readBytes(Z);if(W!==0)return q(W);Y=K}return j({seq:J,headCph:I,bodyCph:Y})}};var f$={encode($,J){$.writeBytes(J.sig),$.writeBytes(J.kdm);let Q=$.writeVarBytes(J.headCph);if(Q!==0)return Q;return 0},decode($){let[J,Q]=$.readBytes(y0);if(Q!==0)return q(Q);let[I,V]=$.readBytes(b0);if(V!==0)return q(V);let[Z,X]=$.readVarBytes();if(X!==0)return q(X);return j({sig:J,kdm:I,headCph:Z})}};var x$={encode($,J){if($.writeVarInt(J.idx),$.writeBytes(new Uint8Array([J.status])),J.status===0)$.writeVarInt(J.seq);return 0},decode($){let[J,Q]=$.readVarInt();if(Q!==0)return q(Q);let[I,V]=$.readBytes(1);if(V!==0)return q(V);let Z=I[0];if(Z!==0)return j({idx:J,status:Z});let[X,Y]=$.readVarInt();if(Y!==0)return q(Y);return j({idx:J,status:Z,seq:X})}};var ZI={async encodeReq($,J,Q,I,V){let Z=V.writeStruct(W0,Q);if(Z!==0)return Z;let X=V.writeStructs(FJ,I);if(X!==0)return X;return 0},async handleReq($,J,Q){let{clock:I,crypto:V,storage:Z,notifier:X}=$,[Y,K]=J.readStruct(W0);if(K!==0)return K;let W=await u0(Y,V,I);if(W!==0)return W;let{pubKey:G}=Y,[N,U]=await Z.hasUser(G);if(U!==0)return U;if(!N)return 5;let[M,O]=J.readStructs(FJ);if(O!==0)return O;console.info(`PUSH: ${M.length} bags`);let z=[],R=[];for(let A=0;A<M.length;A++){let S=M[A];if(!await $I(S,G,V)){let f={idx:A,status:3},B=Q.writeStruct(x$,f);if(B!==0)return B;continue}z.push(A),R.push(S)}let[D,w]=await Z.setBags(G,R);if(w!==0)return w;if(!D||D.length!==R.length)return 17;let F=[];for(let A=0;A<R.length;A++){let S=R[A],y=z[A],f=D[A],B=new l,m=B.writeStruct(f$,S);if(m!==0)return m;let u=B.result(),H={seq:f,headCph:u};if(M.length===1&&S.bodyCph.length<=eQ)H.bodyCph=S.bodyCph;F.push(H);let g={idx:y,status:0,seq:f},p=Q.writeStruct(x$,g);if(p!==0)return p}if(F.length>0){let A=new l,S=A.writeStructs(B$,F);if(S!==0)return S;let y=A.result();await Promise.resolve(X.push(G,y))}return 0},decodeResp($){return $.readStructs(x$)}};var XI={async encodeReq($,J,Q,I,V){return V.writeStruct(W0,Q)},async handleReq($,J,Q){let{clock:I,crypto:V,storage:Z}=$,[X,Y]=J.readStruct(W0);if(Y!==0)return Y;let K=await u0(X,V,I);if(K!==0)return K;let{pubKey:W}=X;if(!J.done())return 8;let[G,N]=await Z.addUser(W);if(N!==0)return N;return 0},decodeResp($){return j(void 0)}};class AJ{url;websocket;constructor($){this.url=$}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect($,J,Q=()=>{},I=()=>{}){let{url:V}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let Z=new l;Z.writeStruct(W0,$);let X=Z.result(),Y=C0(X);return V.searchParams.set("t",Y),this.websocket=new WebSocket(V),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),I()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Q()},this.websocket.onmessage=(K)=>{let W=new Uint8Array(K.data);J(W)},this.websocket.onerror=(K)=>{console.log(`ERROR: ${JSON.stringify(K)}`),this.websocket=void 0,Q()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var Z0={user:{path:"/user",endpoint:XI,name:0},push:{path:"/push",endpoint:ZI,name:2},peek:{path:"/peek",endpoint:II,name:1},pull:{path:"/pull",endpoint:VI,name:3}},tV={0:Z0.user,2:Z0.push,1:Z0.peek,3:Z0.pull},bK={[Z0.user.path]:Z0.user,[Z0.push.path]:Z0.push,[Z0.peek.path]:Z0.peek,[Z0.pull.path]:Z0.pull};class PJ{url;listener;constructor($){this.url=$;this.listener=new AJ($)}async call($,J){let{path:Q}=tV[$],I=new URL(Q,this.url);try{return await eV(I,J)}catch{return q(25)}}}var g$=($)=>{return new PJ($.handle)};async function eV($,J){let Q=await fetch($,{method:"POST",body:J.result().slice()});if(!Q.ok)return q(24);let I=await n.fromResponse(Q);return j(I)}class m${enclave;crypto;host;clock;transport;updateHostMeta;constructor($,J,Q,I,V,Z){this.enclave=$;this.crypto=J;this.host=Q;this.clock=I;this.transport=V;this.updateHostMeta=Z}async call($,J){let{clock:Q,crypto:I,transport:V}=this,{endpoint:Z,name:X}=$,Y=await this.keys(),K=Q.now(),[W,G]=await OJ(Y,K,I);if(G!==0)return q(G);let N=new l,U=await Z.encodeReq(this,Y,W,J,N);if(U!==0)return q(U);let M=Q.now(),[O,z]=await V.call(X,N),R=Q.now();if(z!==0)return q(z);let[D,w]=O.readStruct(CJ);if(w!==0)return q(w);if(D.status!==0)return q(D.status);let A={clockOffset:QI(M,D.timeRcvd,D.timeSent,R),subscription:D.subscription},S=await this.updateHostMeta(A);if(S!==0)return q(S);return Z.decodeResp(O)}keys=()=>{let{host:$}=this;return wJ(this,$.label,$.idx)};seal=async($)=>{let{crypto:J,enclave:Q}=this,I=await this.keys();return JI($,I,J,Q)};register=()=>this.call(Z0.user,[]);peek=($)=>this.call(Z0.peek,[$]);push=($)=>this.call(Z0.push,$);pull=($)=>this.call(Z0.pull,$);listen=async($,J,Q)=>{let{clock:I,crypto:V,host:Z,transport:X}=this,{listener:Y}=X,K=await wJ(this,Z.label,Z.idx),W=I.now(),[G,N]=await OJ(K,W,V);if(N!==0)return N;return await Y.connect(G,$,J,Q)};isConnected(){let $=this.transport?.listener;if($&&typeof $.connected==="function")return $.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var jJ={encode($,J){let Q=$.writeVarString(J.lbl);if(Q!==0)return Q;let I=$.writeVarInt(J.idx);if(I!==0)return I;let V=$.writeVarInt(J.num);if(V!==0)return V;return $.writeBytes(J.hsh),$.writeBytes(J.sig),0},decode($){let[J,Q]=$.readVarString();if(Q!==0)return q(Q);let[I,V]=$.readVarInt();if(V!==0)return q(V);let[Z,X]=$.readVarInt();if(X!==0)return q(X);let[Y,K]=$.readBytes(E$);if(K!==0)return q(K);let[W,G]=$.readBytes(y0);if(G!==0)return q(G);return j({lbl:J,idx:I,num:Z,hsh:Y,sig:W})}};var kJ={encode($,J){let Q=$.writeStruct(jJ,J.head);if(Q!==0)return Q;let I=$.writeVarBytes(J.indexEnc);if(I!==0)return I;let V=$.writeVarBytes(J.bodyEnc);if(V!==0)return V;return 0},decode($){let[J,Q]=$.readStruct(jJ);if(Q!==0)return q(Q);let[I,V]=$.readVarBytes();if(V!==0)return q(V);let[Z,X]=$.readVarBytes();if(X!==0)return q(X);return j({head:J,indexEnc:I,bodyEnc:Z})}};var SJ={encode($,J){$.writeBytes(J.kdm);let Q=$.writeVarBytes(J.headCph);if(Q!==0)return Q;let I=$.writeVarInt(J.lenBody);if(I!==0)return I;if(J.lenBody>0&&J.offBody!==void 0){let V=$.writeVarInt(J.offBody);if(V!==0)return V}return 0},decode($){let[J,Q]=$.readBytes(b0);if(Q!==0)return q(Q);let[I,V]=$.readVarBytes();if(V!==0)return q(V);let[Z,X]=$.readVarInt();if(X!==0)return q(X);let Y;if(Z>0){let[K,W]=$.readVarInt();if(W!==0)return q(W);Y=K}return j({kdm:J,headCph:I,lenBody:Z,offBody:Y})}};async function YI($,J,Q,I,V){let Z=await V.derive($,J),X=await I.deriveEd25519KeyPair(Z),Y=new l,K=new l,W=0,G=0;for(let w of Q){let F=new l,A=F.writeStruct(R0,w.head);if(A!==0)return q(A);let S=F.result(),y=await HJ(S,X,I),f=await V.deriveFromKDM(y),B=await I.encryptXSalsa20Poly1305Combined(S,f),m=w.body?await I.encryptXSalsa20Poly1305Combined(w.body,f):new Uint8Array(0),u=w.head.len>0&&w.head.hsh!==void 0?m.length:0,H={kdm:y,headCph:B,lenBody:u,offBody:u>0?G:void 0},g=Y.writeStruct(SJ,H);if(g!==0)return q(g);if(w.body)K.writeBytes(m),G+=m.length;W++}let N=K.result(),U=Y.result(),M=await I.blake3(U),O=await I.signEd25519(M,X.privateKey),z={lbl:$,idx:J,num:W,hsh:M,sig:O},R=new l;R.writeStruct(kJ,{head:z,indexEnc:U,bodyEnc:N});let D=R.result();return j(D)}async function KI($,J,Q){let[I,V]=kJ.decode(new n($));if(V!==0)return q(V);let{head:Z,indexEnc:X,bodyEnc:Y}=I,K=await Q.derive(Z.lbl,Z.idx),W=await J.deriveEd25519KeyPair(K);if(!await J.checkSigEd25519(Z.sig,Z.hsh,W.publicKey))return q(3);let N=await J.blake3(X);if(!w0(N,Z.hsh))return q(19);let U=new n(X),M=[];for(let z=0;z<Z.num;z++){let[R,D]=U.readStruct(SJ);if(D!==0)return q(D);M.push(R)}if(M.length!==Z.num)return q(14);let O=[];for(let z of M){let R=await Q.deriveFromKDM(z.kdm),D=await J.decryptXSalsa20Poly1305Combined(z.headCph,R),[w,F]=R0.decode(new n(D));if(F!==0)return q(F);let A;if(z.lenBody>0&&z.offBody!==void 0){if(w.hsh===void 0)return q(14);let S=Y.slice(z.offBody,z.offBody+z.lenBody);A=await J.decryptXSalsa20Poly1305Combined(S,R);let y=await J.blake3(A);if(!w0(y,w.hsh))return q(19)}O.push({head:w,body:A})}return j(O)}async function GI({now:$,bod:J,crypto:Q}){let I=await Q.genRandomBytes(8),V=new l,Z=V.writeStruct(q0,{id:I,ts:$});if(Z!==0)return q(Z);let X=V.result();return v$({now:$,eid:X,ctr:0,bod:J,crypto:Q})}async function v$({now:$,eid:J,ctr:Q,bod:I,crypto:V}){let Z=new n(J),[X,Y]=q0.decode(Z);if(Y!==0)return q(Y);let K=$.getTime()-X.ts.getTime(),W,G=I?.length??0;if(I&&G>0)W=await V.blake3(I);return j({eid:J,off:K,ctr:Q,len:G,hsh:W})}class y${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 J=await $();while(this.again)this.again=!1,J=await $();return J}finally{this.inflight=null}}}var b$=100;class H${timer=null;delayMs;work;tail=new y$;constructor($,J){this.delayMs=$<0?0:$,this.work=J}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)}}var Q$={phase:"idle"},R$=50;function I$($,J,Q){if($<=0||J<=0)return!1;if($===1||$===J)return!0;return $%Q===0}function u$($,J){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob($,J);return}let Q=URL.createObjectURL($),I=document.createElement("a");I.href=Q,I.download=J,document.body.appendChild(I),I.click(),document.body.removeChild(I),URL.revokeObjectURL(Q)}async function LJ($,J,Q,I){let V=new n($.headCph),[Z,X]=V.readStruct(f$);if(X!==0)return q(X);let{sig:Y,kdm:K,headCph:W}=Z;if(!await I.checkSigEd25519(Y,W,J.publicKey))return q(3);let N=await Q.deriveFromKDM(K),U;try{U=await I.decryptXSalsa20Poly1305Combined(W,N)}catch{return q(20)}return j({kdm:K,headEnc:U})}var _J=1048576,EJ=1048576;function $Z($){return $.sig.length+$.kdm.length+$.headCph.length+$.bodyCph.length}async function JZ($,J,Q,I,V){if(I.length<1)return 0;let[Z,X]=await $.push(I);if(X!==0)return X;if(!Z)return 27;for(let K of Z){if(K.status!==0){console.error("push err",K);continue}let W=V[K.idx];if(!W){console.error("no hash",K);continue}await J.uploads.deq(Q,[W])}let Y=await J.hosts.get(Q);if(Y){let K=Y.lastSeq,W=K,G=[];for(let N of Z)if(N.status===0)G.push(N.seq);G.sort((N,U)=>N-U);for(let N of G)if(N===K+1)K=N;if(K>W)await J.hosts.touch(Q,K)}return 0}async function QZ($,J,Q,I,V,Z,X){if(Z.length<1)return 0;let Y=new Map,K=[];for(let R of Z)Y.set(R.seq,R),K.push(R.seq);let[W,G]=await $.pull(K);if(G!==0)return G;if(!W)return 27;let N=[],U=[],M=[];for(let{seq:R,bodyCph:D}of W){let w=Y.get(R);if(!w)continue;let{head:F}=w,A=new l;A.writeStruct(R0,F);let S=A.result(),y=await V.blake3(S),f=await Q.deriveFromKDM(w.kdm),[B,m]=await RJ(S,D,f,V);if(m!==0){await J.downloads.deq(I,[R]);continue}let u={head:F,body:B.bod},H=MI(u);U.push({key:y,data:H}),N.push(u),M.push(R)}let O=await J.messages.add(U);await J.downloads.deq(I,M);let z=await X(N,{enqueueUpload:!1,triggerUpload:!1});for(let R=0;R<z.length;R++){let D=O[R];if(D!==0&&D!==15)console.error("ERR storing",L[D],"for message",R);let w=z[R];if(w!==0&&w!==15)console.error("ERR applying",L[w],"for message",R)}return 0}async function WI({conn:$,store:J,enclave:Q,host:I,crypto:V,onProgress:Z,peekProgressEvery:X}){let Y=await $.keys(),K=[],[W,G]=await $.peek(I.lastSeq);if(G!==0)return G;let N=W.length,U=X??R$;if(Z&&N>0)Z({phase:"peek",host:I.label,done:0,total:N});let M=0;for(let O of W){let[z,R]=await LJ(O,Y,Q,V);if(R!==0){if(console.error("peek: decrypting item head",R),M+=1,Z&&I$(M,N,U))Z({phase:"peek",host:I.label,done:M,total:N});continue}let D=await V.blake3(z.headEnc);if(await J.messages.has(D)){if(console.info("peek: skipping download enqueue"),await J.uploads.deq(I.label,[D]),M+=1,Z&&I$(M,N,U))Z({phase:"peek",host:I.label,done:M,total:N});continue}let F=new n(z.headEnc),[A,S]=F.readStruct(R0);if(S!==0){if(console.error("peek: reading item head",S),M+=1,Z&&I$(M,N,U))Z({phase:"peek",host:I.label,done:M,total:N});continue}if(K.push({kdm:z.kdm,head:A,seq:O.seq,host:I.label}),M+=1,Z&&I$(M,N,U))Z({phase:"peek",host:I.label,done:M,total:N})}if(await J.downloads.enq(K),W.length>0){let O=Math.max(...W.map((z)=>z.seq));await J.hosts.touch(I.label,O)}if(Z)Z({phase:"peek",host:I.label,done:N,total:N});return 0}async function NI({conn:$,store:J,host:Q,maxPushBytes:I,onProgress:V}){let Z=I??_J,X=await J.uploads.list(Q.label),Y=X.length,K=0;if(V&&Y>0)V({phase:"push",host:Q.label,done:0,total:Y});let W=[],G=[],N=0,U=async()=>{if(W.length<1)return 0;let M=W.length,O=await JZ($,J,Q.label,W,G);if(W=[],G=[],N=0,O===0){if(K+=M,V)V({phase:"push",host:Q.label,done:K,total:Y})}return O};for(let M of X){let O=await J.messages.get(M);if(!O){K+=1;continue}let z={...O.head,bod:O.body},[R,D]=await $.seal(z);if(D!==0)return D;if(!R)return 12;let w=$Z(R);if(W.length>0&&N+w>Z){let F=await U();if(F!==0)return F}if(W.push(R),G.push(M),N+=w,N>=Z){let F=await U();if(F!==0)return F}}return U()}async function BJ({conn:$,store:J,enclave:Q,host:I,crypto:V,maxPullBytes:Z,onProgress:X},Y){let K=Z??EJ,W=await J.downloads.list(),G=Array.from(W).filter((R)=>R.host===I.label);if(G.length<1)return 15;let N=G.length,U=0;if(X)X({phase:"pull",host:I.label,done:0,total:N});let M=[],O=0,z=async()=>{if(M.length<1)return 0;let R=M.length,D=await QZ($,J,Q,I.label,V,M,Y);if(M=[],O=0,D===0){if(U+=R,X)X({phase:"pull",host:I.label,done:U,total:N}),X({phase:"apply",host:I.label,done:U,total:N})}return D};for(let R of G){let D=R.head.len;if(M.length>0&&O+D>K){let w=await z();if(w!==0)return w}if(M.push(R),O+=D,O>=K){let w=await z();if(w!==0)return w}}return z()}function MI({head:$,body:J}){return{eid:$.eid,...$.off!==0?{off:$.off}:{},...$.ctr!==0?{ctr:$.ctr}:{},body:J,apld:!1}}async function qI($,{conn:J,store:Q,enclave:I,host:V,crypto:Z,clock:X,maxPullBytes:Y,maxPushBytes:K,onProgress:W,peekProgressEvery:G},N,U){let M=V.label,O=await J.keys(),z=new n($),[R,D]=z.readStructs(B$);if(D!==0){console.error("Failed decoding notif",L[D]);return}let w=!1,A=(await Q.hosts.get(M))?.lastSeq,S=[],y=[];for(let H of R){let[g,p]=await LJ({seq:H.seq,headCph:H.headCph},O,I,Z);if(p!==0){console.error("Failed decrypting notif",L[p]);continue}let r=await Z.blake3(g.headEnc);if(await Q.messages.has(r))continue;let o=new n(g.headEnc),[C,P]=o.readStruct(R0);if(P!==0){console.error("Failed to parse head",L[P]);continue}if(!H.bodyCph&&C.len>0){y.push(H.seq);let _={seq:H.seq,host:M,kdm:g.kdm,head:C};await Q.downloads.enq([_])}else S.push({...g,head:C,bodyCph:H.bodyCph,headEncHash:r});if(A===void 0||H.seq!==A+1)console.log("out of seq",H.seq,A),w=!0;else A=H.seq}if(A!==void 0)await Q.hosts.touch(V.label,A);let f=[],B=[];for(let H of S){let g=await I.deriveFromKDM(H.kdm),[p,r]=await RJ(H.headEnc,H.bodyCph,g,Z);if(r!==0){console.error("Failed to open body",L[r]);continue}let o={head:H.head,body:p.bod},C=MI(o),P={key:H.headEncHash,data:C};B.push(P),f.push(o)}let m=await Q.messages.add(B),u=await N(f,{enqueueUpload:!1,triggerUpload:!1});if(W&&f.length>0)W({phase:"apply",host:V.label,done:f.length,total:f.length});for(let H=0;H<u.length;H++){let g=m[H];if(g!==0&&g!==15)console.error("ERR storing",L[g],"for message",H);let p=u[H];if(p!==0&&p!==15)console.error("ERR applying",L[p],"for message",H)}if(w)U();else await BJ({conn:J,store:Q,enclave:I,host:V,crypto:Z,clock:X,maxPullBytes:Y,maxPushBytes:K,onProgress:W,peekProgressEvery:G},N)}class r0{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;syncRuns=new y$;applyChain=Promise.resolve();clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=R$;lastProgress=Q$;scheduledSync;constructor($,J,Q,I,V,Z=!0,X=_J,Y=EJ,K){this.clock=$;this.state=J;this.store=Q;this.transport=I;this.crypto=V;this.forceSkewHandlingByDefault=Z;this.onScheduleSync=K;this.maxPushBytes=X,this.maxPullBytes=Y,this.clientState=new A0(()=>this.getClientState()),this.xferState=new A0(()=>this.getXferState()),this.scheduledSync=new H$(b$,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(W){console.error("Debounced sync failed:",W)}})}emitProgress=($)=>{this.lastProgress=$,this.xferState.emit()};async setSeed($){await this.store.seed.save($),this.clientState.emit()}async getClientState(){let{store:$,connections:J}=this,Q=await $.seed.load(),I=await $.hosts.list(),V=!1;for(let Z of J.values())if(Z.isConnected()){V=!0;break}return{hasSeed:Q!==void 0,hasHost:Array.from(I).length>0,connected:V}}async getXferState(){let{uploads:$,downloads:J}=this.store,Q=await $.count();return{numDownloads:await J.count(),numUploads:Q,progress:this.lastProgress}}apply=async($,J={enqueueUpload:!0,triggerUpload:!0})=>{let Q=[],I=[];for(let{head:Z,body:X}of $){let Y=new l;Y.writeStruct(R0,Z);let K=Y.result(),W=await this.crypto.blake3(K),G={eid:Z.eid,...Z.off!==0?{off:Z.off}:{},...Z.ctr!==0?{ctr:Z.ctr}:{},body:X,apld:!1};Q.push(W),I.push({key:W,data:G})}await this.store.messages.add(I);let V=await this.applyHashes(Q);if(J.enqueueUpload){let Z=[];for(let X=0;X<Q.length;X++){let Y=V[X];if(Y===0||Y===15)Z.push(Q[X])}if(Z.length>0){let X=await this.store.hosts.list();for(let Y of X)await this.store.uploads.enq(Y.label,Z);this.xferState.emit()}}if(J.triggerUpload)this.scheduleSync();return V};enqueueApplyJob($){let J=this.applyChain.then($,$);return this.applyChain=J.then(()=>{return},()=>{return}),J}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let $=await this.store.messages.listUnapplied();if($.length<1)return[];return this.applyStored($)}applyHashes=($)=>{return this.enqueueApplyJob(async()=>{let J=[];for(let V of $){let Z=await this.store.messages.get(V);if(Z)J.push(Z)}let Q=await this.applyStored(J),I=new Map;for(let V=0;V<J.length;V++)I.set(d(J[V].hash),Q[V]??12);return $.map((V)=>I.get(d(V))??13)})};async applyStored($){if($.length<1)return[];let J=$.map((V)=>({...V.head,bod:V.body})),Q=await this.state.apply(J),I=[];for(let V=0;V<$.length;V++){let Z=Q[V];if(Z===0||Z===15)I.push($[V].hash)}if(I.length>0)await this.store.messages.markApplied(I);return Q}async insertRaw($){let{clock:J,crypto:Q}=this,[I,V]=await GI({now:J.now(),bod:$,crypto:Q});if(V!==0)return q(V);return await this.apply([{head:I,body:$}]),j(I)}async upsertRaw($,J,Q=!1){let{clock:I,crypto:V,store:Z}=this,X=I.now(),Y=await Z.messages.last($);if(Y){let M=new n($),[O,z]=M.readStruct(q0);if(z!==0)return q(z);if(O.ts.getTime()+Y.head.off>X.getTime()){if(Q===!1)return q(4);let D=Y.head.off+1,w=Y.head.ctr+1,F={eid:$,off:D,ctr:w,len:0},S=(await this.apply([{head:F,body:void 0}]))[0];if(S!==0)return q(S);if(J===void 0)return j(F);let[y,f]=J$({id:O.id,ts:X});if(f!==0)return q(f);let B={now:X,eid:y,ctr:0,bod:J,crypto:V},[m,u]=await v$(B);if(u!==0)return q(u);let g=(await this.apply([{head:m,body:J}]))[0];if(g!==0)return q(g);return j(m)}}let K=(Y?.head.ctr??-1)+1,[W,G]=await v$({now:X,eid:$,ctr:K,bod:J,crypto:V});if(G!==0)return q(G);let U=(await this.apply([{head:W,body:J}]))[0];if(U!==0)return q(U);return j(W)}async insert($){let{body:J,type:Q,gid:I,pid:V}=$,X=S$({body:J,type:Q,gid:I,pid:V});return this.insertRaw(X)}async upsert($,J=this.forceSkewHandlingByDefault){let{eid:Q,body:I,type:V,gid:Z,pid:X}=$;if(Q===void 0)return this.insert($);let K=S$({body:I,type:V,gid:Z,pid:X});return this.upsertRaw(Q,K,J)}async delete($){return this.upsertRaw($,void 0,!0)}async genEID($){let{clock:J,crypto:Q}=this,I=J.now();if($!==void 0)return J$({id:$,ts:I});let V=await Q.genRandomBytes(8);return J$({id:V,ts:I})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{clock:$,connections:J,crypto:Q,store:I}=this,V=await I.seed.load();if(!V)return 22;await this.drainApplyQueue();for(let[Z,X]of J){let Y=await I.hosts.get(Z);if(!Y)continue;let K={conn:X,store:I,enclave:V,clock:$,host:Y,crypto:Q,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},W=await WI(K);if(W!==0)return console.error(`Failed to peek: ${W}`),W;this.xferState.emit();let G=await NI(K);if(G!==0)return console.error(`Failed to push: ${G}`),G;this.xferState.emit();let N=await BJ(K,this.apply.bind(this));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=Q$,this.clientState.emit(),this.xferState.emit()}import=async($,J)=>{let{crypto:Q,store:I}=this,V=J?.onProgress,Z=await I.seed.load();if(!Z)return 22;console.time("import: decoding file...");let X=await $.bytes(),[Y,K]=await KI(X,Q,Z);if(K!==0)return K;console.timeEnd("import: decoding file...");let W=0;while(W<Y.length){let G=0,N=0,U=W;for(let z=W;z<Y.length&&N<100&&G<102400;z++)G+=Y[z].head.len,N++,U=z+1;let M=Y.slice(W,U);console.time(`import: applying [${W}, ${U}]`);let O=await this.apply(M,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${W}, ${U}]`);for(let z=0;z<M.length;z++){let R=O[z];if(R!==0&&R!==15)console.warn(`failed to import msg ${W+z}: ${L[R]}`)}if(V)queueMicrotask(()=>V(U,Y.length,0));this.emitProgress({phase:"import",done:U,total:Y.length}),W=U}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:$,store:J}=this,Q=await J.seed.load();if(!Q)return q(22);let I=await J.messages.list();return YI("export",0,I,$,Q)}async export($){let[J,Q]=await this.exportBytes();if(Q!==0)return Q;if(!J)return 12;let I=new Blob([J.slice()]);return u$(I,$),0}async link($,J=!0){if(await this.store.hosts.add($),this.clientState.emit(),J){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($,J=!0,Q=!0)=>{let{clock:I,connections:V,crypto:Z,store:X,transport:Y}=this,K=V.get($.label);if(K){if(K.isConnected())return;try{K.closeListener()}catch{}V.delete($.label)}let W=await X.seed.load();if(!W)return;console.info(`Connecting to ${$.handle} (${$.label})`);let G=new m$(W,Z,$,I,Y($),(N)=>X.hosts.set($.label,N));if(await G.register(),J)await G.listen(async(N)=>{let U={conn:G,store:X,enclave:W,host:$,crypto:Z,clock:I,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return qI(N,U,this.apply,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(V.set($.label,G),this.clientState.emit(),Q)this.scheduleSync()};async connect($=!0,J=!0){let{connectToHost:Q,scheduleSync:I,store:V}=this;if(!await V.seed.load())return;await this.drainApplyQueue();let X=await V.hosts.list();for(let Y of X)await Q(Y,$,!1);if(J)I()}disconnect=async()=>{for(let $ of this.connections.values())try{$.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var h0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function i$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function fJ($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function I0($,...J){if(!fJ($))throw Error("Uint8Array expected");if(J.length>0&&!J.includes($.length))throw Error("Uint8Array expected of length "+J+", got length="+$.length)}function xJ($,J=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(J&&$.finished)throw Error("Hash#digest() has already been called")}function UI($,J){I0($);let Q=J.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function gJ($){if(typeof $!=="boolean")throw Error(`boolean expected, not ${$}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var _0=($)=>new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4));var IZ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!IZ)throw Error("Non little-endian hardware is not supported");function VZ($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function p$($){if(typeof $==="string")$=VZ($);else if(fJ($))$=c$($);else throw Error("Uint8Array expected, got "+typeof $);return $}function zI($,J){if(J==null||typeof J!=="object")throw Error("options must be defined");return Object.assign($,J)}function OI($,J){if($.length!==J.length)return!1;let Q=0;for(let I=0;I<$.length;I++)Q|=$[I]^J[I];return Q===0}var HI=($,J)=>{function Q(I,...V){if(I0(I),$.nonceLength!==void 0){let G=V[0];if(!G)throw Error("nonce / iv required");if($.varSizeNonce)I0(G);else I0(G,$.nonceLength)}let Z=$.tagLength;if(Z&&V[1]!==void 0)I0(V[1]);let X=J(I,...V),Y=(G,N)=>{if(N!==void 0){if(G!==2)throw Error("cipher output not supported");I0(N)}},K=!1;return{encrypt(G,N){if(K)throw Error("cannot encrypt() twice with same key + nonce");return K=!0,I0(G),Y(X.encrypt.length,N),X.encrypt(G,N)},decrypt(G,N){if(I0(G),Z&&G.length<Z)throw Error("invalid ciphertext length: smaller than tagLength="+Z);return Y(X.decrypt.length,N),X.decrypt(G,N)}}}return Object.assign(Q,$),Q};function mJ($,J,Q=!0){if(J===void 0)return new Uint8Array($);if(J.length!==$)throw Error("invalid output length, expected "+$+", got: "+J.length);if(Q&&!ZZ(J))throw Error("invalid output, must be aligned");return J}function ZZ($){return $.byteOffset%4===0}function c$($){return Uint8Array.from($)}function P0(...$){for(let J=0;J<$.length;J++)$[J].fill(0)}function l$($=32){if(h0&&typeof h0.getRandomValues==="function")return h0.getRandomValues(new Uint8Array($));if(h0&&typeof h0.randomBytes==="function")return h0.randomBytes($);throw Error("crypto.getRandomValues must be defined")}var CI=($)=>Uint8Array.from($.split("").map((J)=>J.charCodeAt(0))),XZ=CI("expand 16-byte k"),YZ=CI("expand 32-byte k"),KZ=_0(XZ),GZ=_0(YZ);function k($,J){return $<<J|$>>>32-J}function vJ($){return $.byteOffset%4===0}var r$=64,WZ=16,wI=4294967295,RI=new Uint32Array;function NZ($,J,Q,I,V,Z,X,Y){let K=V.length,W=new Uint8Array(r$),G=_0(W),N=vJ(V)&&vJ(Z),U=N?_0(V):RI,M=N?_0(Z):RI;for(let O=0;O<K;X++){if($(J,Q,I,G,X,Y),X>=wI)throw Error("arx: counter overflow");let z=Math.min(r$,K-O);if(N&&z===r$){let R=O/4;if(O%4!==0)throw Error("arx: invalid block position");for(let D=0,w;D<WZ;D++)w=R+D,M[w]=U[w]^G[D];O+=r$;continue}for(let R=0,D;R<z;R++)D=O+R,Z[D]=V[D]^W[R];O+=z}}function TI($,J){let{allowShortKeys:Q,extendNonceFn:I,counterLength:V,counterRight:Z,rounds:X}=zI({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},J);if(typeof $!=="function")throw Error("core must be a function");return i$(V),i$(X),gJ(Z),gJ(Q),(Y,K,W,G,N=0)=>{I0(Y),I0(K),I0(W);let U=W.length;if(G===void 0)G=new Uint8Array(U);if(I0(G),i$(N),N<0||N>=wI)throw Error("arx: counter overflow");if(G.length<U)throw Error(`arx: output (${G.length}) is shorter than data (${U})`);let M=[],O=Y.length,z,R;if(O===32)M.push(z=c$(Y)),R=GZ;else if(O===16&&Q)z=new Uint8Array(32),z.set(Y),z.set(Y,16),R=KZ,M.push(z);else throw Error(`arx: invalid 32-byte key, got length=${O}`);if(!vJ(K))M.push(K=c$(K));let D=_0(z);if(I){if(K.length!==24)throw Error("arx: extended nonce must be 24 bytes");I(R,D,_0(K.subarray(0,16)),D),K=K.subarray(16)}let w=16-V;if(w!==K.length)throw Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){let A=new Uint8Array(12);A.set(K,Z?0:12-K.length),K=A,M.push(K)}let F=_0(K);return NZ($,R,D,F,W,G,N,X),P0(...M),G}}var X0=($,J)=>$[J++]&255|($[J++]&255)<<8;class DI{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,$=p$($),I0($,32);let J=X0($,0),Q=X0($,2),I=X0($,4),V=X0($,6),Z=X0($,8),X=X0($,10),Y=X0($,12),K=X0($,14);this.r[0]=J&8191,this.r[1]=(J>>>13|Q<<3)&8191,this.r[2]=(Q>>>10|I<<6)&7939,this.r[3]=(I>>>7|V<<9)&8191,this.r[4]=(V>>>4|Z<<12)&255,this.r[5]=Z>>>1&8190,this.r[6]=(Z>>>14|X<<2)&8191,this.r[7]=(X>>>11|Y<<5)&8065,this.r[8]=(Y>>>8|K<<8)&8191,this.r[9]=K>>>5&127;for(let W=0;W<8;W++)this.pad[W]=X0($,16+2*W)}process($,J,Q=!1){let I=Q?0:2048,{h:V,r:Z}=this,X=Z[0],Y=Z[1],K=Z[2],W=Z[3],G=Z[4],N=Z[5],U=Z[6],M=Z[7],O=Z[8],z=Z[9],R=X0($,J+0),D=X0($,J+2),w=X0($,J+4),F=X0($,J+6),A=X0($,J+8),S=X0($,J+10),y=X0($,J+12),f=X0($,J+14),B=V[0]+(R&8191),m=V[1]+((R>>>13|D<<3)&8191),u=V[2]+((D>>>10|w<<6)&8191),H=V[3]+((w>>>7|F<<9)&8191),g=V[4]+((F>>>4|A<<12)&8191),p=V[5]+(A>>>1&8191),r=V[6]+((A>>>14|S<<2)&8191),o=V[7]+((S>>>11|y<<5)&8191),C=V[8]+((y>>>8|f<<8)&8191),P=V[9]+(f>>>5|I),T=0,_=T+B*X+m*(5*z)+u*(5*O)+H*(5*M)+g*(5*U);T=_>>>13,_&=8191,_+=p*(5*N)+r*(5*G)+o*(5*W)+C*(5*K)+P*(5*Y),T+=_>>>13,_&=8191;let v=T+B*Y+m*X+u*(5*z)+H*(5*O)+g*(5*M);T=v>>>13,v&=8191,v+=p*(5*U)+r*(5*N)+o*(5*G)+C*(5*W)+P*(5*K),T+=v>>>13,v&=8191;let x=T+B*K+m*Y+u*X+H*(5*z)+g*(5*O);T=x>>>13,x&=8191,x+=p*(5*M)+r*(5*U)+o*(5*N)+C*(5*G)+P*(5*W),T+=x>>>13,x&=8191;let E=T+B*W+m*K+u*Y+H*X+g*(5*z);T=E>>>13,E&=8191,E+=p*(5*O)+r*(5*M)+o*(5*U)+C*(5*N)+P*(5*G),T+=E>>>13,E&=8191;let i=T+B*G+m*W+u*K+H*Y+g*X;T=i>>>13,i&=8191,i+=p*(5*z)+r*(5*O)+o*(5*M)+C*(5*U)+P*(5*N),T+=i>>>13,i&=8191;let c=T+B*N+m*G+u*W+H*K+g*Y;T=c>>>13,c&=8191,c+=p*X+r*(5*z)+o*(5*O)+C*(5*M)+P*(5*U),T+=c>>>13,c&=8191;let h=T+B*U+m*N+u*G+H*W+g*K;T=h>>>13,h&=8191,h+=p*Y+r*X+o*(5*z)+C*(5*O)+P*(5*M),T+=h>>>13,h&=8191;let a=T+B*M+m*U+u*N+H*G+g*W;T=a>>>13,a&=8191,a+=p*K+r*Y+o*X+C*(5*z)+P*(5*O),T+=a>>>13,a&=8191;let Q0=T+B*O+m*M+u*U+H*N+g*G;T=Q0>>>13,Q0&=8191,Q0+=p*W+r*K+o*Y+C*X+P*(5*z),T+=Q0>>>13,Q0&=8191;let V0=T+B*z+m*O+u*M+H*U+g*N;T=V0>>>13,V0&=8191,V0+=p*G+r*W+o*K+C*Y+P*X,T+=V0>>>13,V0&=8191,T=(T<<2)+T|0,T=T+_|0,_=T&8191,T=T>>>13,v+=T,V[0]=_,V[1]=v,V[2]=x,V[3]=E,V[4]=i,V[5]=c,V[6]=h,V[7]=a,V[8]=Q0,V[9]=V0}finalize(){let{h:$,pad:J}=this,Q=new Uint16Array(10),I=$[1]>>>13;$[1]&=8191;for(let X=2;X<10;X++)$[X]+=I,I=$[X]>>>13,$[X]&=8191;$[0]+=I*5,I=$[0]>>>13,$[0]&=8191,$[1]+=I,I=$[1]>>>13,$[1]&=8191,$[2]+=I,Q[0]=$[0]+5,I=Q[0]>>>13,Q[0]&=8191;for(let X=1;X<10;X++)Q[X]=$[X]+I,I=Q[X]>>>13,Q[X]&=8191;Q[9]-=8192;let V=(I^1)-1;for(let X=0;X<10;X++)Q[X]&=V;V=~V;for(let X=0;X<10;X++)$[X]=$[X]&V|Q[X];$[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 Z=$[0]+J[0];$[0]=Z&65535;for(let X=1;X<8;X++)Z=($[X]+J[X]|0)+(Z>>>16)|0,$[X]=Z&65535;P0(Q)}update($){xJ(this);let{buffer:J,blockLen:Q}=this;$=p$($);let I=$.length;for(let V=0;V<I;){let Z=Math.min(Q-this.pos,I-V);if(Z===Q){for(;Q<=I-V;V+=Q)this.process($,V);continue}if(J.set($.subarray(V,V+Z),this.pos),this.pos+=Z,V+=Z,this.pos===Q)this.process(J,0,!1),this.pos=0}return this}destroy(){P0(this.h,this.r,this.buffer,this.pad)}digestInto($){xJ(this),UI($,this),this.finished=!0;let{buffer:J,h:Q}=this,{pos:I}=this;if(I){J[I++]=1;for(;I<16;I++)J[I]=0;this.process(J,0,!0)}this.finalize();let V=0;for(let Z=0;Z<8;Z++)$[V++]=Q[Z]>>>0,$[V++]=Q[Z]>>>8;return $}digest(){let{buffer:$,outputLen:J}=this;this.digestInto($);let Q=$.slice(0,J);return this.destroy(),Q}}function MZ($){let J=(I,V)=>$(V).update(p$(I)).digest(),Q=$(new Uint8Array(32));return J.outputLen=Q.outputLen,J.blockLen=Q.blockLen,J.create=(I)=>$(I),J}var yJ=MZ(($)=>new DI($));function qZ($,J,Q,I,V,Z=20){let X=$[0],Y=J[0],K=J[1],W=J[2],G=J[3],N=$[1],U=Q[0],M=Q[1],O=V,z=0,R=$[2],D=J[4],w=J[5],F=J[6],A=J[7],S=$[3],y=X,f=Y,B=K,m=W,u=G,H=N,g=U,p=M,r=O,o=z,C=R,P=D,T=w,_=F,v=A,x=S;for(let i=0;i<Z;i+=2)u^=k(y+T|0,7),r^=k(u+y|0,9),T^=k(r+u|0,13),y^=k(T+r|0,18),o^=k(H+f|0,7),_^=k(o+H|0,9),f^=k(_+o|0,13),H^=k(f+_|0,18),v^=k(C+g|0,7),B^=k(v+C|0,9),g^=k(B+v|0,13),C^=k(g+B|0,18),m^=k(x+P|0,7),p^=k(m+x|0,9),P^=k(p+m|0,13),x^=k(P+p|0,18),f^=k(y+m|0,7),B^=k(f+y|0,9),m^=k(B+f|0,13),y^=k(m+B|0,18),g^=k(H+u|0,7),p^=k(g+H|0,9),u^=k(p+g|0,13),H^=k(u+p|0,18),P^=k(C+o|0,7),r^=k(P+C|0,9),o^=k(r+P|0,13),C^=k(o+r|0,18),T^=k(x+v|0,7),_^=k(T+x|0,9),v^=k(_+T|0,13),x^=k(v+_|0,18);let E=0;I[E++]=X+y|0,I[E++]=Y+f|0,I[E++]=K+B|0,I[E++]=W+m|0,I[E++]=G+u|0,I[E++]=N+H|0,I[E++]=U+g|0,I[E++]=M+p|0,I[E++]=O+r|0,I[E++]=z+o|0,I[E++]=R+C|0,I[E++]=D+P|0,I[E++]=w+T|0,I[E++]=F+_|0,I[E++]=A+v|0,I[E++]=S+x|0}function UZ($,J,Q,I){let V=$[0],Z=J[0],X=J[1],Y=J[2],K=J[3],W=$[1],G=Q[0],N=Q[1],U=Q[2],M=Q[3],O=$[2],z=J[4],R=J[5],D=J[6],w=J[7],F=$[3];for(let S=0;S<20;S+=2)K^=k(V+R|0,7),U^=k(K+V|0,9),R^=k(U+K|0,13),V^=k(R+U|0,18),M^=k(W+Z|0,7),D^=k(M+W|0,9),Z^=k(D+M|0,13),W^=k(Z+D|0,18),w^=k(O+G|0,7),X^=k(w+O|0,9),G^=k(X+w|0,13),O^=k(G+X|0,18),Y^=k(F+z|0,7),N^=k(Y+F|0,9),z^=k(N+Y|0,13),F^=k(z+N|0,18),Z^=k(V+Y|0,7),X^=k(Z+V|0,9),Y^=k(X+Z|0,13),V^=k(Y+X|0,18),G^=k(W+K|0,7),N^=k(G+W|0,9),K^=k(N+G|0,13),W^=k(K+N|0,18),z^=k(O+M|0,7),U^=k(z+O|0,9),M^=k(U+z|0,13),O^=k(M+U|0,18),R^=k(F+w|0,7),D^=k(R+F|0,9),w^=k(D+R|0,13),F^=k(w+D|0,18);let A=0;I[A++]=V,I[A++]=W,I[A++]=O,I[A++]=F,I[A++]=G,I[A++]=N,I[A++]=U,I[A++]=M}var bJ=TI(qZ,{counterRight:!0,extendNonceFn:UZ}),uJ=HI({blockSize:64,nonceLength:24,tagLength:16},($,J)=>{return{encrypt(Q,I){I=mJ(Q.length+32,I,!1);let V=I.subarray(0,32),Z=I.subarray(32);I.set(Q,32),P0(V),bJ($,J,I,I);let X=yJ(Z,V);return I.set(X,16),P0(I.subarray(0,16),X),I.subarray(16)},decrypt(Q,I){I0(Q),I=mJ(Q.length+32,I,!1);let V=I.subarray(0,32),Z=I.subarray(32,48),X=I.subarray(48);I.set(Q,32),P0(V);let Y=bJ($,J,V,V),K=yJ(X,Y);if(!OI(Z,K))throw Error("invalid tag");return bJ($,J,I.subarray(16),I.subarray(16)),P0(V,Z,K),X}}});function zZ($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function iJ($,...J){if(!zZ($))throw Error("Uint8Array expected");if(J.length>0&&!J.includes($.length))throw Error("Uint8Array expected of length "+J+", got length="+$.length)}function pJ($,J=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(J&&$.finished)throw Error("Hash#digest() has already been called")}function FI($,J){iJ($);let Q=J.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}var n0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */var h$=($)=>new DataView($.buffer,$.byteOffset,$.byteLength);function AI($){if(typeof $!=="string")throw Error("utf8ToBytes expected string, got "+typeof $);return new Uint8Array(new TextEncoder().encode($))}function cJ($){if(typeof $==="string")$=AI($);return iJ($),$}class lJ{clone(){return this._cloneInto()}}function PI($){let J=(I)=>$().update(cJ(I)).digest(),Q=$();return J.outputLen=Q.outputLen,J.blockLen=Q.blockLen,J.create=()=>$(),J}function jI($=32){if(n0&&typeof n0.getRandomValues==="function")return n0.getRandomValues(new Uint8Array($));if(n0&&typeof n0.randomBytes==="function")return n0.randomBytes($);throw Error("crypto.getRandomValues must be defined")}function OZ($,J,Q,I){if(typeof $.setBigUint64==="function")return $.setBigUint64(J,Q,I);let V=BigInt(32),Z=BigInt(4294967295),X=Number(Q>>V&Z),Y=Number(Q&Z),K=I?4:0,W=I?0:4;$.setUint32(J+K,X,I),$.setUint32(J+W,Y,I)}class rJ extends lJ{constructor($,J,Q,I){super();this.blockLen=$,this.outputLen=J,this.padOffset=Q,this.isLE=I,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array($),this.view=h$(this.buffer)}update($){pJ(this);let{view:J,buffer:Q,blockLen:I}=this;$=cJ($);let V=$.length;for(let Z=0;Z<V;){let X=Math.min(I-this.pos,V-Z);if(X===I){let Y=h$($);for(;I<=V-Z;Z+=I)this.process(Y,Z);continue}if(Q.set($.subarray(Z,Z+X),this.pos),this.pos+=X,Z+=X,this.pos===I)this.process(J,0),this.pos=0}return this.length+=$.length,this.roundClean(),this}digestInto($){pJ(this),FI($,this),this.finished=!0;let{buffer:J,view:Q,blockLen:I,isLE:V}=this,{pos:Z}=this;if(J[Z++]=128,this.buffer.subarray(Z).fill(0),this.padOffset>I-Z)this.process(Q,0),Z=0;for(let G=Z;G<I;G++)J[G]=0;OZ(Q,I-8,BigInt(this.length*8),V),this.process(Q,0);let X=h$($),Y=this.outputLen;if(Y%4)throw Error("_sha2: outputLen should be aligned to 32bit");let K=Y/4,W=this.get();if(K>W.length)throw Error("_sha2: outputLen bigger than state");for(let G=0;G<K;G++)X.setUint32(4*G,W[G],V)}digest(){let{buffer:$,outputLen:J}=this;this.digestInto($);let Q=$.slice(0,J);return this.destroy(),Q}_cloneInto($){$||($=new this.constructor),$.set(...this.get());let{blockLen:J,buffer:Q,length:I,finished:V,destroyed:Z,pos:X}=this;if($.length=I,$.pos=X,$.finished=V,$.destroyed=Z,I%J)$.buffer.set(Q);return $}}var n$=BigInt(4294967295),hJ=BigInt(32);function kI($,J=!1){if(J)return{h:Number($&n$),l:Number($>>hJ&n$)};return{h:Number($>>hJ&n$)|0,l:Number($&n$)|0}}function HZ($,J=!1){let Q=new Uint32Array($.length),I=new Uint32Array($.length);for(let V=0;V<$.length;V++){let{h:Z,l:X}=kI($[V],J);[Q[V],I[V]]=[Z,X]}return[Q,I]}var RZ=($,J)=>BigInt($>>>0)<<hJ|BigInt(J>>>0),CZ=($,J,Q)=>$>>>Q,wZ=($,J,Q)=>$<<32-Q|J>>>Q,TZ=($,J,Q)=>$>>>Q|J<<32-Q,DZ=($,J,Q)=>$<<32-Q|J>>>Q,FZ=($,J,Q)=>$<<64-Q|J>>>Q-32,AZ=($,J,Q)=>$>>>Q-32|J<<64-Q,PZ=($,J)=>J,jZ=($,J)=>$,kZ=($,J,Q)=>$<<Q|J>>>32-Q,SZ=($,J,Q)=>J<<Q|$>>>32-Q,LZ=($,J,Q)=>J<<Q-32|$>>>64-Q,_Z=($,J,Q)=>$<<Q-32|J>>>64-Q;function EZ($,J,Q,I){let V=(J>>>0)+(I>>>0);return{h:$+Q+(V/4294967296|0)|0,l:V|0}}var BZ=($,J,Q)=>($>>>0)+(J>>>0)+(Q>>>0),fZ=($,J,Q,I)=>J+Q+I+($/4294967296|0)|0,xZ=($,J,Q,I)=>($>>>0)+(J>>>0)+(Q>>>0)+(I>>>0),gZ=($,J,Q,I,V)=>J+Q+I+V+($/4294967296|0)|0,mZ=($,J,Q,I,V)=>($>>>0)+(J>>>0)+(Q>>>0)+(I>>>0)+(V>>>0),vZ=($,J,Q,I,V,Z)=>J+Q+I+V+Z+($/4294967296|0)|0;var yZ={fromBig:kI,split:HZ,toBig:RZ,shrSH:CZ,shrSL:wZ,rotrSH:TZ,rotrSL:DZ,rotrBH:FZ,rotrBL:AZ,rotr32H:PZ,rotr32L:jZ,rotlSH:kZ,rotlSL:SZ,rotlBH:LZ,rotlBL:_Z,add:EZ,add3L:BZ,add3H:fZ,add4L:xZ,add4H:gZ,add5H:vZ,add5L:mZ},b=yZ;var[bZ,uZ]=(()=>b.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(($)=>BigInt($))))(),p0=new Uint32Array(80),c0=new Uint32Array(80);class SI extends rJ{constructor(){super(128,64,16,!1);this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:$,Al:J,Bh:Q,Bl:I,Ch:V,Cl:Z,Dh:X,Dl:Y,Eh:K,El:W,Fh:G,Fl:N,Gh:U,Gl:M,Hh:O,Hl:z}=this;return[$,J,Q,I,V,Z,X,Y,K,W,G,N,U,M,O,z]}set($,J,Q,I,V,Z,X,Y,K,W,G,N,U,M,O,z){this.Ah=$|0,this.Al=J|0,this.Bh=Q|0,this.Bl=I|0,this.Ch=V|0,this.Cl=Z|0,this.Dh=X|0,this.Dl=Y|0,this.Eh=K|0,this.El=W|0,this.Fh=G|0,this.Fl=N|0,this.Gh=U|0,this.Gl=M|0,this.Hh=O|0,this.Hl=z|0}process($,J){for(let w=0;w<16;w++,J+=4)p0[w]=$.getUint32(J),c0[w]=$.getUint32(J+=4);for(let w=16;w<80;w++){let F=p0[w-15]|0,A=c0[w-15]|0,S=b.rotrSH(F,A,1)^b.rotrSH(F,A,8)^b.shrSH(F,A,7),y=b.rotrSL(F,A,1)^b.rotrSL(F,A,8)^b.shrSL(F,A,7),f=p0[w-2]|0,B=c0[w-2]|0,m=b.rotrSH(f,B,19)^b.rotrBH(f,B,61)^b.shrSH(f,B,6),u=b.rotrSL(f,B,19)^b.rotrBL(f,B,61)^b.shrSL(f,B,6),H=b.add4L(y,u,c0[w-7],c0[w-16]),g=b.add4H(H,S,m,p0[w-7],p0[w-16]);p0[w]=g|0,c0[w]=H|0}let{Ah:Q,Al:I,Bh:V,Bl:Z,Ch:X,Cl:Y,Dh:K,Dl:W,Eh:G,El:N,Fh:U,Fl:M,Gh:O,Gl:z,Hh:R,Hl:D}=this;for(let w=0;w<80;w++){let F=b.rotrSH(G,N,14)^b.rotrSH(G,N,18)^b.rotrBH(G,N,41),A=b.rotrSL(G,N,14)^b.rotrSL(G,N,18)^b.rotrBL(G,N,41),S=G&U^~G&O,y=N&M^~N&z,f=b.add5L(D,A,y,uZ[w],c0[w]),B=b.add5H(f,R,F,S,bZ[w],p0[w]),m=f|0,u=b.rotrSH(Q,I,28)^b.rotrBH(Q,I,34)^b.rotrBH(Q,I,39),H=b.rotrSL(Q,I,28)^b.rotrBL(Q,I,34)^b.rotrBL(Q,I,39),g=Q&V^Q&X^V&X,p=I&Z^I&Y^Z&Y;R=O|0,D=z|0,O=U|0,z=M|0,U=G|0,M=N|0,{h:G,l:N}=b.add(K|0,W|0,B|0,m|0),K=X|0,W=Y|0,X=V|0,Y=Z|0,V=Q|0,Z=I|0;let r=b.add3L(m,H,p);Q=b.add3H(r,B,u,g),I=r|0}({h:Q,l:I}=b.add(this.Ah|0,this.Al|0,Q|0,I|0)),{h:V,l:Z}=b.add(this.Bh|0,this.Bl|0,V|0,Z|0),{h:X,l:Y}=b.add(this.Ch|0,this.Cl|0,X|0,Y|0),{h:K,l:W}=b.add(this.Dh|0,this.Dl|0,K|0,W|0),{h:G,l:N}=b.add(this.Eh|0,this.El|0,G|0,N|0),{h:U,l:M}=b.add(this.Fh|0,this.Fl|0,U|0,M|0),{h:O,l:z}=b.add(this.Gh|0,this.Gl|0,O|0,z|0),{h:R,l:D}=b.add(this.Hh|0,this.Hl|0,R|0,D|0),this.set(Q,I,V,Z,X,Y,K,W,G,N,U,M,O,z,R,D)}roundClean(){p0.fill(0),c0.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}var LI=PI(()=>new SI);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var dJ=BigInt(0),EI=BigInt(1),iZ=BigInt(2);function oJ($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function aJ($){if(!oJ($))throw Error("Uint8Array expected")}function d$($,J){if(typeof J!=="boolean")throw Error($+" boolean expected, got "+J)}var pZ=Array.from({length:256},($,J)=>J.toString(16).padStart(2,"0"));function o$($){aJ($);let J="";for(let Q=0;Q<$.length;Q++)J+=pZ[$[Q]];return J}function BI($){if(typeof $!=="string")throw Error("hex string expected, got "+typeof $);return $===""?dJ:BigInt("0x"+$)}var E0={_0:48,_9:57,A:65,F:70,a:97,f:102};function _I($){if($>=E0._0&&$<=E0._9)return $-E0._0;if($>=E0.A&&$<=E0.F)return $-(E0.A-10);if($>=E0.a&&$<=E0.f)return $-(E0.a-10);return}function fI($){if(typeof $!=="string")throw Error("hex string expected, got "+typeof $);let J=$.length,Q=J/2;if(J%2)throw Error("hex string expected, got unpadded hex of length "+J);let I=new Uint8Array(Q);for(let V=0,Z=0;V<Q;V++,Z+=2){let X=_I($.charCodeAt(Z)),Y=_I($.charCodeAt(Z+1));if(X===void 0||Y===void 0){let K=$[Z]+$[Z+1];throw Error('hex string expected, got non-hex character "'+K+'" at index '+Z)}I[V]=X*16+Y}return I}function xI($){return BI(o$($))}function V$($){return aJ($),BI(o$(Uint8Array.from($).reverse()))}function sJ($,J){return fI($.toString(16).padStart(J*2,"0"))}function C$($,J){return sJ($,J).reverse()}function T0($,J,Q){let I;if(typeof J==="string")try{I=fI(J)}catch(Z){throw Error($+" must be hex string or Uint8Array, cause: "+Z)}else if(oJ(J))I=Uint8Array.from(J);else throw Error($+" must be hex string or Uint8Array");let V=I.length;if(typeof Q==="number"&&V!==Q)throw Error($+" of length "+Q+" expected, got "+V);return I}function tJ(...$){let J=0;for(let I=0;I<$.length;I++){let V=$[I];aJ(V),J+=V.length}let Q=new Uint8Array(J);for(let I=0,V=0;I<$.length;I++){let Z=$[I];Q.set(Z,V),V+=Z.length}return Q}var nJ=($)=>typeof $==="bigint"&&dJ<=$;function cZ($,J,Q){return nJ($)&&nJ(J)&&nJ(Q)&&J<=$&&$<Q}function Z$($,J,Q,I){if(!cZ(J,Q,I))throw Error("expected valid "+$+": "+Q+" <= n < "+I+", got "+J)}function gI($){let J;for(J=0;$>dJ;$>>=EI,J+=1);return J}var mI=($)=>(iZ<<BigInt($-1))-EI;var lZ={bigint:($)=>typeof $==="bigint",function:($)=>typeof $==="function",boolean:($)=>typeof $==="boolean",string:($)=>typeof $==="string",stringOrUint8Array:($)=>typeof $==="string"||oJ($),isSafeInteger:($)=>Number.isSafeInteger($),array:($)=>Array.isArray($),field:($,J)=>J.Fp.isValid($),hash:($)=>typeof $==="function"&&Number.isSafeInteger($.outputLen)};function X$($,J,Q={}){let I=(V,Z,X)=>{let Y=lZ[Z];if(typeof Y!=="function")throw Error("invalid validator function");let K=$[V];if(X&&K===void 0)return;if(!Y(K,$))throw Error("param "+String(V)+" is invalid. Expected "+Z+", got "+K)};for(let[V,Z]of Object.entries(J))I(V,Z,!1);for(let[V,Z]of Object.entries(Q))I(V,Z,!0);return $}function eJ($){let J=new WeakMap;return(Q,...I)=>{let V=J.get(Q);if(V!==void 0)return V;let Z=$(Q,...I);return J.set(Q,Z),Z}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var $0=BigInt(0),s=BigInt(1),d0=BigInt(2),hZ=BigInt(3),$Q=BigInt(4),vI=BigInt(5),yI=BigInt(8),nZ=BigInt(9),dZ=BigInt(16);function t($,J){let Q=$%J;return Q>=$0?Q:J+Q}function oZ($,J,Q){if(J<$0)throw Error("invalid exponent, negatives unsupported");if(Q<=$0)throw Error("invalid modulus");if(Q===s)return $0;let I=s;while(J>$0){if(J&s)I=I*$%Q;$=$*$%Q,J>>=s}return I}function D0($,J,Q){let I=$;while(J-- >$0)I*=I,I%=Q;return I}function bI($,J){if($===$0)throw Error("invert: expected non-zero number");if(J<=$0)throw Error("invert: expected positive modulus, got "+J);let Q=t($,J),I=J,V=$0,Z=s,X=s,Y=$0;while(Q!==$0){let W=I/Q,G=I%Q,N=V-X*W,U=Z-Y*W;I=Q,Q=G,V=X,Z=Y,X=N,Y=U}if(I!==s)throw Error("invert: does not exist");return t(V,J)}function aZ($){let J=($-s)/d0,Q,I,V;for(Q=$-s,I=0;Q%d0===$0;Q/=d0,I++);for(V=d0;V<$&&oZ(V,J,$)!==$-s;V++)if(V>1000)throw Error("Cannot find square root: likely non-prime P");if(I===1){let X=($+s)/$Q;return function(K,W){let G=K.pow(W,X);if(!K.eql(K.sqr(G),W))throw Error("Cannot find square root");return G}}let Z=(Q+s)/d0;return function(Y,K){if(Y.pow(K,J)===Y.neg(Y.ONE))throw Error("Cannot find square root");let W=I,G=Y.pow(Y.mul(Y.ONE,V),Q),N=Y.pow(K,Z),U=Y.pow(K,Q);while(!Y.eql(U,Y.ONE)){if(Y.eql(U,Y.ZERO))return Y.ZERO;let M=1;for(let z=Y.sqr(U);M<W;M++){if(Y.eql(z,Y.ONE))break;z=Y.sqr(z)}let O=Y.pow(G,s<<BigInt(W-M-1));G=Y.sqr(O),N=Y.mul(N,O),U=Y.mul(U,G),W=M}return N}}function sZ($){if($%$Q===hZ){let J=($+s)/$Q;return function(I,V){let Z=I.pow(V,J);if(!I.eql(I.sqr(Z),V))throw Error("Cannot find square root");return Z}}if($%yI===vI){let J=($-vI)/yI;return function(I,V){let Z=I.mul(V,d0),X=I.pow(Z,J),Y=I.mul(V,X),K=I.mul(I.mul(Y,d0),X),W=I.mul(Y,I.sub(K,I.ONE));if(!I.eql(I.sqr(W),V))throw Error("Cannot find square root");return W}}if($%dZ===nZ);return aZ($)}var uI=($,J)=>(t($,J)&s)===s,tZ=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function iI($){let J={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},Q=tZ.reduce((I,V)=>{return I[V]="function",I},J);return X$($,Q)}function eZ($,J,Q){if(Q<$0)throw Error("invalid exponent, negatives unsupported");if(Q===$0)return $.ONE;if(Q===s)return J;let I=$.ONE,V=J;while(Q>$0){if(Q&s)I=$.mul(I,V);V=$.sqr(V),Q>>=s}return I}function $8($,J){let Q=Array(J.length),I=J.reduce((Z,X,Y)=>{if($.is0(X))return Z;return Q[Y]=Z,$.mul(Z,X)},$.ONE),V=$.inv(I);return J.reduceRight((Z,X,Y)=>{if($.is0(X))return Z;return Q[Y]=$.mul(Z,Q[Y]),$.mul(Z,X)},V),Q}function JQ($,J){let Q=J!==void 0?J:$.toString(2).length,I=Math.ceil(Q/8);return{nBitLength:Q,nByteLength:I}}function a$($,J,Q=!1,I={}){if($<=$0)throw Error("invalid field: expected ORDER > 0, got "+$);let{nBitLength:V,nByteLength:Z}=JQ($,J);if(Z>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let X,Y=Object.freeze({ORDER:$,isLE:Q,BITS:V,BYTES:Z,MASK:mI(V),ZERO:$0,ONE:s,create:(K)=>t(K,$),isValid:(K)=>{if(typeof K!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof K);return $0<=K&&K<$},is0:(K)=>K===$0,isOdd:(K)=>(K&s)===s,neg:(K)=>t(-K,$),eql:(K,W)=>K===W,sqr:(K)=>t(K*K,$),add:(K,W)=>t(K+W,$),sub:(K,W)=>t(K-W,$),mul:(K,W)=>t(K*W,$),pow:(K,W)=>eZ(Y,K,W),div:(K,W)=>t(K*bI(W,$),$),sqrN:(K)=>K*K,addN:(K,W)=>K+W,subN:(K,W)=>K-W,mulN:(K,W)=>K*W,inv:(K)=>bI(K,$),sqrt:I.sqrt||((K)=>{if(!X)X=sZ($);return X(Y,K)}),invertBatch:(K)=>$8(Y,K),cmov:(K,W,G)=>G?W:K,toBytes:(K)=>Q?C$(K,Z):sJ(K,Z),fromBytes:(K)=>{if(K.length!==Z)throw Error("Field.fromBytes: expected "+Z+" bytes, got "+K.length);return Q?V$(K):xI(K)}});return Object.freeze(Y)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var pI=BigInt(0),s$=BigInt(1);function QQ($,J){let Q=J.negate();return $?Q:J}function cI($,J){if(!Number.isSafeInteger($)||$<=0||$>J)throw Error("invalid window size, expected [1.."+J+"], got W="+$)}function IQ($,J){cI($,J);let Q=Math.ceil(J/$)+1,I=2**($-1);return{windows:Q,windowSize:I}}function J8($,J){if(!Array.isArray($))throw Error("array expected");$.forEach((Q,I)=>{if(!(Q instanceof J))throw Error("invalid point at index "+I)})}function Q8($,J){if(!Array.isArray($))throw Error("array of scalars expected");$.forEach((Q,I)=>{if(!J.isValid(Q))throw Error("invalid scalar at index "+I)})}var VQ=new WeakMap,lI=new WeakMap;function ZQ($){return lI.get($)||1}function rI($,J){return{constTimeNegate:QQ,hasPrecomputes(Q){return ZQ(Q)!==1},unsafeLadder(Q,I,V=$.ZERO){let Z=Q;while(I>pI){if(I&s$)V=V.add(Z);Z=Z.double(),I>>=s$}return V},precomputeWindow(Q,I){let{windows:V,windowSize:Z}=IQ(I,J),X=[],Y=Q,K=Y;for(let W=0;W<V;W++){K=Y,X.push(K);for(let G=1;G<Z;G++)K=K.add(Y),X.push(K);Y=K.double()}return X},wNAF(Q,I,V){let{windows:Z,windowSize:X}=IQ(Q,J),Y=$.ZERO,K=$.BASE,W=BigInt(2**Q-1),G=2**Q,N=BigInt(Q);for(let U=0;U<Z;U++){let M=U*X,O=Number(V&W);if(V>>=N,O>X)O-=G,V+=s$;let z=M,R=M+Math.abs(O)-1,D=U%2!==0,w=O<0;if(O===0)K=K.add(QQ(D,I[z]));else Y=Y.add(QQ(w,I[R]))}return{p:Y,f:K}},wNAFUnsafe(Q,I,V,Z=$.ZERO){let{windows:X,windowSize:Y}=IQ(Q,J),K=BigInt(2**Q-1),W=2**Q,G=BigInt(Q);for(let N=0;N<X;N++){let U=N*Y;if(V===pI)break;let M=Number(V&K);if(V>>=G,M>Y)M-=W,V+=s$;if(M===0)continue;let O=I[U+Math.abs(M)-1];if(M<0)O=O.negate();Z=Z.add(O)}return Z},getPrecomputes(Q,I,V){let Z=VQ.get(I);if(!Z){if(Z=this.precomputeWindow(I,Q),Q!==1)VQ.set(I,V(Z))}return Z},wNAFCached(Q,I,V){let Z=ZQ(Q);return this.wNAF(Z,this.getPrecomputes(Z,Q,V),I)},wNAFCachedUnsafe(Q,I,V,Z){let X=ZQ(Q);if(X===1)return this.unsafeLadder(Q,I,Z);return this.wNAFUnsafe(X,this.getPrecomputes(X,Q,V),I,Z)},setWindowSize(Q,I){cI(I,J),lI.set(Q,I),VQ.delete(Q)}}}function hI($,J,Q,I){if(J8(Q,$),Q8(I,J),Q.length!==I.length)throw Error("arrays of points and scalars must have equal length");let V=$.ZERO,Z=gI(BigInt(Q.length)),X=Z>12?Z-3:Z>4?Z-2:Z?2:1,Y=(1<<X)-1,K=Array(Y+1).fill(V),W=Math.floor((J.BITS-1)/X)*X,G=V;for(let N=W;N>=0;N-=X){K.fill(V);for(let M=0;M<I.length;M++){let O=I[M],z=Number(O>>BigInt(N)&BigInt(Y));K[z]=K[z].add(Q[M])}let U=V;for(let M=K.length-1,O=V;M>0;M--)O=O.add(K[M]),U=U.add(O);if(G=G.add(U),N!==0)for(let M=0;M<X;M++)G=G.double()}return G}function nI($){return iI($.Fp),X$($,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...JQ($.n,$.nBitLength),...$,...{p:$.Fp.ORDER}})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var F0=BigInt(0),N0=BigInt(1),t$=BigInt(2),I8=BigInt(8),V8={zip215:!0};function Z8($){let J=nI($);return X$($,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...J})}function dI($){let J=Z8($),{Fp:Q,n:I,prehash:V,hash:Z,randomBytes:X,nByteLength:Y,h:K}=J,W=t$<<BigInt(Y*8)-N0,G=Q.create,N=a$(J.n,J.nBitLength),U=J.uvRatio||((C,P)=>{try{return{isValid:!0,value:Q.sqrt(C*Q.inv(P))}}catch(T){return{isValid:!1,value:F0}}}),M=J.adjustScalarBytes||((C)=>C),O=J.domain||((C,P,T)=>{if(d$("phflag",T),P.length||T)throw Error("Contexts/pre-hash are not supported");return C});function z(C,P){Z$("coordinate "+C,P,F0,W)}function R(C){if(!(C instanceof F))throw Error("ExtendedPoint expected")}let D=eJ((C,P)=>{let{ex:T,ey:_,ez:v}=C,x=C.is0();if(P==null)P=x?I8:Q.inv(v);let E=G(T*P),i=G(_*P),c=G(v*P);if(x)return{x:F0,y:N0};if(c!==N0)throw Error("invZ was invalid");return{x:E,y:i}}),w=eJ((C)=>{let{a:P,d:T}=J;if(C.is0())throw Error("bad point: ZERO");let{ex:_,ey:v,ez:x,et:E}=C,i=G(_*_),c=G(v*v),h=G(x*x),a=G(h*h),Q0=G(i*P),V0=G(h*G(Q0+c)),M0=G(a+G(T*G(i*c)));if(V0!==M0)throw Error("bad point: equation left != right (1)");let m0=G(_*v),S0=G(x*E);if(m0!==S0)throw Error("bad point: equation left != right (2)");return!0});class F{constructor(C,P,T,_){this.ex=C,this.ey=P,this.ez=T,this.et=_,z("x",C),z("y",P),z("z",T),z("t",_),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(C){if(C instanceof F)throw Error("extended point not allowed");let{x:P,y:T}=C||{};return z("x",P),z("y",T),new F(P,T,N0,G(P*T))}static normalizeZ(C){let P=Q.invertBatch(C.map((T)=>T.ez));return C.map((T,_)=>T.toAffine(P[_])).map(F.fromAffine)}static msm(C,P){return hI(F,N,C,P)}_setWindowSize(C){y.setWindowSize(this,C)}assertValidity(){w(this)}equals(C){R(C);let{ex:P,ey:T,ez:_}=this,{ex:v,ey:x,ez:E}=C,i=G(P*E),c=G(v*_),h=G(T*E),a=G(x*_);return i===c&&h===a}is0(){return this.equals(F.ZERO)}negate(){return new F(G(-this.ex),this.ey,this.ez,G(-this.et))}double(){let{a:C}=J,{ex:P,ey:T,ez:_}=this,v=G(P*P),x=G(T*T),E=G(t$*G(_*_)),i=G(C*v),c=P+T,h=G(G(c*c)-v-x),a=i+x,Q0=a-E,V0=i-x,M0=G(h*Q0),m0=G(a*V0),S0=G(h*V0),A$=G(Q0*a);return new F(M0,m0,A$,S0)}add(C){R(C);let{a:P,d:T}=J,{ex:_,ey:v,ez:x,et:E}=this,{ex:i,ey:c,ez:h,et:a}=C;if(P===BigInt(-1)){let gQ=G((v-_)*(c+i)),mQ=G((v+_)*(c-i)),WJ=G(mQ-gQ);if(WJ===F0)return this.double();let vQ=G(x*t$*a),yQ=G(E*t$*h),bQ=yQ+vQ,uQ=mQ+gQ,iQ=yQ-vQ,TV=G(bQ*WJ),DV=G(uQ*iQ),FV=G(bQ*iQ),AV=G(WJ*uQ);return new F(TV,DV,AV,FV)}let Q0=G(_*i),V0=G(v*c),M0=G(E*T*a),m0=G(x*h),S0=G((_+v)*(i+c)-Q0-V0),A$=m0-M0,fQ=m0+M0,xQ=G(V0-P*Q0),HV=G(S0*A$),RV=G(fQ*xQ),CV=G(S0*xQ),wV=G(A$*fQ);return new F(HV,RV,wV,CV)}subtract(C){return this.add(C.negate())}wNAF(C){return y.wNAFCached(this,C,F.normalizeZ)}multiply(C){let P=C;Z$("scalar",P,N0,I);let{p:T,f:_}=this.wNAF(P);return F.normalizeZ([T,_])[0]}multiplyUnsafe(C,P=F.ZERO){let T=C;if(Z$("scalar",T,F0,I),T===F0)return S;if(this.is0()||T===N0)return this;return y.wNAFCachedUnsafe(this,T,F.normalizeZ,P)}isSmallOrder(){return this.multiplyUnsafe(K).is0()}isTorsionFree(){return y.unsafeLadder(this,I).is0()}toAffine(C){return D(this,C)}clearCofactor(){let{h:C}=J;if(C===N0)return this;return this.multiplyUnsafe(C)}static fromHex(C,P=!1){let{d:T,a:_}=J,v=Q.BYTES;C=T0("pointHex",C,v),d$("zip215",P);let x=C.slice(),E=C[v-1];x[v-1]=E&-129;let i=V$(x),c=P?W:Q.ORDER;Z$("pointHex.y",i,F0,c);let h=G(i*i),a=G(h-N0),Q0=G(T*h-_),{isValid:V0,value:M0}=U(a,Q0);if(!V0)throw Error("Point.fromHex: invalid y coordinate");let m0=(M0&N0)===N0,S0=(E&128)!==0;if(!P&&M0===F0&&S0)throw Error("Point.fromHex: x=0 and x_0=1");if(S0!==m0)M0=G(-M0);return F.fromAffine({x:M0,y:i})}static fromPrivateKey(C){return m(C).point}toRawBytes(){let{x:C,y:P}=this.toAffine(),T=C$(P,Q.BYTES);return T[T.length-1]|=C&N0?128:0,T}toHex(){return o$(this.toRawBytes())}}F.BASE=new F(J.Gx,J.Gy,N0,G(J.Gx*J.Gy)),F.ZERO=new F(F0,N0,N0,F0);let{BASE:A,ZERO:S}=F,y=rI(F,Y*8);function f(C){return t(C,I)}function B(C){return f(V$(C))}function m(C){let P=Q.BYTES;C=T0("private key",C,P);let T=T0("hashed private key",Z(C),2*P),_=M(T.slice(0,P)),v=T.slice(P,2*P),x=B(_),E=A.multiply(x),i=E.toRawBytes();return{head:_,prefix:v,scalar:x,point:E,pointBytes:i}}function u(C){return m(C).pointBytes}function H(C=new Uint8Array,...P){let T=tJ(...P);return B(Z(O(T,T0("context",C),!!V)))}function g(C,P,T={}){if(C=T0("message",C),V)C=V(C);let{prefix:_,scalar:v,pointBytes:x}=m(P),E=H(T.context,_,C),i=A.multiply(E).toRawBytes(),c=H(T.context,i,x,C),h=f(E+c*v);Z$("signature.s",h,F0,I);let a=tJ(i,C$(h,Q.BYTES));return T0("result",a,Q.BYTES*2)}let p=V8;function r(C,P,T,_=p){let{context:v,zip215:x}=_,E=Q.BYTES;if(C=T0("signature",C,2*E),P=T0("message",P),T=T0("publicKey",T,E),x!==void 0)d$("zip215",x);if(V)P=V(P);let i=V$(C.slice(E,2*E)),c,h,a;try{c=F.fromHex(T,x),h=F.fromHex(C.slice(0,E),x),a=A.multiplyUnsafe(i)}catch(M0){return!1}if(!x&&c.isSmallOrder())return!1;let Q0=H(v,h.toRawBytes(),c.toRawBytes(),P);return h.add(c.multiplyUnsafe(Q0)).subtract(a).clearCofactor().equals(F.ZERO)}return A._setWindowSize(8),{CURVE:J,getPublicKey:u,sign:g,verify:r,ExtendedPoint:F,utils:{getExtendedPublicKey:m,randomPrivateKey:()=>X(Q.BYTES),precompute(C=8,P=F.BASE){return P._setWindowSize(C),P.multiply(BigInt(3)),P}}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var XQ=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),oI=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),ZN=BigInt(0),X8=BigInt(1),aI=BigInt(2),XN=BigInt(3),Y8=BigInt(5),K8=BigInt(8);function G8($){let J=BigInt(10),Q=BigInt(20),I=BigInt(40),V=BigInt(80),Z=XQ,Y=$*$%Z*$%Z,K=D0(Y,aI,Z)*Y%Z,W=D0(K,X8,Z)*$%Z,G=D0(W,Y8,Z)*W%Z,N=D0(G,J,Z)*G%Z,U=D0(N,Q,Z)*N%Z,M=D0(U,I,Z)*U%Z,O=D0(M,V,Z)*M%Z,z=D0(O,V,Z)*M%Z,R=D0(z,J,Z)*G%Z;return{pow_p_5_8:D0(R,aI,Z)*$%Z,b2:Y}}function W8($){return $[0]&=248,$[31]&=127,$[31]|=64,$}function N8($,J){let Q=XQ,I=t(J*J*J,Q),V=t(I*I*J,Q),Z=G8($*V).pow_p_5_8,X=t($*I*Z,Q),Y=t(J*X*X,Q),K=X,W=t(X*oI,Q),G=Y===$,N=Y===t(-$,Q),U=Y===t(-$*oI,Q);if(G)X=K;if(N||U)X=W;if(uI(X,Q))X=t(-X,Q);return{isValid:G||N,value:X}}var M8=(()=>a$(XQ,void 0,!0))(),q8=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:M8,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:K8,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:LI,randomBytes:jI,adjustScalarBytes:W8,uvRatio:N8}))(),e$=(()=>dI(q8))();/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function U8($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function w$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function o0($,...J){if(!U8($))throw Error("Uint8Array expected");if(J.length>0&&!J.includes($.length))throw Error("Uint8Array expected of length "+J+", got length="+$.length)}function T$($,J=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(J&&$.finished)throw Error("Hash#digest() has already been called")}function $J($,J){o0($);let Q=J.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function sI($){return new Uint8Array($.buffer,$.byteOffset,$.byteLength)}function Y$($){return new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4))}function K$(...$){for(let J=0;J<$.length;J++)$[J].fill(0)}function D$($,J){return $<<32-J|$>>>J}var tI=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function eI($){return $<<24&4278190080|$<<8&16711680|$>>>8&65280|$>>>24&255}var $V=tI?($)=>$:($)=>eI($);function z8($){for(let J=0;J<$.length;J++)$[J]=eI($[J]);return $}var K0=tI?($)=>$:z8;function O8($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function G$($){if(typeof $==="string")$=O8($);return o0($),$}class YQ{}function JV($){let J=(I,V)=>$(V).update(G$(I)).digest(),Q=$({});return J.outputLen=Q.outputLen,J.blockLen=Q.blockLen,J.create=(I)=>$(I),J}var QV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var JJ=BigInt(4294967295),IV=BigInt(32);function KQ($,J=!1){if(J)return{h:Number($&JJ),l:Number($>>IV&JJ)};return{h:Number($>>IV&JJ)|0,l:Number($&JJ)|0}}function B0($,J,Q,I,V){return $=$+J+V|0,I=D$(I^$,16),Q=Q+I|0,J=D$(J^Q,12),{a:$,b:J,c:Q,d:I}}function f0($,J,Q,I,V){return $=$+J+V|0,I=D$(I^$,8),Q=Q+I|0,J=D$(J^Q,7),{a:$,b:J,c:Q,d:I}}class GQ extends YQ{constructor($,J){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,w$($),w$(J),this.blockLen=$,this.outputLen=J,this.buffer=new Uint8Array($),this.buffer32=Y$(this.buffer)}update($){T$(this),$=G$($),o0($);let{blockLen:J,buffer:Q,buffer32:I}=this,V=$.length,Z=$.byteOffset,X=$.buffer;for(let Y=0;Y<V;){if(this.pos===J)K0(I),this.compress(I,0,!1),K0(I),this.pos=0;let K=Math.min(J-this.pos,V-Y),W=Z+Y;if(K===J&&!(W%4)&&Y+K<V){let G=new Uint32Array(X,W,Math.floor((V-Y)/4));K0(G);for(let N=0;Y+J<V;N+=I.length,Y+=J)this.length+=J,this.compress(G,N,!1);K0(G);continue}Q.set($.subarray(Y,Y+K),this.pos),this.pos+=K,this.length+=K,Y+=K}return this}digestInto($){T$(this),$J($,this);let{pos:J,buffer32:Q}=this;this.finished=!0,K$(this.buffer.subarray(J)),K0(Q),this.compress(Q,0,!0),K0(Q);let I=Y$($);this.get().forEach((V,Z)=>I[Z]=$V(V))}digest(){let{buffer:$,outputLen:J}=this;this.digestInto($);let Q=$.slice(0,J);return this.destroy(),Q}_cloneInto($){let{buffer:J,length:Q,finished:I,destroyed:V,outputLen:Z,pos:X}=this;return $||($=new this.constructor({dkLen:Z})),$.set(...this.get()),$.buffer.set(J),$.destroyed=V,$.finished=I,$.length=Q,$.pos=X,$.outputLen=Z,$}clone(){return this._cloneInto()}}function WQ($,J,Q,I,V,Z,X,Y,K,W,G,N,U,M,O,z,R,D,w,F){let A=0;for(let S=0;S<I;S++)({a:V,b:K,c:U,d:R}=B0(V,K,U,R,Q[J+$[A++]])),{a:V,b:K,c:U,d:R}=f0(V,K,U,R,Q[J+$[A++]]),{a:Z,b:W,c:M,d:D}=B0(Z,W,M,D,Q[J+$[A++]]),{a:Z,b:W,c:M,d:D}=f0(Z,W,M,D,Q[J+$[A++]]),{a:X,b:G,c:O,d:w}=B0(X,G,O,w,Q[J+$[A++]]),{a:X,b:G,c:O,d:w}=f0(X,G,O,w,Q[J+$[A++]]),{a:Y,b:N,c:z,d:F}=B0(Y,N,z,F,Q[J+$[A++]]),{a:Y,b:N,c:z,d:F}=f0(Y,N,z,F,Q[J+$[A++]]),{a:V,b:W,c:O,d:F}=B0(V,W,O,F,Q[J+$[A++]]),{a:V,b:W,c:O,d:F}=f0(V,W,O,F,Q[J+$[A++]]),{a:Z,b:G,c:z,d:R}=B0(Z,G,z,R,Q[J+$[A++]]),{a:Z,b:G,c:z,d:R}=f0(Z,G,z,R,Q[J+$[A++]]),{a:X,b:N,c:U,d:D}=B0(X,N,U,D,Q[J+$[A++]]),{a:X,b:N,c:U,d:D}=f0(X,N,U,D,Q[J+$[A++]]),{a:Y,b:K,c:M,d:w}=B0(Y,K,M,w,Q[J+$[A++]]),{a:Y,b:K,c:M,d:w}=f0(Y,K,M,w,Q[J+$[A++]]);return{v0:V,v1:Z,v2:X,v3:Y,v4:K,v5:W,v6:G,v7:N,v8:U,v9:M,v10:O,v11:z,v12:R,v13:D,v14:w,v15:F}}var j0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},x0=QV.slice(),VV=(()=>{let $=Array.from({length:16},(I,V)=>V),J=(I)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((V)=>I[V]),Q=[];for(let I=0,V=$;I<7;I++,V=J(V))Q.push(...V);return Uint8Array.from(Q)})();class NQ extends GQ{constructor($={},J=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:I}=$,V=I!==void 0;if(Q!==void 0){if(V)throw Error('Only "key" or "context" can be specified at same time');let Z=G$(Q).slice();o0(Z,32),this.IV=Y$(Z),K0(this.IV),this.flags=J|j0.KEYED_HASH}else if(V){let Z=G$(I),X=new NQ({dkLen:32},j0.DERIVE_KEY_CONTEXT).update(Z).digest();this.IV=Y$(X),K0(this.IV),this.flags=J|j0.DERIVE_KEY_MATERIAL}else this.IV=x0.slice(),this.flags=J;this.state=this.IV.slice(),this.bufferOut=sI(this.bufferOut32)}get(){return[]}set(){}b2Compress($,J,Q,I=0){let{state:V,pos:Z}=this,{h:X,l:Y}=KQ(BigInt($),!0),{v0:K,v1:W,v2:G,v3:N,v4:U,v5:M,v6:O,v7:z,v8:R,v9:D,v10:w,v11:F,v12:A,v13:S,v14:y,v15:f}=WQ(VV,I,Q,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],x0[0],x0[1],x0[2],x0[3],X,Y,Z,J);V[0]=K^R,V[1]=W^D,V[2]=G^w,V[3]=N^F,V[4]=U^A,V[5]=M^S,V[6]=O^y,V[7]=z^f}compress($,J=0,Q=!1){let I=this.flags;if(!this.chunkPos)I|=j0.CHUNK_START;if(this.chunkPos===15||Q)I|=j0.CHUNK_END;if(!Q)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,I,$,J),this.chunkPos+=1,this.chunkPos===16||Q){let V=this.state;this.state=this.IV.slice();for(let Z,X=this.chunksDone+1;Q||!(X&1);X>>=1){if(!(Z=this.stack.pop()))break;this.buffer32.set(Z,0),this.buffer32.set(V,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|j0.PARENT,this.buffer32,0),V=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(V)}this.pos=0}_cloneInto($){$=super._cloneInto($);let{IV:J,flags:Q,state:I,chunkPos:V,posOut:Z,chunkOut:X,stack:Y,chunksDone:K}=this;return $.state.set(I.slice()),$.stack=Y.map((W)=>Uint32Array.from(W)),$.IV.set(J),$.flags=Q,$.chunkPos=V,$.chunksDone=K,$.posOut=Z,$.chunkOut=X,$.enableXOF=this.enableXOF,$.bufferOut32.set(this.bufferOut32),$}destroy(){this.destroyed=!0,K$(this.state,this.buffer32,this.IV,this.bufferOut32),K$(...this.stack)}b2CompressOut(){let{state:$,pos:J,flags:Q,buffer32:I,bufferOut32:V}=this,{h:Z,l:X}=KQ(BigInt(this.chunkOut++));K0(I);let{v0:Y,v1:K,v2:W,v3:G,v4:N,v5:U,v6:M,v7:O,v8:z,v9:R,v10:D,v11:w,v12:F,v13:A,v14:S,v15:y}=WQ(VV,0,I,7,$[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],x0[0],x0[1],x0[2],x0[3],X,Z,J,Q);V[0]=Y^z,V[1]=K^R,V[2]=W^D,V[3]=G^w,V[4]=N^F,V[5]=U^A,V[6]=M^S,V[7]=O^y,V[8]=$[0]^z,V[9]=$[1]^R,V[10]=$[2]^D,V[11]=$[3]^w,V[12]=$[4]^F,V[13]=$[5]^A,V[14]=$[6]^S,V[15]=$[7]^y,K0(I),K0(V),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,K$(this.buffer.subarray(this.pos));let $=this.flags|j0.ROOT;if(this.stack.length)$|=j0.PARENT,K0(this.buffer32),this.compress(this.buffer32,0,!0),K0(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else $|=(!this.chunkPos?j0.CHUNK_START:0)|j0.CHUNK_END;this.flags=$,this.b2CompressOut()}writeInto($){T$(this,!1),o0($),this.finish();let{blockLen:J,bufferOut:Q}=this;for(let I=0,V=$.length;I<V;){if(this.posOut>=J)this.b2CompressOut();let Z=Math.min(J-this.posOut,V-I);$.set(Q.subarray(this.posOut,this.posOut+Z),I),this.posOut+=Z,I+=Z}return $}xofInto($){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto($)}xof($){return w$($),this.xofInto(new Uint8Array($))}digestInto($){if($J($,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 ZV=JV(($)=>new NQ($));class MQ{async genRandomBytes($){return l$($)}async gen256BitSecureRandomSeed(){return l$(32)}async encryptXSalsa20Poly1305Combined($,J){let Q=l$(24),V=uJ(J,Q).encrypt($);return new Uint8Array([...Q,...V])}async decryptXSalsa20Poly1305Combined($,J){let Q=$.slice(0,24),I=$.slice(24);return uJ(J,Q).decrypt(I)}async deriveEd25519KeyPair($){let J=$,Q=e$.getPublicKey(J),I=new Uint8Array(64);return I.set(J,0),I.set(Q,32),{keyType:"ed25519",privateKey:I,publicKey:Q}}async signEd25519($,J){let Q=typeof $==="string"?new TextEncoder().encode($):$,I=J.slice(0,32);return e$.sign(Q,I)}async checkSigEd25519($,J,Q){let I=typeof J==="string"?new TextEncoder().encode(J):J;return e$.verify($,I,Q)}async blake3($){return ZV($)}}var H8=new MQ,z0=H8;var _N=Symbol("EntityID");function XV($){return"type"in $}var EN=Symbol("MasterSeed"),BN=Symbol("DerivationSeed"),fN=Symbol("PublicKey"),xN=Symbol("PrivateKey"),gN=Symbol("HostSpecificKeyPair"),mN=Symbol("Hash");function R8($){if(!$)return!1;if(typeof $!=="object")return!1;if("body"in $===!1)return!1;if("type"in $===!1)return!1;return!0}function C8($){if(!$.bod||$.bod.length===0){let I={off:$.off,ctr:$.ctr,eid:$.eid};return j(I)}let J=zJ($.bod);if(R8(J)===!1)return console.warn("msg body invalid",J),q(14);let Q={off:$.off,ctr:$.ctr,eid:$.eid,gid:J.gid,pid:J.pid,type:J.type,body:J.body};return j(Q)}class QJ{applier;emitter=new v0;clearer;onTypes;constructor($,J,Q){this.applier=$;this.clearer=J,this.onTypes=Q}apply=async($)=>{let J=[],Q=[];for(let X of $){let[Y,K]=C8(X);if(Q.push(K),K!==0)continue;J.push(Y)}let{stats:I,types:V}=await this.applier(J),Z=[];for(let X=0;X<$.length;X++){let Y=Q[X],K=I[X];if(Y!==0){Z.push(Y);continue}if(K!==0){Z.push(K);continue}Z.push(0)}for(let X of V)this.emitter.emit(X,null);if(V.size>0)this.onTypes?.(V);return Z};clear=async()=>{let $=await this.clearer();if($!==0)return $;return this.emitter.emitAll(null),$};notify=($)=>{for(let J of $)this.emitter.emit(J,null)};on=($,J)=>{this.emitter.addEventListener($,J)};off=($,J)=>{this.emitter.removeEventListener($,J)}}var qQ={apply:async function($){return $.map(()=>0)},clear:async function(){return 0},notify:function($){},on:function($,J){},off:function($,J){}};function UQ($){return new QJ((J)=>$.apply(J),()=>$.clear())}function IJ($,J){let Q=new n(J.eid),[I,V]=Q.readStruct(q0);if(V!==0)return q(V);let Z=new Date(I.ts.getTime()+J.off);if($!==void 0&&Z<=$.updatedAt)return q(15);if(XV(J))return j({eid:J.eid,gid:J.gid,pid:J.pid,type:J.type,createdAt:I.ts,updatedAt:Z,ctr:J.ctr,body:J.body});else return j(void 0)}var w8={getEnt:async()=>q(21),getEntities:async($)=>q(21),countEntities:async()=>q(21),apply:async($)=>({stats:$.map(()=>21),types:new Set}),clear:async()=>21};var J0="entities",VJ="entity_type_created_at",zQ="entity_type_updated_at",OQ="entity_type_group_id",HQ="entity_type_parent_id";function T8($){let J={bod:$.body,crd:$.createdAt,...$.ctr!==0?{ctr:$.ctr}:{},eid:d($.eid),gid:$.gid,pid:$.pid?d($.pid):void 0,typ:$.type,upd:$.updatedAt};if(J.gid===void 0)delete J.gid;if(J.pid===void 0)delete J.pid;if(J.ctr===void 0)delete J.ctr;return J}function W$($){return{body:$.bod,createdAt:$.crd,updatedAt:$.upd,ctr:$.ctr??0,type:$.typ,eid:U0($.eid),gid:$.gid,pid:$.pid?U0($.pid):void 0}}class RQ{db;async init(){this.db=await new Promise(($,J)=>{let Q=indexedDB.open("db",11);Q.onupgradeneeded=()=>{let{result:I,transaction:V}=Q;if(!V)throw Error("Transaction is null during upgrade");if(!I.objectStoreNames.contains(J0))I.createObjectStore(J0,{keyPath:"eid",autoIncrement:!1});let Z=V.objectStore(J0);if(!Z.indexNames.contains(VJ))Z.createIndex(VJ,["typ","crd"],{unique:!1});if(!Z.indexNames.contains(zQ))Z.createIndex(zQ,["typ","upd"],{unique:!1});if(!Z.indexNames.contains(OQ))Z.createIndex(OQ,["typ","gid"],{unique:!1});if(!Z.indexNames.contains(HQ))Z.createIndex(HQ,["typ","pid"],{unique:!1})},Q.onsuccess=()=>$(Q.result),Q.onerror=()=>J(Q.error)})}apply=async($)=>{let J=new Set;if(!this.db)return{stats:$.map(()=>16),types:J};let Q=this.db.transaction(J0,"readwrite"),I=Q.objectStore(J0);return new Promise((V)=>{let Z=Array($.length).fill(0);if($.length<1){V({stats:[],types:J});return}Q.oncomplete=()=>{V({stats:Z,types:J})},Q.onerror=()=>{for(let Y=0;Y<Z.length;Y++)if(Z[Y]===void 0)Z[Y]=18;V({stats:Z,types:J})};let X=new Map;for(let Y=0;Y<$.length;Y++){let K=$[Y],W=d(K.eid),G={op:K,index:Y},N=X.get(W);if(N)N.push(G);else X.set(W,[G])}for(let[Y,K]of X){if(K.length<1)continue;let W=I.get(Y);W.onsuccess=()=>{let G=W.result,N=G?W$(G):void 0;for(let{op:U,index:M}of K){let[O,z]=IJ(N,U);if(z!==0){Z[M]=z;continue}if(O)J.add(O.type);else if(N)J.add(N.type);N=O}if(N){let U=T8(N),M=I.put(U);M.onerror=(O)=>{O.preventDefault();for(let{index:z}of K)Z[z]=18}}else{let U=I.delete(Y);U.onerror=()=>{for(let{index:M}of K)Z[M]=18}}},W.onerror=()=>{for(let{index:G}of K)Z[G]=18}}})};async clear(){if(!this.db)return 16;let $=this.db.transaction(J0,"readwrite"),J=$.objectStore(J0);return new Promise((Q)=>{$.oncomplete=()=>Q(0),$.onerror=()=>Q(18),J.clear()})}async getEnt($){if(!this.db)return q(16);let J=d($),I=this.db.transaction(J0,"readonly").objectStore(J0);return new Promise((V)=>{let Z=I.get(J);Z.onsuccess=()=>{let X=Z.result;if(!X)V(j(void 0));else{let Y=W$(X);V(j(Y))}},Z.onerror=()=>V(q(18))})}async getAllOfTypeUpdatedBetween($,J,Q){if(!this.db)return q(16);let V=this.db.transaction(J0,"readonly").objectStore(J0).index(zQ);return new Promise((Z)=>{let X=V.getAll(IDBKeyRange.bound([$,J],[$,Q]));X.onsuccess=()=>{let Y=X.result;Z(j(Y.map(W$)))},X.onerror=()=>Z(q(18))})}async getGroupMembers($,J){if(!this.db)return q(16);let I=this.db.transaction(J0,"readonly").objectStore(J0).index(OQ);return new Promise((V)=>{let Z=I.getAll(IDBKeyRange.only([$,J]));Z.onsuccess=()=>{let X=Z.result;V(j(X.map(W$)))},Z.onerror=()=>V(q(18))})}async getAllOfType($){if(!this.db)return q(16);let Q=this.db.transaction(J0,"readonly").objectStore(J0).index(VJ);return new Promise((I)=>{let V=Q.getAll(IDBKeyRange.bound([$],[$,[]]));V.onsuccess=()=>{let Z=V.result;I(j(Z.map(W$)))},V.onerror=()=>I(q(18))})}async getAllEntities($){if(!this.db)return q(16);if("pid"in $){let J=d($.pid),I=this.db.transaction(J0,"readonly").objectStore(J0).index(HQ);return new Promise((V)=>{let Z=I.getAll(IDBKeyRange.only([$.type,J]));Z.onsuccess=()=>{let Y=Z.result.map(W$);V(j(Y))},Z.onerror=()=>V(q(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[J,Q]=await this.getAllEntities($);if(Q!==0)return q(Q);return j(J)}async countEntities({type:$}){if(!this.db)return q(16);let Q=this.db.transaction(J0,"readonly").objectStore(J0).index(VJ);return new Promise((I)=>{let V=IDBKeyRange.bound([$],[$,[]]),Z=Q.count(V);Z.onsuccess=()=>I(j(Z.result)),Z.onerror=()=>I(q(18))})}}async function CQ(){let $=new RQ;return await $.init(),$}class YV{ents=new Map;constructor($=[]){for(let J of $){let Q=d(J.eid);this.ents.set(Q,J)}}async apply($){let J=new Set,Q=[];for(let I of $){let V=d(I.eid),Z=this.ents.get(V),[X,Y]=IJ(Z,I);if(Y!==0){Q.push(Y);continue}if(X)J.add(X.type);else if(Z)J.add(Z.type);if(X)this.ents.set(V,X);else this.ents.delete(V);Q.push(0)}return{stats:Q,types:J}}async clear(){return this.ents.clear(),0}async getEnt($){let J=d($),Q=this.ents.get(J);return j(Q)}async getAllEntities({type:$,gid:J,pid:Q,updatedBetween:I}){let V=[];if(Q!==void 0){for(let Z of this.ents.values())if(Z.type===$&&Z.pid&&w0(Z.pid,Q))V.push(Z)}else if(J!==void 0){for(let Z of this.ents.values())if(Z.type===$&&(typeof Z.gid==="string"&&Z.gid===J))V.push(Z)}else if(I!==void 0){for(let Z of this.ents.values())if(Z.type===$&&Z.updatedAt>=I.start&&Z.updatedAt<=I.end)V.push(Z)}else for(let Z of this.ents.values())if(Z.type===$)V.push(Z);return j(V)}async getEntities($){let[J,Q]=await this.getAllEntities($);if(Q!==0)return q(Q);return j(J)}async countEntities({type:$}){let J=0;for(let Q of this.ents.values())if(Q.type===$)J+=1;return j(J)}}import{useEffect as GJ,useState as kQ}from"react";class wQ{db;constructor($){this.db=$}async enq($){let J=[...$];if(J.length===0)return;let Q=this.db.transaction(O0,"readwrite"),I=Q.objectStore(O0);return new Promise((V,Z)=>{Q.oncomplete=()=>V(),Q.onerror=()=>Z(Q.error);for(let X of J){let Y=`${X.host}:${X.seq}`;I.put(X,Y)}})}async deq($,J){let Q=[...J];if(Q.length===0)return;let I=this.db.transaction(O0,"readwrite"),V=I.objectStore(O0);return new Promise((Z,X)=>{I.oncomplete=()=>Z(),I.onerror=()=>X(I.error);for(let Y of Q){let K=`${$}:${Y}`;V.delete(K)}})}async list(){let J=this.db.transaction(O0,"readonly").objectStore(O0);return new Promise((Q,I)=>{let V=J.getAll();V.onsuccess=()=>Q(V.result),V.onerror=()=>I(V.error)})}async count(){let J=this.db.transaction(O0,"readonly").objectStore(O0);return new Promise((Q,I)=>{let V=J.count();V.onsuccess=()=>Q(V.result),V.onerror=()=>I(V.error)})}async wipe(){let $=this.db.transaction(O0,"readwrite"),J=$.objectStore(O0);return new Promise((Q,I)=>{$.oncomplete=()=>Q(),$.onerror=()=>I($.error),J.clear()})}}function KV($){return{label:$.label,handle:new URL($.handle),idx:$.idx,lastSeq:$.lastSeq||0,clockOffset:$.clockOffset,subscription:$.subscription}}class TQ{db;constructor($){this.db=$}async add($){return this.put($)}async put($){let J={...$,handle:$.handle.toString(),lastSeq:$.lastSeq??0},Q=this.db.transaction(G0,"readwrite"),I=Q.objectStore(G0);return new Promise((V,Z)=>{Q.oncomplete=()=>V(),Q.onerror=()=>Z(Q.error),I.put(J)})}async touch($,J){let Q=this.db.transaction(G0,"readwrite"),I=Q.objectStore(G0);return new Promise((V,Z)=>{Q.oncomplete=()=>V(),Q.onerror=()=>Z(Q.error);let X=I.get($);X.onsuccess=()=>{let Y=X.result;if(!Y)return;let K=Y.lastSeq||0;if(J<=K)return;I.put({...Y,lastSeq:J})}})}async get($){let Q=this.db.transaction(G0,"readonly").objectStore(G0);return new Promise((I,V)=>{let Z=Q.get($);Z.onsuccess=()=>{let X=Z.result;if(!X)I(void 0);else I(KV(X))},Z.onerror=()=>V(Z.error)})}async set($,J){let Q=await this.get($);if(!Q)return 13;try{return await this.put({...Q,...J}),0}catch{return 18}}async del($){let J=this.db.transaction(G0,"readwrite"),Q=J.objectStore(G0);return new Promise((I,V)=>{J.oncomplete=()=>I(),J.onerror=()=>V(J.error),Q.delete($)})}async list(){let J=this.db.transaction(G0,"readonly").objectStore(G0);return new Promise((Q,I)=>{let V=J.getAll();V.onsuccess=()=>{let Z=V.result;Q(Z.map(KV))},V.onerror=()=>I(V.error)})}async wipe(){let $=this.db.transaction(G0,"readwrite"),J=$.objectStore(G0);return new Promise((Q,I)=>{$.oncomplete=()=>Q(),$.onerror=()=>I($.error),J.clear()})}}function a0($){return{eid:$.eid,...$.off!==void 0?{off:$.off}:{},...$.ctr!==void 0?{ctr:$.ctr}:{},...$.body!==void 0?{body:$.body}:{},apld:$.apld??!1}}function DQ($){return a0($).apld===!1}async function k0($,J,Q){let I=a0(J),V=I.body?.length??0,Z;if(I.body&&V>0)Z=await Q.blake3(I.body);let X={eid:I.eid,off:I.off??0,ctr:I.ctr??0,len:V,hsh:Z};return{hash:$,head:X,body:I.body,applied:I.apld}}class FQ{crypto;db;constructor($,J){this.crypto=J;this.db=$}async add($){let J=this.db.transaction(e,"readwrite"),Q=J.objectStore(e);return new Promise((I)=>{if($.length===0){I([]);return}let V=Array($.length).fill(0);J.oncomplete=()=>I(V),J.onerror=()=>{for(let Z=0;Z<V.length;Z++)V[Z]=18;I(V)};for(let Z=0;Z<$.length;Z++){let{key:X,data:Y}=$[Z],K=d(X),W=Q.put(Y,K);W.onerror=(G)=>{G.preventDefault(),V[Z]=18}}})}async del($){let J=[...$];if(J.length===0)return;let Q=this.db.transaction(e,"readwrite"),I=Q.objectStore(e);return new Promise((V,Z)=>{Q.oncomplete=()=>V(),Q.onerror=()=>Z(Q.error);for(let X of J){let Y=d(X);I.delete(Y)}})}async get($){let Q=this.db.transaction(e,"readonly").objectStore(e);return new Promise((I,V)=>{let Z=d($),X=Q.get(Z);X.onsuccess=async()=>{let Y=X.result;if(Y)I(await k0($,Y,this.crypto));else I(void 0)},X.onerror=()=>V(X.error)})}async has($){return await this.get($)!==void 0}async list(){let J=this.db.transaction(e,"readonly").objectStore(e);return new Promise((Q,I)=>{let V=[],Z=J.openCursor();Z.onsuccess=async(X)=>{let Y=X.target.result;if(Y){let{key:K,value:W}=Y,G=U0(K),N=await k0(G,W,this.crypto);V.push(N),Y.continue()}else Q(V)},Z.onerror=()=>I(Z.error)})}async last($){let Q=this.db.transaction(e,"readonly").objectStore(e);return new Promise((I,V)=>{let Z,X=Q.openCursor();X.onsuccess=async(Y)=>{let K=Y.target.result;if(K){let{key:W,value:G}=K;if(w0($,G.eid)){if(!Z||(G.ctr??0)>(Z.data.ctr??0)||(G.ctr??0)===(Z.data.ctr??0)&&(G.off??0)>(Z.data.off??0))Z={key:W,data:G}}K.continue()}else if(Z){let W=U0(Z.key);I(await k0(W,Z.data,this.crypto))}else I(void 0)},X.onerror=()=>V(X.error)})}async listUnapplied(){let Q=this.db.transaction(e,"readonly").objectStore(e).index(ZJ);return new Promise((I,V)=>{let Z=[],X=Q.openCursor(IDBKeyRange.only(!1));X.onsuccess=(Y)=>{let K=Y.target.result;if(K){let{primaryKey:W,value:G}=K;Z.push({hash:U0(W),data:G}),K.continue()}else Promise.all(Z.map(({hash:W,data:G})=>k0(W,G,this.crypto))).then(I).catch(V)},X.onerror=()=>V(X.error)})}async markApplied($){let J=[...$];if(J.length===0)return;let Q=this.db.transaction(e,"readwrite"),I=Q.objectStore(e);return new Promise((V,Z)=>{Q.oncomplete=()=>V(),Q.onerror=()=>Z(Q.error);for(let X of J){let Y=d(X),K=I.get(Y);K.onsuccess=()=>{let W=K.result;if(!W)return;I.put({...a0(W),apld:!0},Y)},K.onerror=(W)=>{W.preventDefault()}}})}async wipe(){let $=this.db.transaction(e,"readwrite"),J=$.objectStore(e);return new Promise((Q,I)=>{$.oncomplete=()=>Q(),$.onerror=()=>I($.error),J.clear()})}}class N${seed;crypto;constructor($,J){this.seed=$,this.crypto=J}async deriveFromKDM($){let J=z$(this.seed,$);return await this.crypto.blake3(J)}async derive($,J=0){let Q=new TextEncoder().encode($),I=new Uint8Array(8);new DataView(I.buffer).setBigUint64(0,BigInt(J),!1);let V=z$(Q,I);return await this.deriveFromKDM(V)}}class AQ{enclave;db;constructor($){this.db=$}async save($){let J=C0($),Q=this.db.transaction(g0,"readwrite"),I=Q.objectStore(g0);return new Promise((V,Z)=>{Q.oncomplete=()=>{this.enclave=new N$($,z0),V(this.enclave)},Q.onerror=()=>Z(Q.error),I.put(J,"seed")})}async load(){if(this.enclave)return this.enclave;let J=this.db.transaction(g0,"readonly").objectStore(g0);return new Promise((Q,I)=>{let V=J.get("seed");V.onsuccess=()=>{let Z=V.result;if(!Z)Q(void 0);else{let X=i0(Z);this.enclave=new N$(X,z0),Q(this.enclave)}},V.onerror=()=>I(V.error)})}async wipe(){this.enclave=void 0;let $=this.db.transaction(g0,"readwrite"),J=$.objectStore(g0);return new Promise((Q,I)=>{$.oncomplete=()=>Q(),$.onerror=()=>I($.error),J.delete("seed")})}}class PQ{db;constructor($){this.db=$}async enq($,J){let Q=[...J];if(Q.length===0)return;let I=this.db.transaction(H0,"readwrite"),V=I.objectStore(H0);return new Promise((Z,X)=>{I.oncomplete=()=>Z(),I.onerror=()=>X(I.error);for(let Y of Q){let K=C0(Y);V.put({host:$,hash:K})}})}async deq($,J){let Q=[...J];if(Q.length===0)return;let I=this.db.transaction(H0,"readwrite"),V=I.objectStore(H0);return new Promise((Z,X)=>{I.oncomplete=()=>Z(),I.onerror=()=>X(I.error);for(let Y of Q){let K=C0(Y);V.delete([$,K])}})}async list($){let Q=this.db.transaction(H0,"readonly").objectStore(H0);return new Promise((I,V)=>{let Z=Q.getAll();Z.onsuccess=()=>{let Y=Z.result.filter((K)=>K.host===$).map((K)=>K.hash);I(Y.map((K)=>i0(K)))},Z.onerror=()=>V(Z.error)})}async count(){let J=this.db.transaction(H0,"readonly").objectStore(H0);return new Promise((Q,I)=>{let V=J.count();V.onsuccess=()=>Q(V.result),V.onerror=()=>I(V.error)})}async wipe(){let $=this.db.transaction(H0,"readwrite"),J=$.objectStore(H0);return new Promise((Q,I)=>{$.oncomplete=()=>Q(),$.onerror=()=>I($.error),J.clear()})}}var g0="seedMeta",G0="hosts",H0="uploadQueue",O0="downloadQueue",e="messages",ZJ="apld",D8=3;class jQ{seed;hosts;uploads;downloads;messages;db;constructor($,J){this.db=$,this.seed=new AQ($),this.hosts=new TQ($),this.uploads=new PQ($),this.downloads=new wQ($),this.messages=new FQ($,J)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function F8(){return new Promise(($,J)=>{let Q=indexedDB.open("diplomatic-store-db",D8);Q.onupgradeneeded=()=>{let{result:I,transaction:V}=Q;if(!I.objectStoreNames.contains(g0))I.createObjectStore(g0);if(!I.objectStoreNames.contains(G0))I.createObjectStore(G0,{keyPath:"label"});if(!I.objectStoreNames.contains(H0))I.createObjectStore(H0,{keyPath:["host","hash"]});if(!I.objectStoreNames.contains(O0))I.createObjectStore(O0);let Z;if(!I.objectStoreNames.contains(e))Z=I.createObjectStore(e);else{if(!V)throw Error("missing upgrade transaction for messages store");Z=V.objectStore(e)}if(!Z.indexNames.contains(ZJ))Z.createIndex(ZJ,"apld",{unique:!1})},Q.onsuccess=()=>$(Q.result),Q.onerror=()=>J(Q.error)})}async function XJ($){let J=await F8();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new jQ(J,$)}function GV($){if(!$||typeof $!=="object")return!1;if(!("kind"in $))return!1;return typeof $.kind==="string"}function WV($){if(typeof $!=="number")return;return $}var l0="[DIPLOMATIC]";class F${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:Q$};clientState;xferState;constructor($,J,Q,I,V){this.worker=$,this.state=J,this.clientState=new A0(async()=>this.cachedClientState),this.xferState=new A0(async()=>this.cachedXferState),this.scheduledSync=new H$(V,async()=>{try{await this.request({id:this.allocId(),op:"sync"})}catch(Z){console.error(`${l0} worker sync after local write failed`,Z)}}),this.local=new r0(I,J,Q,()=>{throw Error(`${l0} local writer has no transport (use worker for network)`)},z0,!0,void 0,void 0,()=>{this.scheduledSync.schedule()}),this.ready=new Promise((Z,X)=>{this.resolveReady=Z,this.rejectReady=X}),this.worker.onmessage=(Z)=>{this.onMessage(Z.data)},this.worker.onerror=(Z)=>{console.error(`${l0} worker error`,Z),this.failReady(Error(`${l0} worker failed to load`))},this.worker.onmessageerror=()=>{this.failReady(Error(`${l0} worker message error`))}}failReady($){let J=this.rejectReady;if(this.rejectReady=void 0,this.resolveReady=void 0,J)J($)}async flushScheduledSync(){await this.scheduledSync.flush()}static async connect($,J,Q){let I=Q.clock??new L0,V=Q.syncDebounceMs??b$,Z=new F$(Q.worker,$,J,I,V),X=Q.readyTimeoutMs??15000,Y;try{await Promise.race([Z.ready,new Promise((K,W)=>{Y=setTimeout(()=>{W(Error(`${l0} worker ready timeout after ${X}ms`))},X)})])}catch(K){throw Z.terminate(),K}finally{if(Y!==void 0)clearTimeout(Y)}return Z}async ping(){if(await this.ready,await this.request({id:this.allocId(),op:"ping"})!=="pong")throw Error(`${l0} worker ping failed`)}terminate(){this.scheduledSync.cancel(),this.worker.terminate();for(let[,$]of this.pending)$.reject(Error(`${l0} worker terminated`));this.pending.clear()}onMessage($){if(!GV($))return;let J=$;switch(J.kind){case"ready":{let Q=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,Q)Q();return}case"clientState":{this.cachedClientState=J.state,this.clientState.emit();return}case"xferState":{this.cachedXferState=J.state,this.xferState.emit();return}case"dirty":{this.state.notify(J.types);return}case"wiped":{this.state.clear();return}case"reply":{let Q=this.pending.get(J.id);if(!Q)return;if(this.pending.delete(J.id),J.ok)Q.resolve(J.result);else Q.reject(new YJ(J.status));return}default:return}}allocId(){let $=this.nextId;return this.nextId+=1,$}request($,J){return new Promise((Q,I)=>{if(this.pending.set($.id,{resolve:Q,reject:I}),J&&J.length>0)this.worker.postMessage($,J);else this.worker.postMessage($)})}async requestStatus($,J){try{let Q=await this.request($,J),I=WV(Q);if(I!==void 0)return I;return 0}catch(Q){if(Q instanceof YJ)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 J=$.slice();await this.request({id:this.allocId(),op:"setSeed",seed:J},[J.buffer])}async link($,J=!0){await this.ready,await this.local.link($,!1),await this.request({id:this.allocId(),op:"link",host:this.serializeHost($),connect:J})}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,J=!0){await this.ready,await this.request({id:this.allocId(),op:"connect",listen:$,sync:J})}async disconnect(){await this.ready,await this.request({id:this.allocId(),op:"disconnect"})}async insertRaw($){return await this.ready,this.local.insertRaw($)}async upsertRaw($,J,Q){return await this.ready,this.local.upsertRaw($,J,Q)}async insert($){return await this.ready,this.local.insert($)}async upsert($,J){return await this.ready,this.local.upsert($,J)}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 J=new Uint8Array(await $.arrayBuffer());return this.requestStatus({id:this.allocId(),op:"import",bytes:J},[J.buffer])}async export($,J){await this.ready;try{let Q=await this.request({id:this.allocId(),op:"export"});if(!(Q instanceof Uint8Array))return 12;let I=new Blob([Q.slice()]);return u$(I,$),0}catch(Q){if(Q instanceof YJ)return Q.status;return 12}}}class YJ extends Error{status;constructor($){super(`WorkerReplyError: ${L[$]}`);this.status=$;this.name="WorkerReplyError"}}var s0="[DIPLOMATIC]";async function KJ($){let J=$.clock??new L0;if($.worker!==void 0&&A8($)!==void 0)throw Error(`${s0} worker path requires IndexedDB on both sides; do not pass store (got a custom store)`);if($.worker===void 0){console.info(`${s0} sync on main thread `+"(no worker — app did not request a worker)");let V=await NV($.store);return P8(J,$.state,V)}if(typeof Worker>"u")throw Error(`${s0} worker was provided but Worker API is unavailable`);let Q=await NV(void 0);console.info(`${s0} attaching app-provided sync worker…`);let I=await F$.connect($.state,Q,{worker:$.worker,readyTimeoutMs:$.readyTimeoutMs,clock:J,syncDebounceMs:$.syncDebounceMs});return await I.ping(),console.info(`${s0} sync worker active (network + EntDB writes off main; local mutates on main; dirty signals only)`),{client:I,mode:"worker",dispose:()=>{console.info(`${s0} terminating sync worker`),I.terminate()}}}function A8($){if("store"in $)return $.store;return}async function P8($,J,Q){let I=new r0($,J,Q,g$,z0);return{client:I,mode:"main",dispose:()=>{I.disconnect()}}}async function NV($){if($!==void 0)return $;if(typeof indexedDB>"u")throw Error(`${s0} IndexedDB is unavailable; pass store explicitly (e.g. new MemoryStore(crypto))`);return XJ(z0)}function j8($){let[J,Q]=kQ();return GJ(()=>{async function I(){let Z=await $.clientState.get();Q(Z)}let V=$.clientState.listen(I);return I(),()=>{V()}},[$]),J}function k8($){let[J,Q]=kQ();return GJ(()=>{async function I(){let Z=await $.xferState.get();Q(Z)}let V=$.xferState.listen(I);return I(),()=>{V()}},[$]),J}function S8($){GJ(()=>{async function J(){try{await $.connect(),await $.sync()}catch(Z){console.error("reconnectAndSync failed",Z)}}function Q(){J()}function I(){if(typeof document<"u"&&document.visibilityState==="visible")J()}function V(){J()}if(globalThis.addEventListener("online",Q),typeof document<"u")document.addEventListener("visibilitychange",I);return globalThis.addEventListener("focus",V),globalThis.addEventListener("pageshow",V),()=>{if(globalThis.removeEventListener("online",Q),typeof document<"u")document.removeEventListener("visibilitychange",I);globalThis.removeEventListener("focus",V),globalThis.removeEventListener("pageshow",V)}},[$])}function L8($={}){let J=$.clock??new L0,{seed:Q,host:I,readyTimeoutMs:V}=$,Z=$.worker,X="store"in $?$.store:void 0,[Y,K]=kQ({stateMgr:qQ});return GJ(()=>{let W=!1,G;return(async()=>{let N=await CQ();if(W)return;let U=UQ(N),M=Z!==void 0?await KJ({state:U,clock:J,worker:Z,readyTimeoutMs:V}):await KJ({state:U,clock:J,store:X,readyTimeoutMs:V});if(W){M.dispose();return}G=M.dispose;let{client:O,mode:z}=M;if(Q)await O.setSeed(Q);if(I)await O.link(I);if(W){G();return}K({client:O,entDB:N,stateMgr:U,mode:z,error:void 0})})().catch((N)=>{let U=N instanceof Error?N:Error(String(N));if(console.error("[DIPLOMATIC] useClient init failed",U),!W)K((M)=>({...M,client:void 0,error:U}))}),()=>{W=!0,G?.()}},[J,Q,I,Z,X,V]),Y}import{use as _8,useEffect as MV,useRef as E8,useState as B8}from"react";function qV($,J,Q){let[I,V]=B8();return MV(()=>{async function Z(){let X=await Q();V(X)}return Z(),$.on(J,Z),()=>{$.off(J,Z)}},[$,J,Q]),I}function f8($,J,Q){let I=E8(Q());return MV(()=>{async function V(){I.current=Q()}return $.on(J,V),()=>{$.off(J,V)}},[$,J,Q]),_8(I.current)}function UV($,J){return`${$}:${J}`}class SQ{queue=new Map;async enq($){for(let J of $){let Q=UV(J.host,J.seq);this.queue.set(Q,J)}}async deq($,J){for(let Q of J){let I=UV($,Q);this.queue.delete(I)}}async list(){let $=[];for(let J of this.queue.values())$.push(J);return $}async count(){return this.queue.size}async wipe(){this.queue.clear()}}class LQ{hosts=new Map;async add($){let J={...$,lastSeq:0};this.hosts.set($.label,J)}async touch($,J){let Q=this.hosts.get($);if(!Q||J<=Q.lastSeq)return;this.hosts.set($,{...Q,lastSeq:J})}async get($){return this.hosts.get($)}async set($,J){let Q=this.hosts.get($);if(!Q)return 13;return this.hosts.set($,{...Q,...J}),0}async del($){this.hosts.delete($)}async list(){return this.hosts.values()}async wipe(){this.hosts.clear()}}class _Q{crypto;messages=new Map;constructor($){this.crypto=$}async add($){let J=[];for(let{key:Q,data:I}of $)this.messages.set(d(Q),I),J.push(0);return J}async del($){for(let J of $)this.messages.delete(d(J))}async get($){let J=this.messages.get(d($));if(J)return await k0($,J,this.crypto);return}async has($){return this.messages.has(d($))}async list(){let $=Array.from(this.messages.entries());return await Promise.all($.map(([Q,I])=>{let V=U0(Q);return k0(V,I,this.crypto)}))}async last($){let J;for(let[Q,I]of this.messages){if(w0($,I.eid)===!1)continue;let V=U0(Q);if(J===void 0)J={hash:V,data:I};else if((I.ctr??0)>(J.data.ctr??0)||(I.ctr??0)===(J.data.ctr??0)&&(I.off??0)>(J.data.off??0))J={hash:V,data:I}}if(J)return await k0(J.hash,J.data,this.crypto);return}async listUnapplied(){let $=[];for(let[J,Q]of this.messages){if(!DQ(Q))continue;let I=U0(J);$.push(await k0(I,Q,this.crypto))}return $}async markApplied($){for(let J of $){let Q=d(J),I=this.messages.get(Q);if(!I)continue;this.messages.set(Q,{...a0(I),apld:!0})}}async wipe(){this.messages.clear()}}class EQ{enclave;async save($){return this.enclave=new N$($,z0),this.enclave}async load(){return this.enclave}async wipe(){this.enclave=void 0}}class BQ{queue=new Map;async enq($,J){let Q=this.queue.get($)||new Set;this.queue.set($,Q);for(let I of J)Q.add(C0(I))}async deq($,J){let Q=this.queue.get($);if(Q)for(let I of J)Q.delete(C0(I))}async list($){let J=this.queue.get($);if(!J)return[];let Q=[];for(let I of J)Q.push(i0(I));return Q}async count(){let $=0;for(let J of this.queue.values())$+=J.size;return $}async wipe(){this.queue.clear()}}class zV{seed=new EQ;hosts=new LQ;uploads=new BQ;downloads=new SQ;messages;constructor($){this.messages=new _Q($)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}class OV{singletonType;latest;latestOff=-1;emitter=new v0;constructor($){this.singletonType=$}async apply($){for(let J of $){let Q=new n(J.eid),[I,V]=Q.readStruct(q0);if(V!==0)continue;let Z=new l;Z.writeVarString(this.singletonType);let X=Z.result();if(I.id.length===X.length&&I.id.every((Y,K)=>Y===X[K])){if(this.latest===void 0||J.off>this.latestOff)this.latestOff=J.off,this.latest=J.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 J of $)if(J===this.singletonType)this.emitter.emit(this.singletonType,null)};on=($,J)=>{this.emitter.addEventListener($,J)};off=($,J)=>{this.emitter.removeEventListener($,J)}}async function p9($,J){let Q=await XJ(z0),I=new r0(new L0,$,Q,g$,z0);return{client:I,setSeed:async(Z)=>{let X=i0(Z);await Q.seed.save(X),await Q.hosts.add({handle:J,label:"host",idx:0}),await I.connect()}}}export{S8 as useSyncOnResume,f8 as useStateWatcherSuspense,qV as useStateWatcher,k8 as useClientXferState,j8 as useClientState,L8 as useClient,I$ as shouldEmitItemProgress,XJ as openIDBStore,CQ as openEntIDB,KJ as openDiplomaticClient,qQ as nullStateManager,w8 as nullEntDB,a0 as normalizeStoredMessageData,DQ as isPendingApply,Q$ as idleProgress,i0 as htob,g$ as hostHTTPTransport,p9 as genWebClient,sV as genSingletonEID,UQ as entStateManager,q0 as eidCodec,R$ as defaultPeekProgressEvery,z0 as crypto,C0 as btoh,F$ as WorkerClient,v0 as TypedEventEmitter,r0 as SyncClient,L as Status,QJ as StateManager,OV as SingletonStateManager,zV as MemoryStore,jQ as IDBStore,PJ as HTTPTransport,RQ as EntIDB,YV as EntDBMemory,l as Encoder,n as Decoder,L0 as Clock};
@@ -145,6 +145,8 @@ export interface IClient<Handle extends HostHandle> {
145
145
  insert<T = unknown>(op: IInsertParams<T>): Promise<ValStat<IMessageHead>>;
146
146
  upsert<T = unknown>(op: IUpsertParams<T>, force?: boolean): Promise<ValStat<IMessageHead>>;
147
147
  delete(eid: EntityID): Promise<ValStat<IMessageHead>>;
148
+ /** Allocate an entity id (optional 8-byte id material; else random). */
149
+ genEID(id?: Uint8Array): Promise<ValStat<EntityID>>;
148
150
  sync(): Promise<Status>;
149
151
  wipe(): Promise<void>;
150
152
  import(file: File): Promise<Status>;
@@ -72,6 +72,7 @@ export declare class WorkerClient implements IClient<URL> {
72
72
  insert<T = unknown>(op: IInsertParams<T>): Promise<ValStat<IMessageHead>>;
73
73
  upsert<T = unknown>(op: IUpsertParams<T>, force?: boolean): Promise<ValStat<IMessageHead>>;
74
74
  delete(eid: EntityID): Promise<ValStat<IMessageHead>>;
75
+ genEID(id?: Uint8Array): Promise<ValStat<EntityID>>;
75
76
  sync(): Promise<Status>;
76
77
  wipe(): Promise<void>;
77
78
  import(file: File): Promise<Status>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@interncom/diplomatic",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "type": "module",
5
5
  "description": "Secure sync layer and CLI utilities for DIPLOMATIC",
6
6
  "files": [