@interncom/diplomatic 0.4.4 → 0.5.0

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.
@@ -58,10 +58,10 @@ export declare class SyncClient<Handle extends HostHandle> implements IClient<Ha
58
58
  private getClientState;
59
59
  private getXferState;
60
60
  /**
61
- * Persist msgs (apld=false), exec into app state, then optionally enq upload.
61
+ * Persist msgs (APLD_PENDING), exec into app state, then optionally enq upload.
62
62
  *
63
63
  * Order (crash-safe):
64
- * 1) durable archive 2) exec + apld=true 3) upload queue
64
+ * 1) durable archive 2) exec + APLD_APPLIED/APLD_ERROR 3) upload queue
65
65
  * Exec is where the app validates the msg; only successes are pushed.
66
66
  * Crash between 1–2 → drainApplyQueue / exec stage recovers.
67
67
  */
@@ -76,11 +76,13 @@ export declare class SyncClient<Handle extends HostHandle> implements IClient<Ha
76
76
  /** Apply specific archive keys via IStateManager and mark applied. */
77
77
  private applyHashes;
78
78
  /**
79
- * Apply a batch of archived msgs via IStateManager and mark successes applied.
79
+ * Apply a batch of archived msgs via IStateManager and mark outcomes.
80
+ * Success/NoChange → APLD_APPLIED; terminal failures → APLD_ERROR;
81
+ * transient stay APLD_PENDING.
80
82
  *
81
83
  * TODO: may need to chunk large batches (memory / IDB / UI). Also test edge
82
84
  * cases: state.apply returning stats.length !== msgs.length (short/long
83
- * array, holes) — markApplied currently indexes stats[i] against stored[i]
85
+ * array, holes) — mark paths currently index stats[i] against stored[i]
84
86
  * without validating length alignment.
85
87
  */
86
88
  private applyStored;
@@ -17,8 +17,8 @@ import { nullStateManager, StateManager } from "./state";
17
17
  import { IDBStore, openIDBStore } from "./stores/idb/store";
18
18
  import { MemoryStore } from "./stores/memory/store";
19
19
  import { SingletonStateManager } from "./shared/singleton";
20
- import type { Applier, IClient, IDiplomaticClientState, IHostRow, IStore, IStoredMessage, IStoredMessageData, IStoredMessageWrite } from "./types";
21
- import { isPendingApply, normalizeStoredMessageData } from "./types";
20
+ import type { ApldState, Applier, IClient, IDiplomaticClientState, IHostRow, IStore, IStoredMessage, IStoredMessageData, IStoredMessageWrite } from "./types";
21
+ import { APLD_APPLIED, APLD_ERROR, APLD_PENDING, apldFromStored, isApldState, isPendingApply, isTerminalApplyFailure, setApld } from "./types";
22
22
  import type { SyncProgressEvent } from "./progress";
23
23
  import { defaultPeekProgressEvery, idleProgress, shouldEmitItemProgress } from "./progress";
24
24
  import { openDiplomaticClient, type OpenDiplomaticClientMainOptions, type OpenDiplomaticClientOptions, type OpenDiplomaticClientWorkerOptions, type OpenedDiplomaticClient } from "./openClient";
@@ -28,5 +28,5 @@ export declare function genWebClient(stateMgr: IStateManager, url: URL): Promise
28
28
  client: SyncClient<URL>;
29
29
  setSeed: (seedHex: string) => Promise<void>;
30
30
  }>;
31
- export { btoh, Clock, crypto, Decoder, defaultPeekProgressEvery, eidCodec, Encoder, EntDBMemory, EntIDB, EntitiesQuery, EntityID, entStateManager, genSingletonEID, GroupID, hostHTTPTransport, htob, HTTPTransport, IDBStore, idleProgress, IEntDB, IEntity, isPendingApply, IStore, MasterSeed, MemoryStore, normalizeStoredMessageData, nullEntDB, nullStateManager, openDiplomaticClient, openEntIDB, openIDBStore, shouldEmitItemProgress, SingletonStateManager, StateManager, Status, SyncClient, TypedEventEmitter, useClient, useClientState, useClientXferState, useStateWatcher, useStateWatcherSuspense, useSyncOnResume, WorkerClient, };
32
- export type { Applier, HostHandle, IClient, ICrypto, IDiplomaticClientState, IHostConnectionInfo, IHostRow, IMessage, IMutateOp, IOp, IStateManager, IStoredMessage, IStoredMessageData, IStoredMessageWrite, ITransport, OpenDiplomaticClientMainOptions, OpenDiplomaticClientOptions, OpenDiplomaticClientWorkerOptions, OpenedDiplomaticClient, SyncProgressEvent, WorkerClientOptions, };
31
+ export { APLD_APPLIED, APLD_ERROR, APLD_PENDING, apldFromStored, btoh, Clock, crypto, Decoder, defaultPeekProgressEvery, eidCodec, Encoder, EntDBMemory, EntIDB, EntitiesQuery, EntityID, entStateManager, genSingletonEID, GroupID, hostHTTPTransport, htob, HTTPTransport, IDBStore, idleProgress, IEntDB, IEntity, isApldState, isPendingApply, isTerminalApplyFailure, IStore, MasterSeed, MemoryStore, nullEntDB, nullStateManager, openDiplomaticClient, openEntIDB, openIDBStore, setApld, shouldEmitItemProgress, SingletonStateManager, StateManager, Status, SyncClient, TypedEventEmitter, useClient, useClientState, useClientXferState, useStateWatcher, useStateWatcherSuspense, useSyncOnResume, WorkerClient, };
32
+ export type { ApldState, Applier, HostHandle, IClient, ICrypto, IDiplomaticClientState, IHostConnectionInfo, IHostRow, IMessage, IMutateOp, IOp, IStateManager, IStoredMessage, IStoredMessageData, IStoredMessageWrite, ITransport, OpenDiplomaticClientMainOptions, OpenDiplomaticClientOptions, OpenDiplomaticClientWorkerOptions, OpenedDiplomaticClient, SyncProgressEvent, WorkerClientOptions, };
@@ -1 +1 @@
1
- function n$(V){let $=V.length,Q=0,Z=0;while(Z<$){let J=V.charCodeAt(Z++);if((J&4294967168)===0){Q++;continue}else if((J&4294965248)===0)Q+=2;else{if(J>=55296&&J<=56319){if(Z<$){let I=V.charCodeAt(Z);if((I&64512)===56320)++Z,J=((J&1023)<<10)+(I&1023)+65536}}if((J&4294901760)===0)Q+=3;else Q+=4}}return Q}function aQ(V,$,Q){let Z=V.length,J=Q,I=0;while(I<Z){let W=V.charCodeAt(I++);if((W&4294967168)===0){$[J++]=W;continue}else if((W&4294965248)===0)$[J++]=W>>6&31|192;else{if(W>=55296&&W<=56319){if(I<Z){let Y=V.charCodeAt(I);if((Y&64512)===56320)++I,W=((W&1023)<<10)+(Y&1023)+65536}}if((W&4294901760)===0)$[J++]=W>>12&15|224,$[J++]=W>>6&63|128;else $[J++]=W>>18&7|240,$[J++]=W>>12&63|128,$[J++]=W>>6&63|128}$[J++]=W&63|128}}var sQ=new TextEncoder,tQ=50;function eQ(V,$,Q){sQ.encodeInto(V,$.subarray(Q))}function y$(V,$,Q){if(V.length>tQ)eQ(V,$,Q);else aQ(V,$,Q)}var VZ=4096;function gV(V,$,Q){let Z=$,J=Z+Q,I=[],W="";while(Z<J){let Y=V[Z++];if((Y&128)===0)I.push(Y);else if((Y&224)===192){let X=V[Z++]&63;I.push((Y&31)<<6|X)}else if((Y&240)===224){let X=V[Z++]&63,G=V[Z++]&63;I.push((Y&31)<<12|X<<6|G)}else if((Y&248)===240){let X=V[Z++]&63,G=V[Z++]&63,K=V[Z++]&63,N=(Y&7)<<18|X<<12|G<<6|K;if(N>65535)N-=65536,I.push(N>>>10&1023|55296),N=56320|N&1023;I.push(N)}else I.push(Y);if(I.length>=VZ)W+=String.fromCharCode(...I),I.length=0}if(I.length>0)W+=String.fromCharCode(...I);return W}var $Z=new TextDecoder,QZ=200;function ZZ(V,$,Q){let Z=V.subarray($,$+Q);return $Z.decode(Z)}function b$(V,$,Q){if(Q>QZ)return ZZ(V,$,Q);else return gV(V,$,Q)}class g0{type;data;constructor(V,$){this.type=V,this.data=$}}class s extends Error{constructor(V){super(V);let $=Object.create(s.prototype);Object.setPrototypeOf(this,$),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:s.name})}}var i0=4294967295;function p$(V,$,Q){let Z=Q/4294967296,J=Q;V.setUint32($,Z),V.setUint32($+4,J)}function IV(V,$,Q){let Z=Math.floor(Q/4294967296),J=Q;V.setUint32($,Z),V.setUint32($+4,J)}function WV(V,$){let Q=V.getInt32($),Z=V.getUint32($+4);return Q*4294967296+Z}function l$(V,$){let Q=V.getUint32($),Z=V.getUint32($+4);return Q*4294967296+Z}var JZ=-1,IZ=4294967295,WZ=17179869183;function YZ({sec:V,nsec:$}){if(V>=0&&$>=0&&V<=WZ)if($===0&&V<=IZ){let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,V),Q}else{let Q=V/4294967296,Z=V&4294967295,J=new Uint8Array(8),I=new DataView(J.buffer);return I.setUint32(0,$<<2|Q&3),I.setUint32(4,Z),J}else{let Q=new Uint8Array(12),Z=new DataView(Q.buffer);return Z.setUint32(0,$),IV(Z,4,V),Q}}function XZ(V){let $=V.getTime(),Q=Math.floor($/1000),Z=($-Q*1000)*1e6,J=Math.floor(Z/1e9);return{sec:Q+J,nsec:Z-J*1e9}}function GZ(V){if(V instanceof Date){let $=XZ(V);return YZ($)}else return null}function KZ(V){let $=new DataView(V.buffer,V.byteOffset,V.byteLength);switch(V.byteLength){case 4:{let Q=$.getUint32(0),Z=0;return{sec:Q,nsec:0}}case 8:{let Q=$.getUint32(0),Z=$.getUint32(4),J=(Q&3)*4294967296+Z,I=Q>>>2;return{sec:J,nsec:I}}case 12:{let Q=WV($,4),Z=$.getUint32(0);return{sec:Q,nsec:Z}}default:throw new s(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${V.length}`)}}function RZ(V){let $=KZ(V);return new Date($.sec*1000+$.nsec/1e6)}var r$={type:JZ,encode:GZ,decode:RZ};class v0{static defaultCodec=new v0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(r$)}register({type:V,encode:$,decode:Q}){if(V>=0)this.encoders[V]=$,this.decoders[V]=Q;else{let Z=-1-V;this.builtInEncoders[Z]=$,this.builtInDecoders[Z]=Q}}tryToEncode(V,$){for(let Q=0;Q<this.builtInEncoders.length;Q++){let Z=this.builtInEncoders[Q];if(Z!=null){let J=Z(V,$);if(J!=null){let I=-1-Q;return new g0(I,J)}}}for(let Q=0;Q<this.encoders.length;Q++){let Z=this.encoders[Q];if(Z!=null){let J=Z(V,$);if(J!=null)return new g0(Q,J)}}if(V instanceof g0)return V;return null}decode(V,$,Q){let Z=$<0?this.builtInDecoders[-1-$]:this.decoders[$];if(Z)return Z(V,$,Q);else return new g0($,V)}}function NZ(V){return V instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&V instanceof SharedArrayBuffer}function c0(V){if(V instanceof Uint8Array)return V;else if(ArrayBuffer.isView(V))return new Uint8Array(V.buffer,V.byteOffset,V.byteLength);else if(NZ(V))return new Uint8Array(V);else return Uint8Array.from(V)}var MZ=100,wZ=2048;class YV{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??v0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.maxDepth=V?.maxDepth??MZ,this.initialBufferSize=V?.initialBufferSize??wZ,this.sortKeys=V?.sortKeys??!1,this.forceFloat32=V?.forceFloat32??!1,this.ignoreUndefined=V?.ignoreUndefined??!1,this.forceIntegerToFloat=V?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new YV({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(V){if(this.entered)return this.clone().encodeSharedRef(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(V){if(this.entered)return this.clone().encode(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(V,$){if($>this.maxDepth)throw Error(`Too deep objects in depth ${$}`);if(V==null)this.encodeNil();else if(typeof V==="boolean")this.encodeBoolean(V);else if(typeof V==="number")if(!this.forceIntegerToFloat)this.encodeNumber(V);else this.encodeNumberAsFloat(V);else if(typeof V==="string")this.encodeString(V);else if(this.useBigInt64&&typeof V==="bigint")this.encodeBigInt64(V);else this.encodeObject(V,$)}ensureBufferSizeToWrite(V){let $=this.pos+V;if(this.view.byteLength<$)this.resizeBuffer($*2)}resizeBuffer(V){let $=new ArrayBuffer(V),Q=new Uint8Array($),Z=new DataView($);Q.set(this.bytes),this.view=Z,this.bytes=Q}encodeNil(){this.writeU8(192)}encodeBoolean(V){if(V===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber(V){if(!this.forceIntegerToFloat&&Number.isSafeInteger(V))if(V>=0)if(V<128)this.writeU8(V);else if(V<256)this.writeU8(204),this.writeU8(V);else if(V<65536)this.writeU8(205),this.writeU16(V);else if(V<4294967296)this.writeU8(206),this.writeU32(V);else if(!this.useBigInt64)this.writeU8(207),this.writeU64(V);else this.encodeNumberAsFloat(V);else if(V>=-32)this.writeU8(224|V+32);else if(V>=-128)this.writeU8(208),this.writeI8(V);else if(V>=-32768)this.writeU8(209),this.writeI16(V);else if(V>=-2147483648)this.writeU8(210),this.writeI32(V);else if(!this.useBigInt64)this.writeU8(211),this.writeI64(V);else this.encodeNumberAsFloat(V);else this.encodeNumberAsFloat(V)}encodeNumberAsFloat(V){if(this.forceFloat32)this.writeU8(202),this.writeF32(V);else this.writeU8(203),this.writeF64(V)}encodeBigInt64(V){if(V>=BigInt(0))this.writeU8(207),this.writeBigUint64(V);else this.writeU8(211),this.writeBigInt64(V)}writeStringHeader(V){if(V<32)this.writeU8(160+V);else if(V<256)this.writeU8(217),this.writeU8(V);else if(V<65536)this.writeU8(218),this.writeU16(V);else if(V<4294967296)this.writeU8(219),this.writeU32(V);else throw Error(`Too long string: ${V} bytes in UTF-8`)}encodeString(V){let Q=n$(V);this.ensureBufferSizeToWrite(5+Q),this.writeStringHeader(Q),y$(V,this.bytes,this.pos),this.pos+=Q}encodeObject(V,$){let Q=this.extensionCodec.tryToEncode(V,this.context);if(Q!=null)this.encodeExtension(Q);else if(Array.isArray(V))this.encodeArray(V,$);else if(ArrayBuffer.isView(V))this.encodeBinary(V);else if(typeof V==="object")this.encodeMap(V,$);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply(V)}`)}encodeBinary(V){let $=V.byteLength;if($<256)this.writeU8(196),this.writeU8($);else if($<65536)this.writeU8(197),this.writeU16($);else if($<4294967296)this.writeU8(198),this.writeU32($);else throw Error(`Too large binary: ${$}`);let Q=c0(V);this.writeU8a(Q)}encodeArray(V,$){let Q=V.length;if(Q<16)this.writeU8(144+Q);else if(Q<65536)this.writeU8(220),this.writeU16(Q);else if(Q<4294967296)this.writeU8(221),this.writeU32(Q);else throw Error(`Too large array: ${Q}`);for(let Z of V)this.doEncode(Z,$+1)}countWithoutUndefined(V,$){let Q=0;for(let Z of $)if(V[Z]!==void 0)Q++;return Q}encodeMap(V,$){let Q=Object.keys(V);if(this.sortKeys)Q.sort();let Z=this.ignoreUndefined?this.countWithoutUndefined(V,Q):Q.length;if(Z<16)this.writeU8(128+Z);else if(Z<65536)this.writeU8(222),this.writeU16(Z);else if(Z<4294967296)this.writeU8(223),this.writeU32(Z);else throw Error(`Too large map object: ${Z}`);for(let J of Q){let I=V[J];if(!(this.ignoreUndefined&&I===void 0))this.encodeString(J),this.doEncode(I,$+1)}}encodeExtension(V){if(typeof V.data==="function"){let Q=V.data(this.pos+6),Z=Q.length;if(Z>=4294967296)throw Error(`Too large extension object: ${Z}`);this.writeU8(201),this.writeU32(Z),this.writeI8(V.type),this.writeU8a(Q);return}let $=V.data.length;if($===1)this.writeU8(212);else if($===2)this.writeU8(213);else if($===4)this.writeU8(214);else if($===8)this.writeU8(215);else if($===16)this.writeU8(216);else if($<256)this.writeU8(199),this.writeU8($);else if($<65536)this.writeU8(200),this.writeU16($);else if($<4294967296)this.writeU8(201),this.writeU32($);else throw Error(`Too large extension object: ${$}`);this.writeI8(V.type),this.writeU8a(V.data)}writeU8(V){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,V),this.pos++}writeU8a(V){let $=V.length;this.ensureBufferSizeToWrite($),this.bytes.set(V,this.pos),this.pos+=$}writeI8(V){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,V),this.pos++}writeU16(V){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,V),this.pos+=2}writeI16(V){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,V),this.pos+=2}writeU32(V){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,V),this.pos+=4}writeI32(V){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,V),this.pos+=4}writeF32(V){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,V),this.pos+=4}writeF64(V){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,V),this.pos+=8}writeU64(V){this.ensureBufferSizeToWrite(8),p$(this.view,this.pos,V),this.pos+=8}writeI64(V){this.ensureBufferSizeToWrite(8),IV(this.view,this.pos,V),this.pos+=8}writeBigUint64(V){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,V),this.pos+=8}writeBigInt64(V){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,V),this.pos+=8}}function XV(V,$){return new YV($).encodeSharedRef(V)}function GV(V){return`${V<0?"-":""}0x${Math.abs(V).toString(16).padStart(2,"0")}`}var zZ=16,UZ=16;class iV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(V=zZ,$=UZ){this.maxKeyLength=V,this.maxLengthPerKey=$,this.caches=[];for(let Q=0;Q<this.maxKeyLength;Q++)this.caches.push([])}canBeCached(V){return V>0&&V<=this.maxKeyLength}find(V,$,Q){let Z=this.caches[Q-1];V:for(let J of Z){let I=J.bytes;for(let W=0;W<Q;W++)if(I[W]!==V[$+W])continue V;return J.str}return null}store(V,$){let Q=this.caches[V.length-1],Z={bytes:V,str:$};if(Q.length>=this.maxLengthPerKey)Q[Math.random()*Q.length|0]=Z;else Q.push(Z)}decode(V,$,Q){let Z=this.find(V,$,Q);if(Z!=null)return this.hit++,Z;this.miss++;let J=gV(V,$,Q),I=Uint8Array.prototype.slice.call(V,$,$+Q);return this.store(I,J),J}}var vV="array",o0="map_key",c$="map_value",FZ=(V)=>{if(typeof V==="string"||typeof V==="number")return V;throw new s("The type of key must be string or number but "+typeof V)};class d${stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(V){let $=this.getUninitializedStateFromPool();$.type=vV,$.position=0,$.size=V,$.array=Array(V)}pushMapState(V){let $=this.getUninitializedStateFromPool();$.type=o0,$.readCount=0,$.size=V,$.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let V={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(V)}return this.stack[this.stackHeadPosition]}release(V){if(this.stack[this.stackHeadPosition]!==V)throw Error("Invalid stack state. Released state is not on top of the stack.");if(V.type===vV){let Q=V;Q.size=0,Q.array=void 0,Q.position=0,Q.type=void 0}if(V.type===o0||V.type===c$){let Q=V;Q.size=0,Q.map=void 0,Q.readCount=0,Q.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var d0=-1,uV=new DataView(new ArrayBuffer(0)),PZ=new Uint8Array(uV.buffer);try{uV.getInt8(0)}catch(V){if(!(V instanceof RangeError))throw Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var h$=RangeError("Insufficient data"),OZ=new iV;class KV{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=uV;bytes=PZ;headByte=d0;stack=new d$;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??v0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.rawStrings=V?.rawStrings??!1,this.maxStrLength=V?.maxStrLength??i0,this.maxBinLength=V?.maxBinLength??i0,this.maxArrayLength=V?.maxArrayLength??i0,this.maxMapLength=V?.maxMapLength??i0,this.maxExtLength=V?.maxExtLength??i0,this.keyDecoder=V?.keyDecoder!==void 0?V.keyDecoder:OZ,this.mapKeyConverter=V?.mapKeyConverter??FZ}clone(){return new KV({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=d0,this.stack.reset()}setBuffer(V){let $=c0(V);this.bytes=$,this.view=new DataView($.buffer,$.byteOffset,$.byteLength),this.pos=0}appendBuffer(V){if(this.headByte===d0&&!this.hasRemaining(1))this.setBuffer(V);else{let $=this.bytes.subarray(this.pos),Q=c0(V),Z=new Uint8Array($.length+Q.length);Z.set($),Z.set(Q,$.length),this.setBuffer(Z)}}hasRemaining(V){return this.view.byteLength-this.pos>=V}createExtraByteError(V){let{view:$,pos:Q}=this;return RangeError(`Extra ${$.byteLength-Q} of ${$.byteLength} byte(s) found at buffer[${V}]`)}decode(V){if(this.entered)return this.clone().decode(V);try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);let $=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return $}finally{this.entered=!1}}*decodeMulti(V){if(this.entered){yield*this.clone().decodeMulti(V);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(V){if(this.entered)return this.clone().decodeAsync(V);try{this.entered=!0;let $=!1,Q;for await(let W of V){if($)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(W);try{Q=this.doDecodeSync(),$=!0}catch(Y){if(!(Y instanceof RangeError))throw Y}this.totalPos+=this.pos}if($){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Q}let{headByte:Z,pos:J,totalPos:I}=this;throw RangeError(`Insufficient data in parsing ${GV(Z)} at ${I} (${J} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(V){return this.decodeMultiAsync(V,!0)}decodeStream(V){return this.decodeMultiAsync(V,!1)}async*decodeMultiAsync(V,$){if(this.entered){yield*this.clone().decodeMultiAsync(V,$);return}try{this.entered=!0;let Q=$,Z=-1;for await(let J of V){if($&&Z===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(J),Q)Z=this.readArraySize(),Q=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--Z===0)break}catch(I){if(!(I instanceof RangeError))throw I}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){V:while(!0){let V=this.readHeadByte(),$;if(V>=224)$=V-256;else if(V<192)if(V<128)$=V;else if(V<144){let Z=V-128;if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V<160){let Z=V-144;if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else{let Z=V-160;$=this.decodeString(Z,0)}else if(V===192)$=null;else if(V===194)$=!1;else if(V===195)$=!0;else if(V===202)$=this.readF32();else if(V===203)$=this.readF64();else if(V===204)$=this.readU8();else if(V===205)$=this.readU16();else if(V===206)$=this.readU32();else if(V===207)if(this.useBigInt64)$=this.readU64AsBigInt();else $=this.readU64();else if(V===208)$=this.readI8();else if(V===209)$=this.readI16();else if(V===210)$=this.readI32();else if(V===211)if(this.useBigInt64)$=this.readI64AsBigInt();else $=this.readI64();else if(V===217){let Z=this.lookU8();$=this.decodeString(Z,1)}else if(V===218){let Z=this.lookU16();$=this.decodeString(Z,2)}else if(V===219){let Z=this.lookU32();$=this.decodeString(Z,4)}else if(V===220){let Z=this.readU16();if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else if(V===221){let Z=this.readU32();if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else if(V===222){let Z=this.readU16();if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V===223){let Z=this.readU32();if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V===196){let Z=this.lookU8();$=this.decodeBinary(Z,1)}else if(V===197){let Z=this.lookU16();$=this.decodeBinary(Z,2)}else if(V===198){let Z=this.lookU32();$=this.decodeBinary(Z,4)}else if(V===212)$=this.decodeExtension(1,0);else if(V===213)$=this.decodeExtension(2,0);else if(V===214)$=this.decodeExtension(4,0);else if(V===215)$=this.decodeExtension(8,0);else if(V===216)$=this.decodeExtension(16,0);else if(V===199){let Z=this.lookU8();$=this.decodeExtension(Z,1)}else if(V===200){let Z=this.lookU16();$=this.decodeExtension(Z,2)}else if(V===201){let Z=this.lookU32();$=this.decodeExtension(Z,4)}else throw new s(`Unrecognized type byte: ${GV(V)}`);this.complete();let Q=this.stack;while(Q.length>0){let Z=Q.top();if(Z.type===vV)if(Z.array[Z.position]=$,Z.position++,Z.position===Z.size)$=Z.array,Q.release(Z);else continue V;else if(Z.type===o0){if($==="__proto__")throw new s("The key __proto__ is not allowed");Z.key=this.mapKeyConverter($),Z.type=c$;continue V}else if(Z.map[Z.key]=$,Z.readCount++,Z.readCount===Z.size)$=Z.map,Q.release(Z);else{Z.key=null,Z.type=o0;continue V}}return $}}readHeadByte(){if(this.headByte===d0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=d0}readArraySize(){let V=this.readHeadByte();switch(V){case 220:return this.readU16();case 221:return this.readU32();default:if(V<160)return V-144;else throw new s(`Unrecognized array type byte: ${GV(V)}`)}}pushMapState(V){if(V>this.maxMapLength)throw new s(`Max length exceeded: map length (${V}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(V)}pushArrayState(V){if(V>this.maxArrayLength)throw new s(`Max length exceeded: array length (${V}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(V)}decodeString(V,$){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String(V,$);return this.decodeBinary(V,$)}decodeUtf8String(V,$){if(V>this.maxStrLength)throw new s(`Max length exceeded: UTF-8 byte length (${V}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+$+V)throw h$;let Q=this.pos+$,Z;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached(V))Z=this.keyDecoder.decode(this.bytes,Q,V);else Z=b$(this.bytes,Q,V);return this.pos+=$+V,Z}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===o0;return!1}decodeBinary(V,$){if(V>this.maxBinLength)throw new s(`Max length exceeded: bin length (${V}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(V+$))throw h$;let Q=this.pos+$,Z=this.bytes.subarray(Q,Q+V);return this.pos+=$+V,Z}decodeExtension(V,$){if(V>this.maxExtLength)throw new s(`Max length exceeded: ext length (${V}) > maxExtLength (${this.maxExtLength})`);let Q=this.view.getInt8(this.pos+$),Z=this.decodeBinary(V,$+1);return this.extensionCodec.decode(Z,Q,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let V=this.view.getUint8(this.pos);return this.pos++,V}readI8(){let V=this.view.getInt8(this.pos);return this.pos++,V}readU16(){let V=this.view.getUint16(this.pos);return this.pos+=2,V}readI16(){let V=this.view.getInt16(this.pos);return this.pos+=2,V}readU32(){let V=this.view.getUint32(this.pos);return this.pos+=4,V}readI32(){let V=this.view.getInt32(this.pos);return this.pos+=4,V}readU64(){let V=l$(this.view,this.pos);return this.pos+=8,V}readI64(){let V=WV(this.view,this.pos);return this.pos+=8,V}readU64AsBigInt(){let V=this.view.getBigUint64(this.pos);return this.pos+=8,V}readI64AsBigInt(){let V=this.view.getBigInt64(this.pos);return this.pos+=8,V}readF32(){let V=this.view.getFloat32(this.pos);return this.pos+=4,V}readF64(){let V=this.view.getFloat64(this.pos);return this.pos+=8,V}}function nV(V,$){return new KV($).decode(V)}class H0{listeners=new Map;addEventListener(V,$){let Q=this.listeners.get(V);if(!Q)Q=new Set,this.listeners.set(V,Q);return Q.add($),()=>{this.removeEventListener(V,$)}}removeEventListener(V,$){let Q=this.listeners.get(V);if(Q){if(Q.delete($),Q.size===0)this.listeners.delete(V)}}emit(V,$){let Q=this.listeners.get(V);if(Q){let Z=Array.from(Q);for(let J of Z)J($)}}emitAll(V){let $=Array.from(this.listeners.keys());for(let Q of $)this.emit(Q,V)}}class G0{getter;static eventName="update";emitter;constructor(V){this.getter=V;this.emitter=new H0}get=()=>this.getter();async emit(){let V=await this.getter();queueMicrotask(()=>this.emitter.emit(G0.eventName,V))}listen(V){return this.emitter.addEventListener(G0.eventName,V),()=>{this.emitter.removeEventListener(G0.eventName,V)}}}var C0=64;var o$=32,D0=8;var RV=32;var a$=30000,s$=512,_;((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"})(_||={});function q(V){return[V,0]}function R(V){return[void 0,V]}function qZ(V){if(V<0)console.info("N",V),console.trace();if(typeof V!=="bigint")V=BigInt(V);if(V<0n)return R(10);let $=[];while(V>0n){let Q=Number(V&0x7fn);if(V>>=7n,V>0n)$.push(Q|128);else $.push(Q)}if($.length===0)return q(new Uint8Array([0]));if($.length>8)return R(26);return q(new Uint8Array($))}function HZ(V,$=0){let Q=0n,Z=0,J=$;while(!0){if(J>=V.length)return R(14);let I=V[J++];if(I===void 0)return R(14);if(Q|=BigInt(I&127)<<BigInt(Z),(I&128)===0){if(J-$>8)return R(26);return q({value:Q>0x1fffffffffffffn?Q:Number(Q),bytesRead:J-$})}if(Z+=7,Z>=56)return R(26)}}class B{data;pos=0;constructor(V){this.data=V}static async fromResponse(V){let $=await V.arrayBuffer(),Q=new Uint8Array($);return new B(Q)}readBigInt(){if(this.pos+8>this.data.length)return R(7);let V=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,q(V)}readDate(){let[V,$]=this.readVarInt();if($!==0)return R($);return q(new Date(V))}readVarInt(){let[V,$]=HZ(this.data,this.pos);if($!==0)return R($);this.pos+=V.bytesRead;let Q=V.value;return q(typeof Q==="bigint"?Number(Q):Q)}readVarString(){let[V,$]=this.readVarInt();if($!==0)return R($);let[Q,Z]=this.readBytes(V);if(Z!==0)return R(Z);let J=new TextDecoder().decode(Q);return q(J)}readBytes(V){if(V<0)return R(10);if(this.pos+V>this.data.length)return R(23);let $=this.data.slice(this.pos,this.pos+V);return this.pos+=V,q($)}readVarBytes(){let[V,$]=this.readVarInt();if($!==0)return R($);return this.readBytes(V)}readStruct(V){return V.decode(this)}readStructs(V){let $=[];while(!this.done()){let[Q,Z]=this.readStruct(V);if(Z!==0)return R(Z);$.push(Q)}return q($)}readBytesSeq(V){let $=[];while(!this.done()){let[Q,Z]=this.readBytes(V);if(Z!==0)return R(Z);$.push(Q)}return q($)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class x{parts=[];writeBigInt(V){let $=new Uint8Array(8);new DataView($.buffer).setBigUint64(0,V,!1),this.parts.push($)}writeDate(V){let $=V.getTime();return this.writeVarInt($)}writeVarInt(V){let[$,Q]=qZ(V);if(Q!==0)return Q;return this.parts.push($),0}writeVarString(V){let $=new TextEncoder().encode(V),Q=this.writeVarInt($.length);if(Q!==0)return Q;return this.writeBytes($),0}prependBytes(V){this.parts.unshift(V)}writeBytes(V){this.parts.push(V)}writeVarBytes(V){let $=this.writeVarInt(V.length);if($!==0)return $;return this.writeBytes(V),0}writeStruct(V,$){return V.encode(this,$)}writeStructs(V,$){for(let Q of $){let Z=this.writeStruct(V,Q);if(Z!==0)return Z}return 0}writeBytesSeq(V){for(let $ of V)this.writeBytes($)}result(){let V=this.parts.reduce((Z,J)=>Z+J.length,0),$=new Uint8Array(V),Q=0;for(let Z of this.parts)$.set(Z,Q),Q+=Z.length;return $}*scan(){for(let V of this.parts)yield V}}async function yV(V,$,Q){let Z=new x,J=Z.writeDate($);if(J!==0)return R(J);let I=Z.result(),W=await Q.signEd25519(I,V.privateKey);return q({pubKey:V.publicKey,sig:W,timestamp:$})}async function T0(V,$,Q){let Z=Q.now().getTime(),J=V.timestamp.getTime();if(Math.abs(Z-J)>a$)return 4;let W=new x;W.writeDate(V.timestamp);let Y=W.result();if(!await $.checkSigEd25519(V.sig,Y,V.pubKey))return 3;return 0}var t={encode(V,$){let Q=V.writeVarBytes($.id);if(Q!==0)return Q;let Z=V.writeDate($.ts);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return R(Q);let[Z,J]=V.readDate();if(J!==0)return R(J);return q({id:$,ts:Z})}};function u0(V){let $=new x,Q=$.writeStruct(t,V);if(Q!==0)return R(Q);let Z=$.result();return q(Z)}async function CZ(V){return u0({id:V,ts:new Date(0)})}var Y0={encode(V,$){let Q=V.writeVarBytes($.eid);if(Q!==0)return Q;let Z=V.writeVarInt($.off);if(Z!==0)return Z;let J=V.writeVarInt($.ctr);if(J!==0)return J;let I=V.writeVarInt($.len);if(I!==0)return I;if($.hsh)V.writeBytes($.hsh);return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return R(Q);let Z=new B($),[,J]=t.decode(Z);if(J!==0)return R(J);let[I,W]=V.readVarInt();if(W!==0)return R(W);let[Y,X]=V.readVarInt();if(X!==0)return R(X);let[G,K]=V.readVarInt();if(K!==0)return R(K);let N;if(G>0){let[M,z]=V.readBytes(RV);if(z!==0)return R(z);N=M}return q({eid:$,off:I,ctr:Y,len:G,hsh:N})}};function o(V){return Array.from(V).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}function A0(V){if(V.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(V.length/2);for(let Q=0;Q<V.length;Q+=2)$[Q/2]=Number.parseInt(V.substr(Q,2),16);return $}function X0(V,$){if(V===$)return!0;if(V.byteLength!==$.byteLength)return!1;return V.every((Q,Z)=>Q===$[Z])}var k;if(typeof Uint8Array.prototype.toBase64==="function")k=(V)=>V.toBase64();else k=(V)=>btoa(String.fromCharCode(...V));var Z0;if(typeof Uint8Array.fromBase64==="function")Z0=(V)=>Uint8Array.fromBase64(V);else Z0=(V)=>Uint8Array.from(atob(V),($)=>$.charCodeAt(0));function a0(V,$){let Q=new Uint8Array(V.length+$.length);return Q.set(V,0),Q.set($,V.length),Q}function t$(V,$,Q){return Q.checkSigEd25519(V.sig,V.headCph,$)}async function bV(V,$,Q){let Z=a0($.privateKey,V);return(await Q.blake3(Z)).slice(0,D0)}async function e$(V,$,Q,Z){let J;if(V.bod&&V.len>0)J=await Q.blake3(V.bod);let I=new x,W=Y0.encode(I,{...V,hsh:J});if(W!==0)return R(W);let Y=I.result(),X=await bV(Y,$,Q),G=await Z.deriveFromKDM(X),K=await Q.encryptXSalsa20Poly1305Combined(Y,G),N=V.bod?await Q.encryptXSalsa20Poly1305Combined(V.bod,G):new Uint8Array(0),M=await Q.signEd25519(K,$.privateKey);return q({sig:M,kdm:X,headCph:K,bodyCph:N})}async function pV(V,$,Q,Z,J){let I=new B(V),[W,Y]=Y0.decode(I);if(Y!==0)return R(14);let X;try{X=$&&$.length>0?await Z.decryptXSalsa20Poly1305Combined($,Q):void 0}catch{return R(20)}let G=W.hsh&&X===void 0,K=W.hsh===void 0&&X!==void 0;if(G||K)return R(19);if(W.hsh&&X){let M=await Z.blake3(X);if(!X0(M,W.hsh))return R(19)}let N=J??await Z.blake3(V);return q({msgHead:W,bod:X,headHash:N})}class w0{now(){return new Date}}function VQ(V,$,Q,Z){let J=$.getTime()-V.getTime(),I=Q.getTime()-Z.getTime();return(J+I)/2}var s0={encode(V,$){if(V.writeVarInt($.quota),$.quota>0){if($.usage===void 0)return 9;V.writeVarInt($.usage)}return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return R(Q);let Z;if($>0){let[J,I]=V.readVarInt();if(I!==0)return R(I);Z=J}return q({quota:$,usage:Z})}};var lV={encode(V,$){V.writeBytes(new Uint8Array([$.status]));let Q=V.writeDate($.timeRcvd);if(Q!==0)return Q;let Z=V.writeDate($.timeSent);if(Z!==0)return Z;let J=V.writeVarInt($.subscription.term);if(J!==0)return J;let I=V.writeVarInt($.subscription.elapsed);if(I!==0)return I;let W=V.writeStruct(s0,$.subscription.stat);if(W!==0)return W;let Y=V.writeStruct(s0,$.subscription.dyn);if(Y!==0)return Y;return 0},decode(V){let[$,Q]=V.readBytes(1);if(Q!==0)return R(Q);let Z=$[0],[J,I]=V.readDate();if(I!==0)return R(I);let[W,Y]=V.readDate();if(Y!==0)return R(Y);let[X,G]=V.readVarInt();if(G!==0)return R(G);let[K,N]=V.readVarInt();if(N!==0)return R(N);let[M,z]=V.readStruct(s0);if(z!==0)return R(z);let[U,w]=V.readStruct(s0);if(w!==0)return R(w);return q({status:Z,timeRcvd:J,timeSent:W,subscription:{term:X,elapsed:K,stat:M,dyn:U}})}};async function rV(V,$,Q){let{crypto:Z,enclave:J}=V,I=await J.derive($,Q);return await Z.deriveEd25519KeyPair(I)}var hV={encode(V,$){let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarInt($.seq);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return R(Q);let[Z,J]=V.readVarInt();if(J!==0)return R(J);return q({headCph:$,seq:Z})}};var Q0={encode(V,$){V.writeBytes($.pubKey),V.writeBytes($.sig);let Q=V.writeDate($.timestamp);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readBytes(o$);if(Q!==0)return R(Q);let[Z,J]=V.readBytes(C0);if(J!==0)return R(J);let[I,W]=V.readDate();if(W!==0)return R(W);return q({pubKey:$,sig:Z,timestamp:I})}};var $Q={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct(Q0,Q);if(I!==0)return I;for(let W of Z)J.writeVarInt(W);return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct(Q0);if(Y!==0)return Y;let X=await T0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W,[K,N]=await I.hasUser(G);if(N!==0)return N;if(!K)return 5;let[M,z]=$.readVarInt();if(z!==0)return z;if(!$.done())return 8;let[U,w]=await I.listHeads(G,M);if(w!==0)return w;return Q.writeStructs(hV,U)},decodeResp(V){return V.readStructs(hV)}};var cV={encode(V,$){V.writeVarInt($.seq);let Q=V.writeVarBytes($.bodyCph);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return R(Q);let[Z,J]=V.readVarBytes();if(J!==0)return R(J);return q({seq:$,bodyCph:Z})}};var QQ={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct(Q0,Q);if(I!==0)return I;for(let W of Z){let Y=J.writeVarInt(W);if(Y!==0)return Y}return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct(Q0);if(Y!==0)return Y;let X=await T0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W,[K,N]=await I.hasUser(G);if(N!==0)return N;if(!K)return 5;let M=[];while(!$.done()){let[w,O]=$.readVarInt();if(O!==0)return O;M.push(w)}console.info(`PULL: ${M.length} bags`);let[z,U]=await I.getBodies(G,M);if(U!==0)return U;if(!z)return 17;for(let{seq:w,bodyCph:O}of z){let P={seq:w,bodyCph:O},C=Q.writeStruct(cV,P);if(C!==0)return C}return 0},decodeResp(V){return V.readStructs(cV)}};var dV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarBytes($.bodyCph);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readBytes(C0);if(Q!==0)return R(Q);let[Z,J]=V.readBytes(D0);if(J!==0)return R(J);let[I,W]=V.readVarBytes();if(W!==0)return R(W);let[Y,X]=V.readVarBytes();if(X!==0)return R(X);return q({sig:$,kdm:Z,headCph:I,bodyCph:Y})}};var NV={encode(V,$){let Q=V.writeVarInt($.seq);if(Q!==0)return Q;let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=$.bodyCph?$.bodyCph.length:0,I=V.writeVarInt(J);if(I!==0)return I;if(J>0){if(!$.bodyCph)return 10;V.writeBytes($.bodyCph)}return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return R(Q);let[Z,J]=V.readVarBytes();if(J!==0)return R(J);let[I,W]=V.readVarInt();if(W!==0)return R(W);let Y;if(I>0){let[X,G]=V.readBytes(I);if(G!==0)return R(G);Y=X}return q({seq:$,headCph:Z,bodyCph:Y})}};var MV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readBytes(C0);if(Q!==0)return R(Q);let[Z,J]=V.readBytes(D0);if(J!==0)return R(J);let[I,W]=V.readVarBytes();if(W!==0)return R(W);return q({sig:$,kdm:Z,headCph:I})}};var wV={encode(V,$){if(V.writeVarInt($.idx),V.writeBytes(new Uint8Array([$.status])),$.status===0)V.writeVarInt($.seq);return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return R(Q);let[Z,J]=V.readBytes(1);if(J!==0)return R(J);let I=Z[0];if(I!==0)return q({idx:$,status:I});let[W,Y]=V.readVarInt();if(Y!==0)return R(Y);return q({idx:$,status:I,seq:W})}};var ZQ={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct(Q0,Q);if(I!==0)return I;let W=J.writeStructs(dV,Z);if(W!==0)return W;return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I,notifier:W}=V,[Y,X]=$.readStruct(Q0);if(X!==0)return X;let G=await T0(Y,J,Z);if(G!==0)return G;let{pubKey:K}=Y,[N,M]=await I.hasUser(K);if(M!==0)return M;if(!N)return 5;let[z,U]=$.readStructs(dV);if(U!==0)return U;console.info(`PUSH: ${z.length} bags`);let w=[],O=[];for(let F=0;F<z.length;F++){let T=z[F];if(!await t$(T,K,J)){let E={idx:F,status:3},S=Q.writeStruct(wV,E);if(S!==0)return S;continue}w.push(F),O.push(T)}let[P,C]=await I.setBags(K,O);if(C!==0)return C;if(!P||P.length!==O.length)return 17;let A=[];for(let F=0;F<O.length;F++){let T=O[F],L=w[F],E=P[F],S=new x,m=S.writeStruct(MV,T);if(m!==0)return m;let f=S.result(),H={seq:E,headCph:f};if(z.length===1&&T.bodyCph.length<=s$)H.bodyCph=T.bodyCph;A.push(H);let g={idx:L,status:0,seq:E},v=Q.writeStruct(wV,g);if(v!==0)return v}if(A.length>0){let F=new x,T=F.writeStructs(NV,A);if(T!==0)return T;let L=F.result();await Promise.resolve(W.push(K,L))}return 0},decodeResp(V){return V.readStructs(wV)}};var JQ={async encodeReq(V,$,Q,Z,J){return J.writeStruct(Q0,Q)},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct(Q0);if(Y!==0)return Y;let X=await T0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W;if(!$.done())return 8;let[K,N]=await I.addUser(G);if(N!==0)return N;return 0},decodeResp(V){return q(void 0)}};class oV{url;websocket;constructor(V){this.url=V}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(V,$,Q=()=>{},Z=()=>{}){let{url:J}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let I=new x;I.writeStruct(Q0,V);let W=I.result(),Y=o(W);return J.searchParams.set("t",Y),this.websocket=new WebSocket(J),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),Z()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Q()},this.websocket.onmessage=(X)=>{let G=new Uint8Array(X.data);$(G)},this.websocket.onerror=(X)=>{console.log(`ERROR: ${JSON.stringify(X)}`),this.websocket=void 0,Q()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var h={user:{path:"/user",endpoint:JQ,name:0},push:{path:"/push",endpoint:ZQ,name:2},peek:{path:"/peek",endpoint:$Q,name:1},pull:{path:"/pull",endpoint:QQ,name:3}},DZ={0:h.user,2:h.push,1:h.peek,3:h.pull},zY={[h.user.path]:h.user,[h.push.path]:h.push,[h.peek.path]:h.peek,[h.pull.path]:h.pull};class aV{url;listener;constructor(V){this.url=V;this.listener=new oV(V)}async call(V,$){let{path:Q}=DZ[V],Z=new URL(Q,this.url);try{return await TZ(Z,$)}catch{return R(25)}}}var zV=(V)=>{return new aV(V.handle)};async function TZ(V,$){let Q=await fetch(V,{method:"POST",body:$.result().slice()});if(!Q.ok)return R(24);let Z=await B.fromResponse(Q);return q(Z)}class UV{enclave;crypto;host;clock;transport;updateHostMeta;constructor(V,$,Q,Z,J,I){this.enclave=V;this.crypto=$;this.host=Q;this.clock=Z;this.transport=J;this.updateHostMeta=I}async call(V,$){let{clock:Q,crypto:Z,transport:J}=this,{endpoint:I,name:W}=V,Y=await this.keys(),X=Q.now(),[G,K]=await yV(Y,X,Z);if(K!==0)return R(K);let N=new x,M=await I.encodeReq(this,Y,G,$,N);if(M!==0)return R(M);let z=Q.now(),[U,w]=await J.call(W,N),O=Q.now();if(w!==0)return R(w);let[P,C]=U.readStruct(lV);if(C!==0)return R(C);if(P.status!==0)return R(P.status);let F={clockOffset:VQ(z,P.timeRcvd,P.timeSent,O),subscription:P.subscription},T=await this.updateHostMeta(F);if(T!==0)return R(T);return I.decodeResp(U)}keys=()=>{let{host:V}=this;return rV(this,V.label,V.idx)};seal=async(V)=>{let{crypto:$,enclave:Q}=this,Z=await this.keys();return e$(V,Z,$,Q)};register=()=>this.call(h.user,[]);peek=(V)=>this.call(h.peek,[V]);push=(V)=>this.call(h.push,V);pull=(V)=>this.call(h.pull,V);listen=async(V,$,Q)=>{let{clock:Z,crypto:J,host:I,transport:W}=this,{listener:Y}=W,X=await rV(this,I.label,I.idx),G=Z.now(),[K,N]=await yV(X,G,J);if(N!==0)return N;return await Y.connect(K,V,$,Q)};isConnected(){let V=this.transport?.listener;if(V&&typeof V.connected==="function")return V.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var sV={encode(V,$){let Q=V.writeVarString($.lbl);if(Q!==0)return Q;let Z=V.writeVarInt($.idx);if(Z!==0)return Z;let J=V.writeVarInt($.num);if(J!==0)return J;return V.writeBytes($.hsh),V.writeBytes($.sig),0},decode(V){let[$,Q]=V.readVarString();if(Q!==0)return R(Q);let[Z,J]=V.readVarInt();if(J!==0)return R(J);let[I,W]=V.readVarInt();if(W!==0)return R(W);let[Y,X]=V.readBytes(RV);if(X!==0)return R(X);let[G,K]=V.readBytes(C0);if(K!==0)return R(K);return q({lbl:$,idx:Z,num:I,hsh:Y,sig:G})}};var tV={encode(V,$){let Q=V.writeStruct(sV,$.head);if(Q!==0)return Q;let Z=V.writeVarBytes($.indexEnc);if(Z!==0)return Z;let J=V.writeVarBytes($.bodyEnc);if(J!==0)return J;return 0},decode(V){let[$,Q]=V.readStruct(sV);if(Q!==0)return R(Q);let[Z,J]=V.readVarBytes();if(J!==0)return R(J);let[I,W]=V.readVarBytes();if(W!==0)return R(W);return q({head:$,indexEnc:Z,bodyEnc:I})}};var eV={encode(V,$){V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarInt($.lenBody);if(Z!==0)return Z;if($.lenBody>0&&$.offBody!==void 0){let J=V.writeVarInt($.offBody);if(J!==0)return J}return 0},decode(V){let[$,Q]=V.readBytes(D0);if(Q!==0)return R(Q);let[Z,J]=V.readVarBytes();if(J!==0)return R(J);let[I,W]=V.readVarInt();if(W!==0)return R(W);let Y;if(I>0){let[X,G]=V.readVarInt();if(G!==0)return R(G);Y=X}return q({kdm:$,headCph:Z,lenBody:I,offBody:Y})}};async function IQ(V,$,Q,Z,J){let I=await J.derive(V,$),W=await Z.deriveEd25519KeyPair(I),Y=new x,X=new x,G=0,K=0;for(let C of Q){let A=new x,F=A.writeStruct(Y0,C.head);if(F!==0)return R(F);let T=A.result(),L=await bV(T,W,Z),E=await J.deriveFromKDM(L),S=await Z.encryptXSalsa20Poly1305Combined(T,E),m=C.body?await Z.encryptXSalsa20Poly1305Combined(C.body,E):new Uint8Array(0),f=C.head.len>0&&C.head.hsh!==void 0?m.length:0,H={kdm:L,headCph:S,lenBody:f,offBody:f>0?K:void 0},g=Y.writeStruct(eV,H);if(g!==0)return R(g);if(C.body)X.writeBytes(m),K+=m.length;G++}let N=X.result(),M=Y.result(),z=await Z.blake3(M),U=await Z.signEd25519(z,W.privateKey),w={lbl:V,idx:$,num:G,hsh:z,sig:U},O=new x;O.writeStruct(tV,{head:w,indexEnc:M,bodyEnc:N});let P=O.result();return q(P)}async function WQ(V,$,Q){let[Z,J]=tV.decode(new B(V));if(J!==0)return R(J);let{head:I,indexEnc:W,bodyEnc:Y}=Z,X=await Q.derive(I.lbl,I.idx),G=await $.deriveEd25519KeyPair(X);if(!await $.checkSigEd25519(I.sig,I.hsh,G.publicKey))return R(3);let N=await $.blake3(W);if(!X0(N,I.hsh))return R(19);let M=new B(W),z=[];for(let w=0;w<I.num;w++){let[O,P]=M.readStruct(eV);if(P!==0)return R(P);z.push(O)}if(z.length!==I.num)return R(14);let U=[];for(let w of z){let O=await Q.deriveFromKDM(w.kdm),P=await $.decryptXSalsa20Poly1305Combined(w.headCph,O),[C,A]=Y0.decode(new B(P));if(A!==0)return R(A);let F;if(w.lenBody>0&&w.offBody!==void 0){if(C.hsh===void 0)return R(14);let T=Y.slice(w.offBody,w.offBody+w.lenBody);F=await $.decryptXSalsa20Poly1305Combined(T,O);let L=await $.blake3(F);if(!X0(L,C.hsh))return R(19)}U.push({head:C,body:F})}return q(U)}async function YQ({now:V,bod:$,crypto:Q}){let Z=await Q.genRandomBytes(8),J=new x,I=J.writeStruct(t,{id:Z,ts:V});if(I!==0)return R(I);let W=J.result();return FV({now:V,eid:W,ctr:0,bod:$,crypto:Q})}async function FV({now:V,eid:$,ctr:Q,bod:Z,crypto:J}){let I=new B($),[W,Y]=t.decode(I);if(Y!==0)return R(Y);let X=V.getTime()-W.ts.getTime(),G,K=Z?.length??0;if(Z&&K>0)G=await J.blake3(Z);return q({eid:$,off:X,ctr:Q,len:K,hsh:G})}class PV{inflight=null;again=!1;run(V){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain(V),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain(V){try{this.again=!1;let $=await V();while(this.again)this.again=!1,$=await V();return $}finally{this.inflight=null}}}var OV=100;class t0{timer=null;delayMs;work;tail=new PV;constructor(V,$){this.delayMs=V<0?0:V,this.work=$}schedule(){if(this.delayMs<=0){this.fire();return}if(this.timer!==null)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=null,this.fire()},this.delayMs)}async flush(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null,this.fire();await this.tail.flush()}cancel(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null}fire(){return this.tail.run(this.work)}}function XQ(V){let $=new B(V.eid),[Q,Z]=t.decode($);if(Z!==0)return;return Q.ts.getTime()+V.off}function AZ(V,$){let Q=XQ(V),Z=XQ($);if(Q===void 0&&Z===void 0)return 0;if(Q===void 0)return 1;if(Z===void 0)return-1;if(Z!==Q)return Z-Q;return $.ctr-V.ctr}function e0(V,$){return V.slice().sort((Q,Z)=>AZ($(Q),$(Z)))}var n0={phase:"idle"},VV=50;function V$(V,$,Q){if(V<=0||$<=0)return!1;if(V===1||V===$)return!0;return V%Q===0}function qV(V,$){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(V,$);return}let Q=URL.createObjectURL(V),Z=document.createElement("a");Z.href=Q,Z.download=$,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(Q)}function $$(V,$,Q){let Z=[],J=[],I=0;for(let W of V){let Y=$(W);if(J.length>0&&I+Y>Q)Z.push(J),J=[],I=0;if(J.push(W),I+=Y,I>=Q)Z.push(J),J=[],I=0}if(J.length>0)Z.push(J);return Z}async function GQ(V,$,Q){let Z=V.length;if(Z<1)return[];let J=Array(Z),I=0,W=Math.min(Math.max(1,$),Z),Y=async()=>{while(!0){let G=I;if(I+=1,G>=Z)return;J[G]=await Q(V[G],G)}},X=[];for(let G=0;G<W;G++)X.push(Y());return await Promise.all(X),J}async function Q$(V,$,Q,Z){let J=new B(V.headCph),[I,W]=J.readStruct(MV);if(W!==0)return R(W);let{sig:Y,kdm:X,headCph:G}=I;if(!await Z.checkSigEd25519(Y,G,$.publicKey))return R(3);let N=await Q.deriveFromKDM(X),M;try{M=await Z.decryptXSalsa20Poly1305Combined(G,N)}catch{return R(20)}return q({kdm:X,headEnc:M})}var Z$=1048576,J$=1048576,_Z=64;function jZ(V){return V.sig.length+V.kdm.length+V.headCph.length+V.bodyCph.length}async function LZ(V,$,Q,Z,J){if(Z.length<1)return 0;let[I,W]=await V.push(Z);if(W!==0)return W;if(!I)return 27;for(let X of I){if(X.status!==0){console.error("push err",X);continue}let G=J[X.idx];if(!G){console.error("no hash",X);continue}await $.uploads.deq(Q,[G])}let Y=await $.hosts.get(Q);if(Y){let X=Y.lastSeq,G=X,K=[];for(let N of I)if(N.status===0)K.push(N.seq);K.sort((N,M)=>N-M);for(let N of K)if(N===X+1)X=N;if(X>G)await $.hosts.touch(Q,X)}return 0}async function KQ(V,$){if($.length<1)return q([]);let Q=new Map,Z=[];for(let Y of $)Q.set(Y.seq,Y),Z.push(Y.seq);let[J,I]=await V.pull(Z);if(I!==0)return R(I);if(!J)return R(27);let W=[];for(let{seq:Y,bodyCph:X}of J){let G=Q.get(Y);if(!G)continue;W.push({dl:G,bodyCph:X})}return q(W)}async function SZ(V,$,Q,Z){if(Z.length<1)return q({parts:[],hashes:[]});let J=[],I=[],W=[],Y=new Map;for(let{dl:G,bodyCph:K}of Z){let{head:N,kdm:M,seq:z,host:U}=G,[w,O]=await RQ(G,Q);if(O!==0||!w){let m=Y.get(U)??[];m.push(z),Y.set(U,m);continue}let{headEnc:P,headEncHash:C}=w,A=await $.deriveFromKDM(M),[F,T]=await pV(P,K,A,Q,C);if(T!==0||!F){let m=Y.get(U)??[];m.push(z),Y.set(U,m);continue}let L={head:N,body:F.bod},E=F.headHash;W.push({key:E,data:UQ(L)}),J.push(L),I.push(E);let S=Y.get(U)??[];S.push(z),Y.set(U,S)}let X=await V.messages.add(W);for(let[G,K]of Y)await V.downloads.deq(G,K);for(let G=0;G<X.length;G++){let K=X[G];if(K!==0&&K!==15)console.error("ERR storing",_[K],"for message",G)}return q({parts:J,hashes:I})}async function RQ(V,$){let Q=V.headEnc;if(!Q){let J=new x,I=J.writeStruct(Y0,V.head);if(I!==0)return R(I);Q=J.result()}if(V.headEncHash)return q({headEnc:Q,headEncHash:V.headEncHash});let Z=await $.blake3(Q);return q({headEnc:Q,headEncHash:Z})}async function NQ(V,$,Q){let Z=new Set;for(let W of $)Z.add(k(W));if(Z.size<1)return;let J=Array.from(await V.downloads.list());if(J.length<1)return;let I=new Map;for(let W of J){let Y;if(W.headEncHash)Y=k(W.headEncHash);else{let[G,K]=await RQ(W,Q);if(K!==0||!G)continue;Y=k(G.headEncHash)}if(!Z.has(Y))continue;let X=I.get(W.host)??[];X.push(W.seq),I.set(W.host,X)}for(let[W,Y]of I)await V.downloads.deq(W,Y)}async function MQ({conn:V,store:$,enclave:Q,host:Z,crypto:J,onProgress:I,peekProgressEvery:W,peekConcurrency:Y}){let X=await V.keys(),G=[],[K,N]=await V.peek(Z.lastSeq);if(N!==0)return N;let M=K.length,z=W??VV,U=Y??_Z;if(I&&M>0)I({phase:"peek",host:Z.label,done:0,total:M});let w=0,O=await GQ(K,U,async(P)=>{let[C,A]=await Q$(P,X,Q,J),F;if(A!==0||!C)F={ok:!1,seq:P.seq,stat:A};else{let T=await J.blake3(C.headEnc);F={ok:!0,seq:P.seq,kdm:C.kdm,headEnc:C.headEnc,headEncHash:T}}if(w+=1,I&&V$(w,M,z))I({phase:"peek",host:Z.label,done:w,total:M});return F});for(let P of O){if(!P.ok){console.error("peek: decrypting item head",P.stat);continue}if(await $.messages.has(P.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await $.uploads.deq(Z.label,[P.headEncHash]),await $.downloads.deq(Z.label,[P.seq]);continue}let A=new B(P.headEnc),[F,T]=A.readStruct(Y0);if(T!==0){console.error("peek: reading item head",T);continue}G.push({kdm:P.kdm,head:F,seq:P.seq,host:Z.label,headEnc:P.headEnc,headEncHash:P.headEncHash})}if(await $.downloads.enq(G),K.length>0){let P=Math.max(...K.map((C)=>C.seq));await $.hosts.touch(Z.label,P)}if(I)I({phase:"peek",host:Z.label,done:M,total:M});return 0}var mZ=1048576;async function wQ({conn:V,store:$,host:Q,maxPushBytes:Z,onProgress:J}){let I=Z??Z$,W=mZ,Y=await $.uploads.list(Q.label),X=Y.length,G=0;if(J&&X>0)J({phase:"push",host:Q.label,done:0,total:X});let K=$$(Y,(w)=>Math.max(1,w.bodyLen),W),N=[],M=[],z=0,U=async()=>{if(N.length<1)return 0;let w=N.length,O=await LZ(V,$,Q.label,N,M);if(N=[],M=[],z=0,O===0){if(G+=w,J)J({phase:"push",host:Q.label,done:G,total:X})}return O};for(let w of K){let O=await $.messages.getMany(w.map((P)=>P.hash));for(let P=0;P<w.length;P++){let C=w[P],A=O[P];if(!A){G+=1;continue}let F={...A.head,bod:A.body},[T,L]=await V.seal(F);if(L!==0)return L;if(!T)return 12;let E=jZ(T);if(N.length>0&&z+E>I){let S=await U();if(S!==0)return S}if(N.push(T),M.push(C.hash),z+=E,z>=I){let S=await U();if(S!==0)return S}}}return U()}async function zQ({conn:V,store:$,enclave:Q,host:Z,crypto:J,maxPullBytes:I,onProgress:W},Y){let X=I??J$,G=await $.downloads.list(),K=Array.from(G).filter((O)=>O.host===Z.label);if(K.length<1)return 15;let N=e0(K,(O)=>O.head),M=$$(N,(O)=>O.head.len,X),z=N.length,U=0;if(W)W({phase:"pull",host:Z.label,done:0,total:z});let w=KQ(V,M[0]);for(let O=0;O<M.length;O++){let[P,C]=await w;if(C!==0||!P)return C;if(U+=M[O].length,W)W({phase:"pull",host:Z.label,done:U,total:z});let A=M[O+1];if(A)w=KQ(V,A);if(W)W({phase:"open",host:Z.label,done:U,total:z});let F=e0(P,(L)=>L.dl.head),[,T]=await SZ($,Q,J,F);if(T!==0)return T;if(Y){if(W)W({phase:"exec",host:Z.label,done:U,total:z});await Y()}}return 0}function UQ({head:V,body:$}){return{eid:V.eid,...V.off!==0?{off:V.off}:{},...V.ctr!==0?{ctr:V.ctr}:{},body:$,apld:!1}}async function FQ(V,{conn:$,store:Q,enclave:Z,host:J,crypto:I,onProgress:W},Y){let X=J.label,G=await $.keys(),K=new B(V),[N,M]=K.readStructs(NV);if(M!==0){console.error("Failed decoding notif",_[M]);return}let z=!1,w=(await Q.hosts.get(X))?.lastSeq,O=[],P=!1;for(let F of N){let[T,L]=await Q$({seq:F.seq,headCph:F.headCph},G,Z,I);if(L!==0){console.error("Failed decrypting notif",_[L]);continue}let E=await I.blake3(T.headEnc);if(await Q.messages.has(E))continue;let S=new B(T.headEnc),[m,f]=S.readStruct(Y0);if(f!==0){console.error("Failed to parse head",_[f]);continue}if(!F.bodyCph&&m.len>0)P=!0,await Q.downloads.enq([{seq:F.seq,host:X,kdm:T.kdm,head:m,headEnc:T.headEnc,headEncHash:E}]);else O.push({...T,head:m,bodyCph:F.bodyCph,headEncHash:E});if(w===void 0||F.seq!==w+1)console.log("out of seq",F.seq,w),z=!0;else w=F.seq}if(w!==void 0)await Q.hosts.touch(J.label,w);let C=[];for(let F of O){let T=await Z.deriveFromKDM(F.kdm),[L,E]=await pV(F.headEnc,F.bodyCph,T,I);if(E!==0){console.error("Failed to open body",_[E]);continue}C.push({key:F.headEncHash,data:UQ({head:F.head,body:L.bod})})}let A=await Q.messages.add(C);for(let F=0;F<A.length;F++){let T=A[F];if(T!==0&&T!==15)console.error("ERR storing",_[T],"for message",F)}if(W&&C.length>0)W({phase:"open",host:J.label,done:C.length,total:C.length});if(z||P||C.length>0)Y()}class _0{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new PV;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=VV;lastProgress=n0;scheduledSync;constructor(V,$,Q,Z,J,I=!0,W=Z$,Y=J$,X){this.clock=V;this.state=$;this.store=Q;this.transport=Z;this.crypto=J;this.forceSkewHandlingByDefault=I;this.onScheduleSync=X;this.maxPushBytes=W,this.maxPullBytes=Y,this.clientState=new G0(()=>this.getClientState()),this.xferState=new G0(()=>this.getXferState()),this.scheduledSync=new t0(OV,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(G){console.error("Debounced sync failed:",G)}})}emitProgress=(V)=>{this.lastProgress=V,this.xferState.emit()};async setSeed(V){await this.store.seed.save(V),this.clientState.emit()}async getClientState(){let{store:V,connections:$}=this,Q=await V.seed.load(),Z=await V.hosts.list(),J=!1;for(let I of $.values())if(I.isConnected()){J=!0;break}return{hasSeed:Q!==void 0,hasHost:Array.from(Z).length>0,connected:J}}async getXferState(){let{uploads:V,downloads:$}=this.store,Q=await V.count();return{numDownloads:await $.count(),numUploads:Q,progress:this.lastProgress}}apply=async(V,$={enqueueUpload:!0,triggerUpload:!0})=>{let Q=[],Z=[];for(let{head:I,body:W}of V){let Y=new x;Y.writeStruct(Y0,I);let X=Y.result(),G=await this.crypto.blake3(X),K={eid:I.eid,...I.off!==0?{off:I.off}:{},...I.ctr!==0?{ctr:I.ctr}:{},body:W,apld:!1};Q.push(G),Z.push({key:G,data:K})}await this.store.messages.add(Z),await NQ(this.store,Q,this.crypto);let J=await this.applyHashes(Q);if($.enqueueUpload){let I=[];for(let W=0;W<Q.length;W++){let Y=J[W];if(Y===0||Y===15)I.push({hash:Q[W],bodyLen:V[W].body?.length??0})}if(I.length>0){let W=await this.store.hosts.list();for(let Y of W)await this.store.uploads.enq(Y.label,I);this.xferState.emit()}}if($.triggerUpload)this.scheduleSync();return J};enqueueApplyJob(V){let $=this.applyChain.then(V,V);return this.applyChain=$.then(()=>{return},()=>{return}),$}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let V=await this.store.messages.listUnapplied();if(V.length<1)return[];let $=e0(V,(Q)=>Q.head);return this.applyStored($)}applyHashes=(V)=>{return this.enqueueApplyJob(async()=>{let $=[];for(let J of V){let I=await this.store.messages.get(J);if(I)$.push(I)}let Q=await this.applyStored($),Z=new Map;for(let J=0;J<$.length;J++)Z.set(k($[J].hash),Q[J]??12);return V.map((J)=>Z.get(k(J))??13)})};async applyStored(V){if(V.length<1)return[];let $=V.map((J)=>({...J.head,bod:J.body})),Q=await this.state.apply($),Z=[];for(let J=0;J<V.length;J++){let I=Q[J];if(I===0||I===15)Z.push(V[J].hash)}if(Z.length>0)await this.store.messages.markApplied(Z);return Q}async insertRaw(V){let{clock:$,crypto:Q}=this,[Z,J]=await YQ({now:$.now(),bod:V,crypto:Q});if(J!==0)return R(J);return await this.apply([{head:Z,body:V}]),q(Z)}async upsertRaw(V,$,Q=!1){let{clock:Z,crypto:J,store:I}=this,W=Z.now(),Y=await I.messages.last(V);if(Y){let z=new B(V),[U,w]=z.readStruct(t);if(w!==0)return R(w);if(U.ts.getTime()+Y.head.off>W.getTime()){if(Q===!1)return R(4);let P=Y.head.off+1,C=Y.head.ctr+1,A={eid:V,off:P,ctr:C,len:0},T=(await this.apply([{head:A,body:void 0}]))[0];if(T!==0)return R(T);if($===void 0)return q(A);let[L,E]=u0({id:U.id,ts:W});if(E!==0)return R(E);let S={now:W,eid:L,ctr:0,bod:$,crypto:J},[m,f]=await FV(S);if(f!==0)return R(f);let g=(await this.apply([{head:m,body:$}]))[0];if(g!==0)return R(g);return q(m)}}let X=(Y?.head.ctr??-1)+1,[G,K]=await FV({now:W,eid:V,ctr:X,bod:$,crypto:J});if(K!==0)return R(K);let M=(await this.apply([{head:G,body:$}]))[0];if(M!==0)return R(M);return q(G)}async insert(V){let{body:$,type:Q,gid:Z,pid:J}=V,W=XV({body:$,type:Q,gid:Z,pid:J});return this.insertRaw(W)}async upsert(V,$=this.forceSkewHandlingByDefault){let{eid:Q,body:Z,type:J,gid:I,pid:W}=V;if(Q===void 0)return this.insert(V);let X=XV({body:Z,type:J,gid:I,pid:W});return this.upsertRaw(Q,X,$)}async delete(V){return this.upsertRaw(V,void 0,!0)}async genEID(V){let{clock:$,crypto:Q}=this,Z=$.now();if(V!==void 0)return u0({id:V,ts:Z});let J=await Q.genRandomBytes(8);return u0({id:J,ts:Z})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:V,crypto:$,store:Q}=this,Z=await Q.seed.load();if(!Z)return 22;await this.drainApplyQueue();for(let[J,I]of V){let W=await Q.hosts.get(J);if(!W)continue;let Y={conn:I,store:Q,enclave:Z,host:W,crypto:$,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},X=await MQ(Y);if(X!==0)return console.error(`Failed to peek: ${X}`),X;this.xferState.emit();let G=await wQ(Y);if(G!==0)return console.error(`Failed to push: ${G}`),G;this.xferState.emit();let K=await zQ(Y,async()=>{await this.drainApplyQueue()});if(K!==0&&K!==15)return console.error(`Failed to pull: ${K}`),K;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async wipe(){this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush(),await this.store.wipe(),await this.state.clear(),this.lastProgress=n0,this.clientState.emit(),this.xferState.emit()}import=async(V,$)=>{let{crypto:Q,store:Z}=this,J=$?.onProgress,I=await Z.seed.load();if(!I)return 22;console.time("import: decoding file...");let W=await V.bytes(),[Y,X]=await WQ(W,Q,I);if(X!==0)return X;console.timeEnd("import: decoding file...");let G=0;while(G<Y.length){let K=0,N=0,M=G;for(let w=G;w<Y.length&&N<100&&K<102400;w++)K+=Y[w].head.len,N++,M=w+1;let z=Y.slice(G,M);console.time(`import: applying [${G}, ${M}]`);let U=await this.apply(z,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${G}, ${M}]`);for(let w=0;w<z.length;w++){let O=U[w];if(O!==0&&O!==15)console.warn(`failed to import msg ${G+w}: ${_[O]}`)}if(J)queueMicrotask(()=>J(M,Y.length,0));this.emitProgress({phase:"import",done:M,total:Y.length}),G=M}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:V,store:$}=this,Q=await $.seed.load();if(!Q)return R(22);let Z=await $.messages.list();return IQ("export",0,Z,V,Q)}async export(V){let[$,Q]=await this.exportBytes();if(Q!==0)return Q;if(!$)return 12;let Z=new Blob([$.slice()]);return qV(Z,V),0}async link(V,$=!0){if(await this.store.hosts.add(V),this.clientState.emit(),$){let Q=await this.store.hosts.get(V.label);if(Q)await this.connectToHost(Q)}}async unlink(V){await this.store.hosts.del(V),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async(V,$=!0,Q=!0)=>{let{clock:Z,connections:J,crypto:I,store:W,transport:Y}=this,X=J.get(V.label);if(X){if(X.isConnected())return;try{X.closeListener()}catch{}J.delete(V.label)}let G=await W.seed.load();if(!G)return;console.info(`Connecting to ${V.handle} (${V.label})`);let K=new UV(G,I,V,Z,Y(V),(N)=>W.hosts.set(V.label,N));if(await K.register(),$)await K.listen(async(N)=>{let M={conn:K,store:W,enclave:G,host:V,crypto:I,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return FQ(N,M,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(J.set(V.label,K),this.clientState.emit(),Q)this.scheduleSync()};async connect(V=!0,$=!0){let{connectToHost:Q,scheduleSync:Z,store:J}=this;if(!await J.seed.load())return;await this.drainApplyQueue();let W=await J.hosts.list();for(let Y of W)await Q(Y,V,!1);if($)Z()}disconnect=async()=>{for(let V of this.connections.values())try{V.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var j0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function HV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function I$(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function r(V,...$){if(!I$(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function W$(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function PQ(V,$){r(V);let Q=$.outputLen;if(V.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function Y$(V){if(typeof V!=="boolean")throw Error(`boolean expected, not ${V}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var z0=(V)=>new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4));var EZ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!EZ)throw Error("Non little-endian hardware is not supported");function xZ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function CV(V){if(typeof V==="string")V=xZ(V);else if(I$(V))V=DV(V);else throw Error("Uint8Array expected, got "+typeof V);return V}function OQ(V,$){if($==null||typeof $!=="object")throw Error("options must be defined");return Object.assign(V,$)}function qQ(V,$){if(V.length!==$.length)return!1;let Q=0;for(let Z=0;Z<V.length;Z++)Q|=V[Z]^$[Z];return Q===0}var HQ=(V,$)=>{function Q(Z,...J){if(r(Z),V.nonceLength!==void 0){let K=J[0];if(!K)throw Error("nonce / iv required");if(V.varSizeNonce)r(K);else r(K,V.nonceLength)}let I=V.tagLength;if(I&&J[1]!==void 0)r(J[1]);let W=$(Z,...J),Y=(K,N)=>{if(N!==void 0){if(K!==2)throw Error("cipher output not supported");r(N)}},X=!1;return{encrypt(K,N){if(X)throw Error("cannot encrypt() twice with same key + nonce");return X=!0,r(K),Y(W.encrypt.length,N),W.encrypt(K,N)},decrypt(K,N){if(r(K),I&&K.length<I)throw Error("invalid ciphertext length: smaller than tagLength="+I);return Y(W.decrypt.length,N),W.decrypt(K,N)}}}return Object.assign(Q,V),Q};function X$(V,$,Q=!0){if($===void 0)return new Uint8Array(V);if($.length!==V)throw Error("invalid output length, expected "+V+", got: "+$.length);if(Q&&!kZ($))throw Error("invalid output, must be aligned");return $}function kZ(V){return V.byteOffset%4===0}function DV(V){return Uint8Array.from(V)}function K0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function TV(V=32){if(j0&&typeof j0.getRandomValues==="function")return j0.getRandomValues(new Uint8Array(V));if(j0&&typeof j0.randomBytes==="function")return j0.randomBytes(V);throw Error("crypto.getRandomValues must be defined")}var DQ=(V)=>Uint8Array.from(V.split("").map(($)=>$.charCodeAt(0))),fZ=DQ("expand 16-byte k"),BZ=DQ("expand 32-byte k"),gZ=z0(fZ),iZ=z0(BZ);function D(V,$){return V<<$|V>>>32-$}function G$(V){return V.byteOffset%4===0}var AV=64,vZ=16,TQ=4294967295,CQ=new Uint32Array;function uZ(V,$,Q,Z,J,I,W,Y){let X=J.length,G=new Uint8Array(AV),K=z0(G),N=G$(J)&&G$(I),M=N?z0(J):CQ,z=N?z0(I):CQ;for(let U=0;U<X;W++){if(V($,Q,Z,K,W,Y),W>=TQ)throw Error("arx: counter overflow");let w=Math.min(AV,X-U);if(N&&w===AV){let O=U/4;if(U%4!==0)throw Error("arx: invalid block position");for(let P=0,C;P<vZ;P++)C=O+P,z[C]=M[C]^K[P];U+=AV;continue}for(let O=0,P;O<w;O++)P=U+O,I[P]=J[P]^G[O];U+=w}}function AQ(V,$){let{allowShortKeys:Q,extendNonceFn:Z,counterLength:J,counterRight:I,rounds:W}=OQ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},$);if(typeof V!=="function")throw Error("core must be a function");return HV(J),HV(W),Y$(I),Y$(Q),(Y,X,G,K,N=0)=>{r(Y),r(X),r(G);let M=G.length;if(K===void 0)K=new Uint8Array(M);if(r(K),HV(N),N<0||N>=TQ)throw Error("arx: counter overflow");if(K.length<M)throw Error(`arx: output (${K.length}) is shorter than data (${M})`);let z=[],U=Y.length,w,O;if(U===32)z.push(w=DV(Y)),O=iZ;else if(U===16&&Q)w=new Uint8Array(32),w.set(Y),w.set(Y,16),O=gZ,z.push(w);else throw Error(`arx: invalid 32-byte key, got length=${U}`);if(!G$(X))z.push(X=DV(X));let P=z0(w);if(Z){if(X.length!==24)throw Error("arx: extended nonce must be 24 bytes");Z(O,P,z0(X.subarray(0,16)),P),X=X.subarray(16)}let C=16-J;if(C!==X.length)throw Error(`arx: nonce must be ${C} or 16 bytes`);if(C!==12){let F=new Uint8Array(12);F.set(X,I?0:12-X.length),X=F,z.push(X)}let A=z0(X);return uZ(V,O,P,A,G,K,N,W),K0(...z),K}}var c=(V,$)=>V[$++]&255|(V[$++]&255)<<8;class _Q{constructor(V){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,V=CV(V),r(V,32);let $=c(V,0),Q=c(V,2),Z=c(V,4),J=c(V,6),I=c(V,8),W=c(V,10),Y=c(V,12),X=c(V,14);this.r[0]=$&8191,this.r[1]=($>>>13|Q<<3)&8191,this.r[2]=(Q>>>10|Z<<6)&7939,this.r[3]=(Z>>>7|J<<9)&8191,this.r[4]=(J>>>4|I<<12)&255,this.r[5]=I>>>1&8190,this.r[6]=(I>>>14|W<<2)&8191,this.r[7]=(W>>>11|Y<<5)&8065,this.r[8]=(Y>>>8|X<<8)&8191,this.r[9]=X>>>5&127;for(let G=0;G<8;G++)this.pad[G]=c(V,16+2*G)}process(V,$,Q=!1){let Z=Q?0:2048,{h:J,r:I}=this,W=I[0],Y=I[1],X=I[2],G=I[3],K=I[4],N=I[5],M=I[6],z=I[7],U=I[8],w=I[9],O=c(V,$+0),P=c(V,$+2),C=c(V,$+4),A=c(V,$+6),F=c(V,$+8),T=c(V,$+10),L=c(V,$+12),E=c(V,$+14),S=J[0]+(O&8191),m=J[1]+((O>>>13|P<<3)&8191),f=J[2]+((P>>>10|C<<6)&8191),H=J[3]+((C>>>7|A<<9)&8191),g=J[4]+((A>>>4|F<<12)&8191),v=J[5]+(F>>>1&8191),y=J[6]+((F>>>14|T<<2)&8191),b=J[7]+((T>>>11|L<<5)&8191),p=J[8]+((L>>>8|E<<8)&8191),l=J[9]+(E>>>5|Z),j=0,d=j+S*W+m*(5*w)+f*(5*U)+H*(5*z)+g*(5*M);j=d>>>13,d&=8191,d+=v*(5*N)+y*(5*K)+b*(5*G)+p*(5*X)+l*(5*Y),j+=d>>>13,d&=8191;let a=j+S*Y+m*W+f*(5*w)+H*(5*U)+g*(5*z);j=a>>>13,a&=8191,a+=v*(5*M)+y*(5*N)+b*(5*K)+p*(5*G)+l*(5*X),j+=a>>>13,a&=8191;let $0=j+S*X+m*Y+f*W+H*(5*w)+g*(5*U);j=$0>>>13,$0&=8191,$0+=v*(5*z)+y*(5*M)+b*(5*N)+p*(5*K)+l*(5*G),j+=$0>>>13,$0&=8191;let i=j+S*G+m*X+f*Y+H*W+g*(5*w);j=i>>>13,i&=8191,i+=v*(5*U)+y*(5*z)+b*(5*M)+p*(5*N)+l*(5*K),j+=i>>>13,i&=8191;let M0=j+S*K+m*G+f*X+H*Y+g*W;j=M0>>>13,M0&=8191,M0+=v*(5*w)+y*(5*U)+b*(5*z)+p*(5*M)+l*(5*N),j+=M0>>>13,M0&=8191;let E0=j+S*N+m*K+f*G+H*X+g*Y;j=E0>>>13,E0&=8191,E0+=v*W+y*(5*w)+b*(5*U)+p*(5*z)+l*(5*M),j+=E0>>>13,E0&=8191;let x0=j+S*M+m*N+f*K+H*G+g*X;j=x0>>>13,x0&=8191,x0+=v*Y+y*W+b*(5*w)+p*(5*U)+l*(5*z),j+=x0>>>13,x0&=8191;let k0=j+S*z+m*M+f*N+H*K+g*G;j=k0>>>13,k0&=8191,k0+=v*X+y*Y+b*W+p*(5*w)+l*(5*U),j+=k0>>>13,k0&=8191;let f0=j+S*U+m*z+f*M+H*N+g*K;j=f0>>>13,f0&=8191,f0+=v*G+y*X+b*Y+p*W+l*(5*w),j+=f0>>>13,f0&=8191;let B0=j+S*w+m*U+f*z+H*M+g*N;j=B0>>>13,B0&=8191,B0+=v*K+y*G+b*X+p*Y+l*W,j+=B0>>>13,B0&=8191,j=(j<<2)+j|0,j=j+d|0,d=j&8191,j=j>>>13,a+=j,J[0]=d,J[1]=a,J[2]=$0,J[3]=i,J[4]=M0,J[5]=E0,J[6]=x0,J[7]=k0,J[8]=f0,J[9]=B0}finalize(){let{h:V,pad:$}=this,Q=new Uint16Array(10),Z=V[1]>>>13;V[1]&=8191;for(let W=2;W<10;W++)V[W]+=Z,Z=V[W]>>>13,V[W]&=8191;V[0]+=Z*5,Z=V[0]>>>13,V[0]&=8191,V[1]+=Z,Z=V[1]>>>13,V[1]&=8191,V[2]+=Z,Q[0]=V[0]+5,Z=Q[0]>>>13,Q[0]&=8191;for(let W=1;W<10;W++)Q[W]=V[W]+Z,Z=Q[W]>>>13,Q[W]&=8191;Q[9]-=8192;let J=(Z^1)-1;for(let W=0;W<10;W++)Q[W]&=J;J=~J;for(let W=0;W<10;W++)V[W]=V[W]&J|Q[W];V[0]=(V[0]|V[1]<<13)&65535,V[1]=(V[1]>>>3|V[2]<<10)&65535,V[2]=(V[2]>>>6|V[3]<<7)&65535,V[3]=(V[3]>>>9|V[4]<<4)&65535,V[4]=(V[4]>>>12|V[5]<<1|V[6]<<14)&65535,V[5]=(V[6]>>>2|V[7]<<11)&65535,V[6]=(V[7]>>>5|V[8]<<8)&65535,V[7]=(V[8]>>>8|V[9]<<5)&65535;let I=V[0]+$[0];V[0]=I&65535;for(let W=1;W<8;W++)I=(V[W]+$[W]|0)+(I>>>16)|0,V[W]=I&65535;K0(Q)}update(V){W$(this);let{buffer:$,blockLen:Q}=this;V=CV(V);let Z=V.length;for(let J=0;J<Z;){let I=Math.min(Q-this.pos,Z-J);if(I===Q){for(;Q<=Z-J;J+=Q)this.process(V,J);continue}if($.set(V.subarray(J,J+I),this.pos),this.pos+=I,J+=I,this.pos===Q)this.process($,0,!1),this.pos=0}return this}destroy(){K0(this.h,this.r,this.buffer,this.pad)}digestInto(V){W$(this),PQ(V,this),this.finished=!0;let{buffer:$,h:Q}=this,{pos:Z}=this;if(Z){$[Z++]=1;for(;Z<16;Z++)$[Z]=0;this.process($,0,!0)}this.finalize();let J=0;for(let I=0;I<8;I++)V[J++]=Q[I]>>>0,V[J++]=Q[I]>>>8;return V}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Q=V.slice(0,$);return this.destroy(),Q}}function nZ(V){let $=(Z,J)=>V(J).update(CV(Z)).digest(),Q=V(new Uint8Array(32));return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=(Z)=>V(Z),$}var K$=nZ((V)=>new _Q(V));function yZ(V,$,Q,Z,J,I=20){let W=V[0],Y=$[0],X=$[1],G=$[2],K=$[3],N=V[1],M=Q[0],z=Q[1],U=J,w=0,O=V[2],P=$[4],C=$[5],A=$[6],F=$[7],T=V[3],L=W,E=Y,S=X,m=G,f=K,H=N,g=M,v=z,y=U,b=w,p=O,l=P,j=C,d=A,a=F,$0=T;for(let M0=0;M0<I;M0+=2)f^=D(L+j|0,7),y^=D(f+L|0,9),j^=D(y+f|0,13),L^=D(j+y|0,18),b^=D(H+E|0,7),d^=D(b+H|0,9),E^=D(d+b|0,13),H^=D(E+d|0,18),a^=D(p+g|0,7),S^=D(a+p|0,9),g^=D(S+a|0,13),p^=D(g+S|0,18),m^=D($0+l|0,7),v^=D(m+$0|0,9),l^=D(v+m|0,13),$0^=D(l+v|0,18),E^=D(L+m|0,7),S^=D(E+L|0,9),m^=D(S+E|0,13),L^=D(m+S|0,18),g^=D(H+f|0,7),v^=D(g+H|0,9),f^=D(v+g|0,13),H^=D(f+v|0,18),l^=D(p+b|0,7),y^=D(l+p|0,9),b^=D(y+l|0,13),p^=D(b+y|0,18),j^=D($0+a|0,7),d^=D(j+$0|0,9),a^=D(d+j|0,13),$0^=D(a+d|0,18);let i=0;Z[i++]=W+L|0,Z[i++]=Y+E|0,Z[i++]=X+S|0,Z[i++]=G+m|0,Z[i++]=K+f|0,Z[i++]=N+H|0,Z[i++]=M+g|0,Z[i++]=z+v|0,Z[i++]=U+y|0,Z[i++]=w+b|0,Z[i++]=O+p|0,Z[i++]=P+l|0,Z[i++]=C+j|0,Z[i++]=A+d|0,Z[i++]=F+a|0,Z[i++]=T+$0|0}function bZ(V,$,Q,Z){let J=V[0],I=$[0],W=$[1],Y=$[2],X=$[3],G=V[1],K=Q[0],N=Q[1],M=Q[2],z=Q[3],U=V[2],w=$[4],O=$[5],P=$[6],C=$[7],A=V[3];for(let T=0;T<20;T+=2)X^=D(J+O|0,7),M^=D(X+J|0,9),O^=D(M+X|0,13),J^=D(O+M|0,18),z^=D(G+I|0,7),P^=D(z+G|0,9),I^=D(P+z|0,13),G^=D(I+P|0,18),C^=D(U+K|0,7),W^=D(C+U|0,9),K^=D(W+C|0,13),U^=D(K+W|0,18),Y^=D(A+w|0,7),N^=D(Y+A|0,9),w^=D(N+Y|0,13),A^=D(w+N|0,18),I^=D(J+Y|0,7),W^=D(I+J|0,9),Y^=D(W+I|0,13),J^=D(Y+W|0,18),K^=D(G+X|0,7),N^=D(K+G|0,9),X^=D(N+K|0,13),G^=D(X+N|0,18),w^=D(U+z|0,7),M^=D(w+U|0,9),z^=D(M+w|0,13),U^=D(z+M|0,18),O^=D(A+C|0,7),P^=D(O+A|0,9),C^=D(P+O|0,13),A^=D(C+P|0,18);let F=0;Z[F++]=J,Z[F++]=G,Z[F++]=U,Z[F++]=A,Z[F++]=K,Z[F++]=N,Z[F++]=M,Z[F++]=z}var R$=AQ(yZ,{counterRight:!0,extendNonceFn:bZ}),N$=HQ({blockSize:64,nonceLength:24,tagLength:16},(V,$)=>{return{encrypt(Q,Z){Z=X$(Q.length+32,Z,!1);let J=Z.subarray(0,32),I=Z.subarray(32);Z.set(Q,32),K0(J),R$(V,$,Z,Z);let W=K$(I,J);return Z.set(W,16),K0(Z.subarray(0,16),W),Z.subarray(16)},decrypt(Q,Z){r(Q),Z=X$(Q.length+32,Z,!1);let J=Z.subarray(0,32),I=Z.subarray(32,48),W=Z.subarray(48);Z.set(Q,32),K0(J);let Y=R$(V,$,J,J),X=K$(W,Y);if(!qQ(I,X))throw Error("invalid tag");return R$(V,$,Z.subarray(16),Z.subarray(16)),K0(J,I,X),W}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function pZ(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function $V(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function L0(V,...$){if(!pZ(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function QV(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function _V(V,$){L0(V);let Q=$.outputLen;if(V.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function jQ(V){return new Uint8Array(V.buffer,V.byteOffset,V.byteLength)}function y0(V){return new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4))}function b0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function ZV(V,$){return V<<32-$|V>>>$}var LQ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function SQ(V){return V<<24&4278190080|V<<8&16711680|V>>>8&65280|V>>>24&255}var mQ=LQ?(V)=>V:(V)=>SQ(V);function lZ(V){for(let $=0;$<V.length;$++)V[$]=SQ(V[$]);return V}var e=LQ?(V)=>V:lZ;function rZ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function p0(V){if(typeof V==="string")V=rZ(V);return L0(V),V}class M${}function EQ(V){let $=(Z,J)=>V(J).update(p0(Z)).digest(),Q=V({});return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=(Z)=>V(Z),$}var xQ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var jV=BigInt(4294967295),kQ=BigInt(32);function w$(V,$=!1){if($)return{h:Number(V&jV),l:Number(V>>kQ&jV)};return{h:Number(V>>kQ&jV)|0,l:Number(V&jV)|0}}function U0(V,$,Q,Z,J){return V=V+$+J|0,Z=ZV(Z^V,16),Q=Q+Z|0,$=ZV($^Q,12),{a:V,b:$,c:Q,d:Z}}function F0(V,$,Q,Z,J){return V=V+$+J|0,Z=ZV(Z^V,8),Q=Q+Z|0,$=ZV($^Q,7),{a:V,b:$,c:Q,d:Z}}class z$ extends M${constructor(V,$){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,$V(V),$V($),this.blockLen=V,this.outputLen=$,this.buffer=new Uint8Array(V),this.buffer32=y0(this.buffer)}update(V){QV(this),V=p0(V),L0(V);let{blockLen:$,buffer:Q,buffer32:Z}=this,J=V.length,I=V.byteOffset,W=V.buffer;for(let Y=0;Y<J;){if(this.pos===$)e(Z),this.compress(Z,0,!1),e(Z),this.pos=0;let X=Math.min($-this.pos,J-Y),G=I+Y;if(X===$&&!(G%4)&&Y+X<J){let K=new Uint32Array(W,G,Math.floor((J-Y)/4));e(K);for(let N=0;Y+$<J;N+=Z.length,Y+=$)this.length+=$,this.compress(K,N,!1);e(K);continue}Q.set(V.subarray(Y,Y+X),this.pos),this.pos+=X,this.length+=X,Y+=X}return this}digestInto(V){QV(this),_V(V,this);let{pos:$,buffer32:Q}=this;this.finished=!0,b0(this.buffer.subarray($)),e(Q),this.compress(Q,0,!0),e(Q);let Z=y0(V);this.get().forEach((J,I)=>Z[I]=mQ(J))}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Q=V.slice(0,$);return this.destroy(),Q}_cloneInto(V){let{buffer:$,length:Q,finished:Z,destroyed:J,outputLen:I,pos:W}=this;return V||(V=new this.constructor({dkLen:I})),V.set(...this.get()),V.buffer.set($),V.destroyed=J,V.finished=Z,V.length=Q,V.pos=W,V.outputLen=I,V}clone(){return this._cloneInto()}}function U$(V,$,Q,Z,J,I,W,Y,X,G,K,N,M,z,U,w,O,P,C,A){let F=0;for(let T=0;T<Z;T++)({a:J,b:X,c:M,d:O}=U0(J,X,M,O,Q[$+V[F++]])),{a:J,b:X,c:M,d:O}=F0(J,X,M,O,Q[$+V[F++]]),{a:I,b:G,c:z,d:P}=U0(I,G,z,P,Q[$+V[F++]]),{a:I,b:G,c:z,d:P}=F0(I,G,z,P,Q[$+V[F++]]),{a:W,b:K,c:U,d:C}=U0(W,K,U,C,Q[$+V[F++]]),{a:W,b:K,c:U,d:C}=F0(W,K,U,C,Q[$+V[F++]]),{a:Y,b:N,c:w,d:A}=U0(Y,N,w,A,Q[$+V[F++]]),{a:Y,b:N,c:w,d:A}=F0(Y,N,w,A,Q[$+V[F++]]),{a:J,b:G,c:U,d:A}=U0(J,G,U,A,Q[$+V[F++]]),{a:J,b:G,c:U,d:A}=F0(J,G,U,A,Q[$+V[F++]]),{a:I,b:K,c:w,d:O}=U0(I,K,w,O,Q[$+V[F++]]),{a:I,b:K,c:w,d:O}=F0(I,K,w,O,Q[$+V[F++]]),{a:W,b:N,c:M,d:P}=U0(W,N,M,P,Q[$+V[F++]]),{a:W,b:N,c:M,d:P}=F0(W,N,M,P,Q[$+V[F++]]),{a:Y,b:X,c:z,d:C}=U0(Y,X,z,C,Q[$+V[F++]]),{a:Y,b:X,c:z,d:C}=F0(Y,X,z,C,Q[$+V[F++]]);return{v0:J,v1:I,v2:W,v3:Y,v4:X,v5:G,v6:K,v7:N,v8:M,v9:z,v10:U,v11:w,v12:O,v13:P,v14:C,v15:A}}var R0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},P0=xQ.slice(),fQ=(()=>{let V=Array.from({length:16},(Z,J)=>J),$=(Z)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((J)=>Z[J]),Q=[];for(let Z=0,J=V;Z<7;Z++,J=$(J))Q.push(...J);return Uint8Array.from(Q)})();class F$ extends z${constructor(V={},$=0){super(64,V.dkLen===void 0?32:V.dkLen);this.chunkPos=0,this.chunksDone=0,this.flags=0,this.stack=[],this.posOut=0,this.bufferOut32=new Uint32Array(16),this.chunkOut=0,this.enableXOF=!0;let{key:Q,context:Z}=V,J=Z!==void 0;if(Q!==void 0){if(J)throw Error('Only "key" or "context" can be specified at same time');let I=p0(Q).slice();L0(I,32),this.IV=y0(I),e(this.IV),this.flags=$|R0.KEYED_HASH}else if(J){let I=p0(Z),W=new F$({dkLen:32},R0.DERIVE_KEY_CONTEXT).update(I).digest();this.IV=y0(W),e(this.IV),this.flags=$|R0.DERIVE_KEY_MATERIAL}else this.IV=P0.slice(),this.flags=$;this.state=this.IV.slice(),this.bufferOut=jQ(this.bufferOut32)}get(){return[]}set(){}b2Compress(V,$,Q,Z=0){let{state:J,pos:I}=this,{h:W,l:Y}=w$(BigInt(V),!0),{v0:X,v1:G,v2:K,v3:N,v4:M,v5:z,v6:U,v7:w,v8:O,v9:P,v10:C,v11:A,v12:F,v13:T,v14:L,v15:E}=U$(fQ,Z,Q,7,J[0],J[1],J[2],J[3],J[4],J[5],J[6],J[7],P0[0],P0[1],P0[2],P0[3],W,Y,I,$);J[0]=X^O,J[1]=G^P,J[2]=K^C,J[3]=N^A,J[4]=M^F,J[5]=z^T,J[6]=U^L,J[7]=w^E}compress(V,$=0,Q=!1){let Z=this.flags;if(!this.chunkPos)Z|=R0.CHUNK_START;if(this.chunkPos===15||Q)Z|=R0.CHUNK_END;if(!Q)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,Z,V,$),this.chunkPos+=1,this.chunkPos===16||Q){let J=this.state;this.state=this.IV.slice();for(let I,W=this.chunksDone+1;Q||!(W&1);W>>=1){if(!(I=this.stack.pop()))break;this.buffer32.set(I,0),this.buffer32.set(J,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|R0.PARENT,this.buffer32,0),J=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(J)}this.pos=0}_cloneInto(V){V=super._cloneInto(V);let{IV:$,flags:Q,state:Z,chunkPos:J,posOut:I,chunkOut:W,stack:Y,chunksDone:X}=this;return V.state.set(Z.slice()),V.stack=Y.map((G)=>Uint32Array.from(G)),V.IV.set($),V.flags=Q,V.chunkPos=J,V.chunksDone=X,V.posOut=I,V.chunkOut=W,V.enableXOF=this.enableXOF,V.bufferOut32.set(this.bufferOut32),V}destroy(){this.destroyed=!0,b0(this.state,this.buffer32,this.IV,this.bufferOut32),b0(...this.stack)}b2CompressOut(){let{state:V,pos:$,flags:Q,buffer32:Z,bufferOut32:J}=this,{h:I,l:W}=w$(BigInt(this.chunkOut++));e(Z);let{v0:Y,v1:X,v2:G,v3:K,v4:N,v5:M,v6:z,v7:U,v8:w,v9:O,v10:P,v11:C,v12:A,v13:F,v14:T,v15:L}=U$(fQ,0,Z,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],P0[0],P0[1],P0[2],P0[3],W,I,$,Q);J[0]=Y^w,J[1]=X^O,J[2]=G^P,J[3]=K^C,J[4]=N^A,J[5]=M^F,J[6]=z^T,J[7]=U^L,J[8]=V[0]^w,J[9]=V[1]^O,J[10]=V[2]^P,J[11]=V[3]^C,J[12]=V[4]^A,J[13]=V[5]^F,J[14]=V[6]^T,J[15]=V[7]^L,e(Z),e(J),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,b0(this.buffer.subarray(this.pos));let V=this.flags|R0.ROOT;if(this.stack.length)V|=R0.PARENT,e(this.buffer32),this.compress(this.buffer32,0,!0),e(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else V|=(!this.chunkPos?R0.CHUNK_START:0)|R0.CHUNK_END;this.flags=V,this.b2CompressOut()}writeInto(V){QV(this,!1),L0(V),this.finish();let{blockLen:$,bufferOut:Q}=this;for(let Z=0,J=V.length;Z<J;){if(this.posOut>=$)this.b2CompressOut();let I=Math.min($-this.posOut,J-Z);V.set(Q.subarray(this.posOut,this.posOut+I),Z),this.posOut+=I,Z+=I}return V}xofInto(V){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(V)}xof(V){return $V(V),this.xofInto(new Uint8Array(V))}digestInto(V){if(_V(V,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto(V),this.destroy(),V}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var BQ=EQ((V)=>new F$(V));var P$=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function gQ(V){let $=new Uint8Array(P$.length+32);return $.set(P$),$.set(V.subarray(0,32),P$.length),$}function iQ(V){return typeof V==="string"?new TextEncoder().encode(V):V}function l0(V){let $=new ArrayBuffer(V.byteLength);return new Uint8Array($).set(V),$}class O${verifyKeys=new Map;signKeys=new Map;async genRandomBytes(V){return TV(V)}async gen256BitSecureRandomSeed(){return TV(32)}async encryptXSalsa20Poly1305Combined(V,$){let Q=TV(24),J=N$($,Q).encrypt(V);return new Uint8Array([...Q,...J])}async decryptXSalsa20Poly1305Combined(V,$){let Q=V.slice(0,24),Z=V.slice(24);return N$($,Q).decrypt(Z)}async deriveEd25519KeyPair(V){let $=V,Q=gQ($),Z=await globalThis.crypto.subtle.importKey("pkcs8",l0(Q),{name:"Ed25519"},!0,["sign"]),J=await globalThis.crypto.subtle.exportKey("jwk",Z);if(typeof J.x!=="string")throw Error("Ed25519 JWK missing x");let I=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:J.x},{name:"Ed25519"},!0,["verify"]),W=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",I)),Y=new Uint8Array(64);return Y.set($,0),Y.set(W,32),this.signKeys.set(o($),Z),this.verifyKeys.set(o(W),I),{keyType:"ed25519",privateKey:Y,publicKey:W}}async importSignKey(V){let $=V.subarray(0,32),Q=o($),Z=this.signKeys.get(Q);if(Z)return Z;let J=gQ($),I=await globalThis.crypto.subtle.importKey("pkcs8",l0(J),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Q,I),I}async importVerifyKey(V){let $=o(V),Q=this.verifyKeys.get($);if(Q)return Q;let Z=await globalThis.crypto.subtle.importKey("raw",l0(V),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set($,Z),Z}async signEd25519(V,$){let Q=iQ(V),Z=await this.importSignKey($),J=await globalThis.crypto.subtle.sign({name:"Ed25519"},Z,l0(Q));return new Uint8Array(J)}async checkSigEd25519(V,$,Q){let Z=iQ($);try{let J=await this.importVerifyKey(Q);return await globalThis.crypto.subtle.verify({name:"Ed25519"},J,l0(V),l0(Z))}catch{return!1}}async blake3(V){return BQ(V)}}var hZ=new O$,J0=hZ;var b8=Symbol("EntityID");function vQ(V){return"type"in V}var p8=Symbol("MasterSeed"),l8=Symbol("DerivationSeed"),r8=Symbol("PublicKey"),h8=Symbol("PrivateKey"),c8=Symbol("HostSpecificKeyPair"),d8=Symbol("Hash");function cZ(V){if(!V)return!1;if(typeof V!=="object")return!1;if("body"in V===!1)return!1;if("type"in V===!1)return!1;return!0}function dZ(V){if(!V.bod||V.bod.length===0){let Z={off:V.off,ctr:V.ctr,eid:V.eid};return q(Z)}let $=nV(V.bod);if(cZ($)===!1)return console.warn("msg body invalid",$),R(14);let Q={off:V.off,ctr:V.ctr,eid:V.eid,gid:$.gid,pid:$.pid,type:$.type,body:$.body};return q(Q)}class LV{applier;emitter=new H0;clearer;onTypes;constructor(V,$,Q){this.applier=V;this.clearer=$,this.onTypes=Q}apply=async(V)=>{let $=[],Q=[];for(let W of V){let[Y,X]=dZ(W);if(Q.push(X),X!==0)continue;$.push(Y)}let{stats:Z,types:J}=await this.applier($),I=[];for(let W=0;W<V.length;W++){let Y=Q[W],X=Z[W];if(Y!==0){I.push(Y);continue}if(X!==0){I.push(X);continue}I.push(0)}for(let W of J)this.emitter.emit(W,null);if(J.size>0)this.onTypes?.(J);return I};clear=async()=>{let V=await this.clearer();if(V!==0)return V;return this.emitter.emitAll(null),V};notify=(V)=>{for(let $ of V)this.emitter.emit($,null)};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}var q$={apply:async function(V){return V.map(()=>0)},clear:async function(){return 0},notify:function(V){},on:function(V,$){},off:function(V,$){}};function H$(V){return new LV(($)=>V.apply($),()=>V.clear())}function SV(V,$){let Q=new B($.eid),[Z,J]=Q.readStruct(t);if(J!==0)return R(J);let I=new Date(Z.ts.getTime()+$.off);if(V!==void 0&&I<=V.updatedAt)return R(15);if(vQ($))return q({eid:$.eid,gid:$.gid,pid:$.pid,type:$.type,createdAt:Z.ts,updatedAt:I,ctr:$.ctr,body:$.body});else return q(void 0)}var oZ={getEnt:async()=>R(21),getEntities:async(V)=>R(21),countEntities:async()=>R(21),apply:async(V)=>({stats:V.map(()=>21),types:new Set}),clear:async()=>21};var n="entities",mV="entity_type_created_at",C$="entity_type_updated_at",D$="entity_type_group_id",T$="entity_type_parent_id";function aZ(V){let $={bod:V.body,crd:V.createdAt,...V.ctr!==0?{ctr:V.ctr}:{},eid:k(V.eid),gid:V.gid,pid:V.pid?k(V.pid):void 0,typ:V.type,upd:V.updatedAt};if($.gid===void 0)delete $.gid;if($.pid===void 0)delete $.pid;if($.ctr===void 0)delete $.ctr;return $}function r0(V){return{body:V.bod,createdAt:V.crd,updatedAt:V.upd,ctr:V.ctr??0,type:V.typ,eid:Z0(V.eid),gid:V.gid,pid:V.pid?Z0(V.pid):void 0}}class A${db;async init(){this.db=await new Promise((V,$)=>{let Q=indexedDB.open("db",11);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!J)throw Error("Transaction is null during upgrade");if(!Z.objectStoreNames.contains(n))Z.createObjectStore(n,{keyPath:"eid",autoIncrement:!1});let I=J.objectStore(n);if(!I.indexNames.contains(mV))I.createIndex(mV,["typ","crd"],{unique:!1});if(!I.indexNames.contains(C$))I.createIndex(C$,["typ","upd"],{unique:!1});if(!I.indexNames.contains(D$))I.createIndex(D$,["typ","gid"],{unique:!1});if(!I.indexNames.contains(T$))I.createIndex(T$,["typ","pid"],{unique:!1})},Q.onsuccess=()=>V(Q.result),Q.onerror=()=>$(Q.error)})}apply=async(V)=>{let $=new Set;if(!this.db)return{stats:V.map(()=>16),types:$};let Q=this.db.transaction(n,"readwrite"),Z=Q.objectStore(n);return new Promise((J)=>{let I=Array(V.length).fill(0);if(V.length<1){J({stats:[],types:$});return}Q.oncomplete=()=>{J({stats:I,types:$})},Q.onerror=()=>{for(let Y=0;Y<I.length;Y++)if(I[Y]===void 0)I[Y]=18;J({stats:I,types:$})};let W=new Map;for(let Y=0;Y<V.length;Y++){let X=V[Y],G=k(X.eid),K={op:X,index:Y},N=W.get(G);if(N)N.push(K);else W.set(G,[K])}for(let[Y,X]of W){if(X.length<1)continue;let G=Z.get(Y);G.onsuccess=()=>{let K=G.result,N=K?r0(K):void 0;for(let{op:M,index:z}of X){let[U,w]=SV(N,M);if(w!==0){I[z]=w;continue}if(U)$.add(U.type);else if(N)$.add(N.type);N=U}if(N){let M=aZ(N),z=Z.put(M);z.onerror=(U)=>{U.preventDefault();for(let{index:w}of X)I[w]=18}}else{let M=Z.delete(Y);M.onerror=()=>{for(let{index:z}of X)I[z]=18}}},G.onerror=()=>{for(let{index:K}of X)I[K]=18}}})};async clear(){if(!this.db)return 16;let V=this.db.transaction(n,"readwrite"),$=V.objectStore(n);return new Promise((Q)=>{V.oncomplete=()=>Q(0),V.onerror=()=>Q(18),$.clear()})}async getEnt(V){if(!this.db)return R(16);let $=k(V),Z=this.db.transaction(n,"readonly").objectStore(n);return new Promise((J)=>{let I=Z.get($);I.onsuccess=()=>{let W=I.result;if(!W)J(q(void 0));else{let Y=r0(W);J(q(Y))}},I.onerror=()=>J(R(18))})}async getAllOfTypeUpdatedBetween(V,$,Q){if(!this.db)return R(16);let J=this.db.transaction(n,"readonly").objectStore(n).index(C$);return new Promise((I)=>{let W=J.getAll(IDBKeyRange.bound([V,$],[V,Q]));W.onsuccess=()=>{let Y=W.result;I(q(Y.map(r0)))},W.onerror=()=>I(R(18))})}async getGroupMembers(V,$){if(!this.db)return R(16);let Z=this.db.transaction(n,"readonly").objectStore(n).index(D$);return new Promise((J)=>{let I=Z.getAll(IDBKeyRange.only([V,$]));I.onsuccess=()=>{let W=I.result;J(q(W.map(r0)))},I.onerror=()=>J(R(18))})}async getAllOfType(V){if(!this.db)return R(16);let Q=this.db.transaction(n,"readonly").objectStore(n).index(mV);return new Promise((Z)=>{let J=Q.getAll(IDBKeyRange.bound([V],[V,[]]));J.onsuccess=()=>{let I=J.result;Z(q(I.map(r0)))},J.onerror=()=>Z(R(18))})}async getAllEntities(V){if(!this.db)return R(16);if("pid"in V){let $=k(V.pid),Z=this.db.transaction(n,"readonly").objectStore(n).index(T$);return new Promise((J)=>{let I=Z.getAll(IDBKeyRange.only([V.type,$]));I.onsuccess=()=>{let Y=I.result.map(r0);J(q(Y))},I.onerror=()=>J(R(18))})}else if("gid"in V)return await this.getGroupMembers(V.type,V.gid);else if("updatedBetween"in V)return await this.getAllOfTypeUpdatedBetween(V.type,V.updatedBetween.start,V.updatedBetween.end);return await this.getAllOfType(V.type)}async getEntities(V){let[$,Q]=await this.getAllEntities(V);if(Q!==0)return R(Q);return q($)}async countEntities({type:V}){if(!this.db)return R(16);let Q=this.db.transaction(n,"readonly").objectStore(n).index(mV);return new Promise((Z)=>{let J=IDBKeyRange.bound([V],[V,[]]),I=Q.count(J);I.onsuccess=()=>Z(q(I.result)),I.onerror=()=>Z(R(18))})}}async function _$(){let V=new A$;return await V.init(),V}class uQ{ents=new Map;constructor(V=[]){for(let $ of V){let Q=k($.eid);this.ents.set(Q,$)}}async apply(V){let $=new Set,Q=[];for(let Z of V){let J=k(Z.eid),I=this.ents.get(J),[W,Y]=SV(I,Z);if(Y!==0){Q.push(Y);continue}if(W)$.add(W.type);else if(I)$.add(I.type);if(W)this.ents.set(J,W);else this.ents.delete(J);Q.push(0)}return{stats:Q,types:$}}async clear(){return this.ents.clear(),0}async getEnt(V){let $=k(V),Q=this.ents.get($);return q(Q)}async getAllEntities({type:V,gid:$,pid:Q,updatedBetween:Z}){let J=[];if(Q!==void 0){for(let I of this.ents.values())if(I.type===V&&I.pid&&X0(I.pid,Q))J.push(I)}else if($!==void 0){for(let I of this.ents.values())if(I.type===V&&(typeof I.gid==="string"&&I.gid===$))J.push(I)}else if(Z!==void 0){for(let I of this.ents.values())if(I.type===V&&I.updatedAt>=Z.start&&I.updatedAt<=Z.end)J.push(I)}else for(let I of this.ents.values())if(I.type===V)J.push(I);return q(J)}async getEntities(V){let[$,Q]=await this.getAllEntities(V);if(Q!==0)return R(Q);return q($)}async countEntities({type:V}){let $=0;for(let Q of this.ents.values())if(Q.type===V)$+=1;return q($)}}import{useEffect as BV,useState as f$}from"react";class j${db;constructor(V){this.db=V}async enq(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(I0,"readwrite"),Z=Q.objectStore(I0);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=`${W.host}:${W.seq}`;Z.put(W,Y)}})}async deq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(I0,"readwrite"),J=Z.objectStore(I0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=`${V}:${Y}`;J.delete(X)}})}async list(){let $=this.db.transaction(I0,"readonly").objectStore(I0);return new Promise((Q,Z)=>{let J=$.getAll();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async count(){let $=this.db.transaction(I0,"readonly").objectStore(I0);return new Promise((Q,Z)=>{let J=$.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(I0,"readwrite"),$=V.objectStore(I0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}function nQ(V){return{label:V.label,handle:new URL(V.handle),idx:V.idx,lastSeq:V.lastSeq||0,clockOffset:V.clockOffset,subscription:V.subscription}}class L${db;constructor(V){this.db=V}async add(V){return this.put(V)}async put(V){let $={...V,handle:V.handle.toString(),lastSeq:V.lastSeq??0},Q=this.db.transaction(V0,"readwrite"),Z=Q.objectStore(V0);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error),Z.put($)})}async touch(V,$){let Q=this.db.transaction(V0,"readwrite"),Z=Q.objectStore(V0);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);let W=Z.get(V);W.onsuccess=()=>{let Y=W.result;if(!Y)return;let X=Y.lastSeq||0;if($<=X)return;Z.put({...Y,lastSeq:$})}})}async get(V){let Q=this.db.transaction(V0,"readonly").objectStore(V0);return new Promise((Z,J)=>{let I=Q.get(V);I.onsuccess=()=>{let W=I.result;if(!W)Z(void 0);else Z(nQ(W))},I.onerror=()=>J(I.error)})}async set(V,$){let Q=await this.get(V);if(!Q)return 13;try{return await this.put({...Q,...$}),0}catch{return 18}}async del(V){let $=this.db.transaction(V0,"readwrite"),Q=$.objectStore(V0);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),Q.delete(V)})}async list(){let $=this.db.transaction(V0,"readonly").objectStore(V0);return new Promise((Q,Z)=>{let J=$.getAll();J.onsuccess=()=>{let I=J.result;Q(I.map(nQ))},J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(V0,"readwrite"),$=V.objectStore(V0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}function sZ(V){return V===!0||V==="t"}function S0(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld===void 0?!1:sZ(V.apld)}}function S$(V){return S0(V).apld===!1}async function N0(V,$,Q){let Z=S0($),J=Z.body?.length??0,I;if(Z.body&&J>0)I=await Q.blake3(Z.body);let W={eid:Z.eid,off:Z.off??0,ctr:Z.ctr??0,len:J,hsh:I};return{hash:V,head:W,body:Z.body,applied:Z.apld}}function yQ(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld?"t":"f"}}class m${crypto;db;constructor(V,$){this.crypto=$;this.db=V}async add(V){let $=this.db.transaction(u,"readwrite"),Q=$.objectStore(u);return new Promise((Z)=>{if(V.length===0){Z([]);return}let J=Array(V.length).fill(0);$.oncomplete=()=>Z(J),$.onerror=()=>{for(let I=0;I<J.length;I++)J[I]=18;Z(J)};for(let I=0;I<V.length;I++){let{key:W,data:Y}=V[I],X=k(W),G=Q.put(yQ(Y),X);G.onerror=(K)=>{K.preventDefault(),J[I]=18}}})}async del(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=k(W);Z.delete(Y)}})}async get(V){let[$]=await this.getMany([V]);return $}async getMany(V){let $=[...V];if($.length<1)return[];let Z=this.db.transaction(u,"readonly").objectStore(u);return new Promise((J,I)=>{let W=Array($.length),Y=$.length,X=!1,G=async()=>{try{let K=[];for(let N=0;N<$.length;N++){let M=W[N];if(M)K.push(await N0($[N],M,this.crypto));else K.push(void 0)}J(K)}catch(K){I(K)}};for(let K=0;K<$.length;K++){let N=K,M=Z.get(k($[K]));M.onsuccess=()=>{if(X)return;if(W[N]=M.result,Y-=1,Y===0)G()},M.onerror=()=>{if(X)return;X=!0,I(M.error)}}})}async has(V){return await this.get(V)!==void 0}async list(){let $=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Q,Z)=>{let J=[],I=$.openCursor();I.onsuccess=async(W)=>{let Y=W.target.result;if(Y){let{key:X,value:G}=Y,K=Z0(X),N=await N0(K,G,this.crypto);J.push(N),Y.continue()}else Q(J)},I.onerror=()=>Z(I.error)})}async last(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let I,W=Q.openCursor();W.onsuccess=async(Y)=>{let X=Y.target.result;if(X){let{key:G,value:K}=X;if(X0(V,K.eid)){if(!I||(K.ctr??0)>(I.data.ctr??0)||(K.ctr??0)===(I.data.ctr??0)&&(K.off??0)>(I.data.off??0))I={key:G,data:K}}X.continue()}else if(I){let G=Z0(I.key);Z(await N0(G,I.data,this.crypto))}else Z(void 0)},W.onerror=()=>J(W.error)})}async listUnapplied(){let Q=this.db.transaction(u,"readonly").objectStore(u).index(EV);return new Promise((Z,J)=>{let I=[],W=Q.openCursor(IDBKeyRange.only("f"));W.onsuccess=(Y)=>{let X=Y.target.result;if(X){let{primaryKey:G,value:K}=X;I.push({hash:Z0(G),data:K}),X.continue()}else Promise.all(I.map(({hash:G,data:K})=>N0(G,K,this.crypto))).then(Z).catch(J)},W.onerror=()=>J(W.error)})}async markApplied(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=k(W),X=Z.get(Y);X.onsuccess=()=>{let G=X.result;if(!G)return;let K=S0(G);Z.put(yQ({...K,apld:!0}),Y)},X.onerror=(G)=>{G.preventDefault()}}})}async wipe(){let V=this.db.transaction(u,"readwrite"),$=V.objectStore(u);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}class h0{seed;crypto;constructor(V,$){this.seed=V,this.crypto=$}async deriveFromKDM(V){let $=a0(this.seed,V);return await this.crypto.blake3($)}async derive(V,$=0){let Q=new TextEncoder().encode(V),Z=new Uint8Array(8);new DataView(Z.buffer).setBigUint64(0,BigInt($),!1);let J=a0(Q,Z);return await this.deriveFromKDM(J)}}class E${enclave;db;constructor(V){this.db=V}async save(V){let $=o(V),Q=this.db.transaction(O0,"readwrite"),Z=Q.objectStore(O0);return new Promise((J,I)=>{Q.oncomplete=()=>{this.enclave=new h0(V,J0),J(this.enclave)},Q.onerror=()=>I(Q.error),Z.put($,"seed")})}async load(){if(this.enclave)return this.enclave;let $=this.db.transaction(O0,"readonly").objectStore(O0);return new Promise((Q,Z)=>{let J=$.get("seed");J.onsuccess=()=>{let I=J.result;if(!I)Q(void 0);else{let W=A0(I);this.enclave=new h0(W,J0),Q(this.enclave)}},J.onerror=()=>Z(J.error)})}async wipe(){this.enclave=void 0;let V=this.db.transaction(O0,"readwrite"),$=V.objectStore(O0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.delete("seed")})}}class x${db;constructor(V){this.db=V}async enq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=o(Y.hash);J.put({host:V,hash:X,bodyLen:Y.bodyLen})}})}async deq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=o(Y);J.delete([V,X])}})}async list(V){let Q=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Z,J)=>{let I=Q.getAll();I.onsuccess=()=>{let W=I.result,Y=[];for(let X of W){if(X.host!==V)continue;Y.push({hash:A0(X.hash),bodyLen:X.bodyLen??0})}Z(Y)},I.onerror=()=>J(I.error)})}async count(){let $=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Q,Z)=>{let J=$.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(W0,"readwrite"),$=V.objectStore(W0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}var O0="seedMeta",V0="hosts",W0="uploadQueue",I0="downloadQueue",u="messages",EV="apld",tZ=3;class k${seed;hosts;uploads;downloads;messages;db;constructor(V,$){this.db=V,this.seed=new E$(V),this.hosts=new L$(V),this.uploads=new x$(V),this.downloads=new j$(V),this.messages=new m$(V,$)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function eZ(){return new Promise((V,$)=>{let Q=indexedDB.open("diplomatic-store-db",tZ);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!Z.objectStoreNames.contains(O0))Z.createObjectStore(O0);if(!Z.objectStoreNames.contains(V0))Z.createObjectStore(V0,{keyPath:"label"});if(!Z.objectStoreNames.contains(W0))Z.createObjectStore(W0,{keyPath:["host","hash"]});if(!Z.objectStoreNames.contains(I0))Z.createObjectStore(I0);let I;if(!Z.objectStoreNames.contains(u))I=Z.createObjectStore(u);else{if(!J)throw Error("missing upgrade transaction for messages store");I=J.objectStore(u)}if(!I.indexNames.contains(EV))I.createIndex(EV,"apld",{unique:!1})},Q.onsuccess=()=>V(Q.result),Q.onerror=()=>$(Q.error)})}async function xV(V){let $=await eZ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new k$($,V)}function bQ(V){if(!V||typeof V!=="object")return!1;if(!("kind"in V))return!1;return typeof V.kind==="string"}function pQ(V){if(typeof V!=="number")return;return V}var q0="[DIPLOMATIC]";class JV{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:n0};clientState;xferState;constructor(V,$,Q,Z,J){this.worker=V,this.state=$,this.clientState=new G0(async()=>this.cachedClientState),this.xferState=new G0(async()=>this.cachedXferState),this.scheduledSync=new t0(J,async()=>{try{await this.request({id:this.allocId(),op:"sync"})}catch(I){console.error(`${q0} worker sync after local write failed`,I)}}),this.local=new _0(Z,$,Q,()=>{throw Error(`${q0} local writer has no transport (use worker for network)`)},J0,!0,void 0,void 0,()=>{this.scheduledSync.schedule()}),this.ready=new Promise((I,W)=>{this.resolveReady=I,this.rejectReady=W}),this.worker.onmessage=(I)=>{this.onMessage(I.data)},this.worker.onerror=(I)=>{console.error(`${q0} worker error`,I),this.failReady(Error(`${q0} worker failed to load`))},this.worker.onmessageerror=()=>{this.failReady(Error(`${q0} worker message error`))}}failReady(V){let $=this.rejectReady;if(this.rejectReady=void 0,this.resolveReady=void 0,$)$(V)}async flushScheduledSync(){await this.scheduledSync.flush()}static async connect(V,$,Q){let Z=Q.clock??new w0,J=Q.syncDebounceMs??OV,I=new JV(Q.worker,V,$,Z,J),W=Q.readyTimeoutMs??15000,Y;try{let X=I.probeReady();await Promise.race([I.ready,X,new Promise((G,K)=>{Y=setTimeout(()=>{K(Error(`${q0} worker ready timeout after ${W}ms`))},W)})]),X.catch(()=>{})}catch(X){throw I.terminate(),X}finally{if(Y!==void 0)clearTimeout(Y)}return I}markReady(){let V=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V()}probeReady(){return new Promise((V,$)=>{let Q=this.allocId();this.pending.set(Q,{resolve:(Z)=>{if(Z==="pong"){this.markReady(),V();return}$(Error(`${q0} worker probe ping failed`))},reject:$}),this.worker.postMessage({id:Q,op:"ping"})})}async ping(){if(await this.ready,await this.request({id:this.allocId(),op:"ping"})!=="pong")throw Error(`${q0} worker ping failed`)}terminate(){this.scheduledSync.cancel(),this.worker.terminate();for(let[,V]of this.pending)V.reject(Error(`${q0} worker terminated`));this.pending.clear()}onMessage(V){if(!bQ(V))return;let $=V;switch($.kind){case"ready":{this.markReady();return}case"clientState":{this.cachedClientState=$.state,this.clientState.emit();return}case"xferState":{this.cachedXferState=$.state,this.xferState.emit();return}case"dirty":{this.state.notify($.types);return}case"wiped":{this.state.clear();return}case"reply":{let Q=this.pending.get($.id);if(!Q)return;if(this.pending.delete($.id),$.ok)Q.resolve($.result);else Q.reject(new kV($.status));return}default:return}}allocId(){let V=this.nextId;return this.nextId+=1,V}request(V,$){return new Promise((Q,Z)=>{if(this.pending.set(V.id,{resolve:Q,reject:Z}),$&&$.length>0)this.worker.postMessage(V,$);else this.worker.postMessage(V)})}async requestStatus(V,$){try{let Q=await this.request(V,$),Z=pQ(Q);if(Z!==void 0)return Z;return 0}catch(Q){if(Q instanceof kV)return Q.status;return 12}}serializeHost(V){return{handle:V.handle.href,label:V.label,idx:V.idx??0}}async setSeed(V){await this.ready,await this.local.setSeed(V);let $=V.slice();await this.request({id:this.allocId(),op:"setSeed",seed:$},[$.buffer])}async link(V,$=!0){await this.ready,await this.local.link(V,!1),await this.request({id:this.allocId(),op:"link",host:this.serializeHost(V),connect:$})}async unlink(V){await this.ready,await this.local.unlink(V),await this.request({id:this.allocId(),op:"unlink",label:V})}async hosts(){return await this.ready,this.local.hosts()}async connect(V=!0,$=!0){await this.ready,await this.request({id:this.allocId(),op:"connect",listen:V,sync:$})}async disconnect(){await this.ready,await this.request({id:this.allocId(),op:"disconnect"})}async insertRaw(V){return await this.ready,this.local.insertRaw(V)}async upsertRaw(V,$,Q){return await this.ready,this.local.upsertRaw(V,$,Q)}async insert(V){return await this.ready,this.local.insert(V)}async upsert(V,$){return await this.ready,this.local.upsert(V,$)}async delete(V){return await this.ready,this.local.delete(V)}async genEID(V){return await this.ready,this.local.genEID(V)}async sync(){return await this.ready,this.requestStatus({id:this.allocId(),op:"sync"})}async wipe(){await this.ready,await this.request({id:this.allocId(),op:"wipe"})}async import(V){await this.ready;let $=new Uint8Array(await V.arrayBuffer());return this.requestStatus({id:this.allocId(),op:"import",bytes:$},[$.buffer])}async export(V,$){await this.ready;try{let Q=await this.request({id:this.allocId(),op:"export"});if(!(Q instanceof Uint8Array))return 12;let Z=new Blob([Q.slice()]);return qV(Z,V),0}catch(Q){if(Q instanceof kV)return Q.status;return 12}}}class kV extends Error{status;constructor(V){super(`WorkerReplyError: ${_[V]}`);this.status=V;this.name="WorkerReplyError"}}var m0="[DIPLOMATIC]";async function fV(V){let $=V.clock??new w0;if(V.worker!==void 0&&VJ(V)!==void 0)throw Error(`${m0} worker path requires IndexedDB on both sides; do not pass store (got a custom store)`);if(V.worker===void 0){console.info(`${m0} sync on main thread `+"(no worker — app did not request a worker)");let J=await lQ(V.store);return $J($,V.state,J)}if(typeof Worker>"u")throw Error(`${m0} worker was provided but Worker API is unavailable`);let Q=await lQ(void 0);console.info(`${m0} attaching app-provided sync worker…`);let Z=await JV.connect(V.state,Q,{worker:V.worker,readyTimeoutMs:V.readyTimeoutMs,clock:$,syncDebounceMs:V.syncDebounceMs});return await Z.ping(),console.info(`${m0} sync worker active (network + EntDB writes off main; local mutates on main; dirty signals only)`),{client:Z,mode:"worker",dispose:()=>{console.info(`${m0} terminating sync worker`),Z.terminate()}}}function VJ(V){if("store"in V)return V.store;return}async function $J(V,$,Q){let Z=new _0(V,$,Q,zV,J0);return{client:Z,mode:"main",dispose:()=>{Z.disconnect()}}}async function lQ(V){if(V!==void 0)return V;if(typeof indexedDB>"u")throw Error(`${m0} IndexedDB is unavailable; pass store explicitly (e.g. new MemoryStore(crypto))`);return xV(J0)}function QJ(V){let[$,Q]=f$();return BV(()=>{async function Z(){let I=await V.clientState.get();Q(I)}let J=V.clientState.listen(Z);return Z(),()=>{J()}},[V]),$}function ZJ(V){let[$,Q]=f$();return BV(()=>{async function Z(){let I=await V.xferState.get();Q(I)}let J=V.xferState.listen(Z);return Z(),()=>{J()}},[V]),$}function JJ(V){BV(()=>{async function $(){try{await V.connect(),await V.sync()}catch(I){console.error("reconnectAndSync failed",I)}}function Q(){$()}function Z(){if(typeof document<"u"&&document.visibilityState==="visible")$()}function J(){$()}if(globalThis.addEventListener("online",Q),typeof document<"u")document.addEventListener("visibilitychange",Z);return globalThis.addEventListener("focus",J),globalThis.addEventListener("pageshow",J),()=>{if(globalThis.removeEventListener("online",Q),typeof document<"u")document.removeEventListener("visibilitychange",Z);globalThis.removeEventListener("focus",J),globalThis.removeEventListener("pageshow",J)}},[V])}function IJ(V={}){let $=V.clock??new w0,{seed:Q,host:Z,readyTimeoutMs:J}=V,I=V.worker,W="store"in V?V.store:void 0,[Y,X]=f$({stateMgr:q$});return BV(()=>{let G=!1,K;return(async()=>{let N=await _$();if(G)return;let M=H$(N),z=I!==void 0?await fV({state:M,clock:$,worker:I,readyTimeoutMs:J}):await fV({state:M,clock:$,store:W,readyTimeoutMs:J});if(G){z.dispose();return}K=z.dispose;let{client:U,mode:w}=z;if(Q)await U.setSeed(Q);if(Z)await U.link(Z);if(G){K();return}X({client:U,entDB:N,stateMgr:M,mode:w,error:void 0})})().catch((N)=>{let M=N instanceof Error?N:Error(String(N));if(console.error("[DIPLOMATIC] useClient init failed",M),!G)X((z)=>({...z,client:void 0,error:M}))}),()=>{G=!0,K?.()}},[$,Q,Z,I,W,J]),Y}import{use as WJ,useEffect as rQ,useRef as YJ,useState as XJ}from"react";function hQ(V,$,Q){let[Z,J]=XJ();return rQ(()=>{async function I(){let W=await Q();J(W)}return I(),V.on($,I),()=>{V.off($,I)}},[V,$,Q]),Z}function GJ(V,$,Q){let Z=YJ(Q());return rQ(()=>{async function J(){Z.current=Q()}return V.on($,J),()=>{V.off($,J)}},[V,$,Q]),WJ(Z.current)}function cQ(V,$){return`${V}:${$}`}class B${queue=new Map;async enq(V){for(let $ of V){let Q=cQ($.host,$.seq);this.queue.set(Q,$)}}async deq(V,$){for(let Q of $){let Z=cQ(V,Q);this.queue.delete(Z)}}async list(){let V=[];for(let $ of this.queue.values())V.push($);return V}async count(){return this.queue.size}async wipe(){this.queue.clear()}}class g${hosts=new Map;async add(V){let $={...V,lastSeq:0};this.hosts.set(V.label,$)}async touch(V,$){let Q=this.hosts.get(V);if(!Q||$<=Q.lastSeq)return;this.hosts.set(V,{...Q,lastSeq:$})}async get(V){return this.hosts.get(V)}async set(V,$){let Q=this.hosts.get(V);if(!Q)return 13;return this.hosts.set(V,{...Q,...$}),0}async del(V){this.hosts.delete(V)}async list(){return this.hosts.values()}async wipe(){this.hosts.clear()}}class i${crypto;messages=new Map;constructor(V){this.crypto=V}async add(V){let $=[];for(let{key:Q,data:Z}of V)this.messages.set(k(Q),Z),$.push(0);return $}async del(V){for(let $ of V)this.messages.delete(k($))}async get(V){let $=this.messages.get(k(V));if($)return await N0(V,$,this.crypto);return}async getMany(V){let $=[];for(let Q of V)$.push(await this.get(Q));return $}async has(V){return this.messages.has(k(V))}async list(){let V=Array.from(this.messages.entries());return await Promise.all(V.map(([Q,Z])=>{let J=Z0(Q);return N0(J,Z,this.crypto)}))}async last(V){let $;for(let[Q,Z]of this.messages){if(X0(V,Z.eid)===!1)continue;let J=Z0(Q);if($===void 0)$={hash:J,data:Z};else if((Z.ctr??0)>($.data.ctr??0)||(Z.ctr??0)===($.data.ctr??0)&&(Z.off??0)>($.data.off??0))$={hash:J,data:Z}}if($)return await N0($.hash,$.data,this.crypto);return}async listUnapplied(){let V=[];for(let[$,Q]of this.messages){if(!S$(Q))continue;let Z=Z0($);V.push(await N0(Z,Q,this.crypto))}return V}async markApplied(V){for(let $ of V){let Q=k($),Z=this.messages.get(Q);if(!Z)continue;this.messages.set(Q,{...S0(Z),apld:!0})}}async wipe(){this.messages.clear()}}class v${enclave;async save(V){return this.enclave=new h0(V,J0),this.enclave}async load(){return this.enclave}async wipe(){this.enclave=void 0}}class u${queue=new Map;async enq(V,$){let Q=this.queue.get(V);if(!Q)Q=new Map,this.queue.set(V,Q);for(let Z of $)Q.set(o(Z.hash),Z.bodyLen)}async deq(V,$){let Q=this.queue.get(V);if(Q)for(let Z of $)Q.delete(o(Z))}async list(V){let $=this.queue.get(V);if(!$)return[];let Q=[];for(let[Z,J]of $)Q.push({hash:A0(Z),bodyLen:J});return Q}async count(){let V=0;for(let $ of this.queue.values())V+=$.size;return V}async wipe(){this.queue.clear()}}class dQ{seed=new v$;hosts=new g$;uploads=new u$;downloads=new B$;messages;constructor(V){this.messages=new i$(V)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}class oQ{singletonType;latest;latestOff=-1;emitter=new H0;constructor(V){this.singletonType=V}async apply(V){for(let $ of V){let Q=new B($.eid),[Z,J]=Q.readStruct(t);if(J!==0)continue;let I=new x;I.writeVarString(this.singletonType);let W=I.result();if(Z.id.length===W.length&&Z.id.every((Y,X)=>Y===W[X])){if(this.latest===void 0||$.off>this.latestOff)this.latestOff=$.off,this.latest=$.bod,this.emitter.emit(this.singletonType,null)}}return V.map(()=>0)}clear=async()=>{return this.latest=void 0,this.latestOff=-1,this.emitter.emit(this.singletonType,null),0};notify=(V)=>{for(let $ of V)if($===this.singletonType)this.emitter.emit(this.singletonType,null)};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}async function $N(V,$){let Q=await xV(J0),Z=new _0(new w0,V,Q,zV,J0);return{client:Z,setSeed:async(I)=>{let W=A0(I);await Q.seed.save(W),await Q.hosts.add({handle:$,label:"host",idx:0}),await Z.connect()}}}export{JJ as useSyncOnResume,GJ as useStateWatcherSuspense,hQ as useStateWatcher,ZJ as useClientXferState,QJ as useClientState,IJ as useClient,V$ as shouldEmitItemProgress,xV as openIDBStore,_$ as openEntIDB,fV as openDiplomaticClient,q$ as nullStateManager,oZ as nullEntDB,S0 as normalizeStoredMessageData,S$ as isPendingApply,n0 as idleProgress,A0 as htob,zV as hostHTTPTransport,$N as genWebClient,CZ as genSingletonEID,H$ as entStateManager,t as eidCodec,VV as defaultPeekProgressEvery,J0 as crypto,o as btoh,JV as WorkerClient,H0 as TypedEventEmitter,_0 as SyncClient,_ as Status,LV as StateManager,oQ as SingletonStateManager,dQ as MemoryStore,k$ as IDBStore,aV as HTTPTransport,A$ as EntIDB,uQ as EntDBMemory,x as Encoder,B as Decoder,w0 as Clock};
1
+ function p$(V){let $=V.length,Q=0,Z=0;while(Z<$){let J=V.charCodeAt(Z++);if((J&4294967168)===0){Q++;continue}else if((J&4294965248)===0)Q+=2;else{if(J>=55296&&J<=56319){if(Z<$){let W=V.charCodeAt(Z);if((W&64512)===56320)++Z,J=((J&1023)<<10)+(W&1023)+65536}}if((J&4294901760)===0)Q+=3;else Q+=4}}return Q}function eQ(V,$,Q){let Z=V.length,J=Q,W=0;while(W<Z){let I=V.charCodeAt(W++);if((I&4294967168)===0){$[J++]=I;continue}else if((I&4294965248)===0)$[J++]=I>>6&31|192;else{if(I>=55296&&I<=56319){if(W<Z){let Y=V.charCodeAt(W);if((Y&64512)===56320)++W,I=((I&1023)<<10)+(Y&1023)+65536}}if((I&4294901760)===0)$[J++]=I>>12&15|224,$[J++]=I>>6&63|128;else $[J++]=I>>18&7|240,$[J++]=I>>12&63|128,$[J++]=I>>6&63|128}$[J++]=I&63|128}}var VZ=new TextEncoder,$Z=50;function QZ(V,$,Q){VZ.encodeInto(V,$.subarray(Q))}function r$(V,$,Q){if(V.length>$Z)QZ(V,$,Q);else eQ(V,$,Q)}var ZZ=4096;function nV(V,$,Q){let Z=$,J=Z+Q,W=[],I="";while(Z<J){let Y=V[Z++];if((Y&128)===0)W.push(Y);else if((Y&224)===192){let X=V[Z++]&63;W.push((Y&31)<<6|X)}else if((Y&240)===224){let X=V[Z++]&63,G=V[Z++]&63;W.push((Y&31)<<12|X<<6|G)}else if((Y&248)===240){let X=V[Z++]&63,G=V[Z++]&63,K=V[Z++]&63,w=(Y&7)<<18|X<<12|G<<6|K;if(w>65535)w-=65536,W.push(w>>>10&1023|55296),w=56320|w&1023;W.push(w)}else W.push(Y);if(W.length>=ZZ)I+=String.fromCharCode(...W),W.length=0}if(W.length>0)I+=String.fromCharCode(...W);return I}var JZ=new TextDecoder,WZ=200;function IZ(V,$,Q){let Z=V.subarray($,$+Q);return JZ.decode(Z)}function l$(V,$,Q){if(Q>WZ)return IZ(V,$,Q);else return nV(V,$,Q)}class u0{type;data;constructor(V,$){this.type=V,this.data=$}}class s extends Error{constructor(V){super(V);let $=Object.create(s.prototype);Object.setPrototypeOf(this,$),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:s.name})}}var n0=4294967295;function h$(V,$,Q){let Z=Q/4294967296,J=Q;V.setUint32($,Z),V.setUint32($+4,J)}function GV(V,$,Q){let Z=Math.floor(Q/4294967296),J=Q;V.setUint32($,Z),V.setUint32($+4,J)}function KV(V,$){let Q=V.getInt32($),Z=V.getUint32($+4);return Q*4294967296+Z}function c$(V,$){let Q=V.getUint32($),Z=V.getUint32($+4);return Q*4294967296+Z}var YZ=-1,XZ=4294967295,GZ=17179869183;function KZ({sec:V,nsec:$}){if(V>=0&&$>=0&&V<=GZ)if($===0&&V<=XZ){let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,V),Q}else{let Q=V/4294967296,Z=V&4294967295,J=new Uint8Array(8),W=new DataView(J.buffer);return W.setUint32(0,$<<2|Q&3),W.setUint32(4,Z),J}else{let Q=new Uint8Array(12),Z=new DataView(Q.buffer);return Z.setUint32(0,$),GV(Z,4,V),Q}}function MZ(V){let $=V.getTime(),Q=Math.floor($/1000),Z=($-Q*1000)*1e6,J=Math.floor(Z/1e9);return{sec:Q+J,nsec:Z-J*1e9}}function wZ(V){if(V instanceof Date){let $=MZ(V);return KZ($)}else return null}function NZ(V){let $=new DataView(V.buffer,V.byteOffset,V.byteLength);switch(V.byteLength){case 4:{let Q=$.getUint32(0),Z=0;return{sec:Q,nsec:0}}case 8:{let Q=$.getUint32(0),Z=$.getUint32(4),J=(Q&3)*4294967296+Z,W=Q>>>2;return{sec:J,nsec:W}}case 12:{let Q=KV($,4),Z=$.getUint32(0);return{sec:Q,nsec:Z}}default:throw new s(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${V.length}`)}}function RZ(V){let $=NZ(V);return new Date($.sec*1000+$.nsec/1e6)}var d$={type:YZ,encode:wZ,decode:RZ};class y0{static defaultCodec=new y0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(d$)}register({type:V,encode:$,decode:Q}){if(V>=0)this.encoders[V]=$,this.decoders[V]=Q;else{let Z=-1-V;this.builtInEncoders[Z]=$,this.builtInDecoders[Z]=Q}}tryToEncode(V,$){for(let Q=0;Q<this.builtInEncoders.length;Q++){let Z=this.builtInEncoders[Q];if(Z!=null){let J=Z(V,$);if(J!=null){let W=-1-Q;return new u0(W,J)}}}for(let Q=0;Q<this.encoders.length;Q++){let Z=this.encoders[Q];if(Z!=null){let J=Z(V,$);if(J!=null)return new u0(Q,J)}}if(V instanceof u0)return V;return null}decode(V,$,Q){let Z=$<0?this.builtInDecoders[-1-$]:this.decoders[$];if(Z)return Z(V,$,Q);else return new u0($,V)}}function zZ(V){return V instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&V instanceof SharedArrayBuffer}function a0(V){if(V instanceof Uint8Array)return V;else if(ArrayBuffer.isView(V))return new Uint8Array(V.buffer,V.byteOffset,V.byteLength);else if(zZ(V))return new Uint8Array(V);else return Uint8Array.from(V)}var UZ=100,FZ=2048;class MV{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??y0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.maxDepth=V?.maxDepth??UZ,this.initialBufferSize=V?.initialBufferSize??FZ,this.sortKeys=V?.sortKeys??!1,this.forceFloat32=V?.forceFloat32??!1,this.ignoreUndefined=V?.ignoreUndefined??!1,this.forceIntegerToFloat=V?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new MV({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(V){if(this.entered)return this.clone().encodeSharedRef(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(V){if(this.entered)return this.clone().encode(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(V,$){if($>this.maxDepth)throw Error(`Too deep objects in depth ${$}`);if(V==null)this.encodeNil();else if(typeof V==="boolean")this.encodeBoolean(V);else if(typeof V==="number")if(!this.forceIntegerToFloat)this.encodeNumber(V);else this.encodeNumberAsFloat(V);else if(typeof V==="string")this.encodeString(V);else if(this.useBigInt64&&typeof V==="bigint")this.encodeBigInt64(V);else this.encodeObject(V,$)}ensureBufferSizeToWrite(V){let $=this.pos+V;if(this.view.byteLength<$)this.resizeBuffer($*2)}resizeBuffer(V){let $=new ArrayBuffer(V),Q=new Uint8Array($),Z=new DataView($);Q.set(this.bytes),this.view=Z,this.bytes=Q}encodeNil(){this.writeU8(192)}encodeBoolean(V){if(V===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber(V){if(!this.forceIntegerToFloat&&Number.isSafeInteger(V))if(V>=0)if(V<128)this.writeU8(V);else if(V<256)this.writeU8(204),this.writeU8(V);else if(V<65536)this.writeU8(205),this.writeU16(V);else if(V<4294967296)this.writeU8(206),this.writeU32(V);else if(!this.useBigInt64)this.writeU8(207),this.writeU64(V);else this.encodeNumberAsFloat(V);else if(V>=-32)this.writeU8(224|V+32);else if(V>=-128)this.writeU8(208),this.writeI8(V);else if(V>=-32768)this.writeU8(209),this.writeI16(V);else if(V>=-2147483648)this.writeU8(210),this.writeI32(V);else if(!this.useBigInt64)this.writeU8(211),this.writeI64(V);else this.encodeNumberAsFloat(V);else this.encodeNumberAsFloat(V)}encodeNumberAsFloat(V){if(this.forceFloat32)this.writeU8(202),this.writeF32(V);else this.writeU8(203),this.writeF64(V)}encodeBigInt64(V){if(V>=BigInt(0))this.writeU8(207),this.writeBigUint64(V);else this.writeU8(211),this.writeBigInt64(V)}writeStringHeader(V){if(V<32)this.writeU8(160+V);else if(V<256)this.writeU8(217),this.writeU8(V);else if(V<65536)this.writeU8(218),this.writeU16(V);else if(V<4294967296)this.writeU8(219),this.writeU32(V);else throw Error(`Too long string: ${V} bytes in UTF-8`)}encodeString(V){let Q=p$(V);this.ensureBufferSizeToWrite(5+Q),this.writeStringHeader(Q),r$(V,this.bytes,this.pos),this.pos+=Q}encodeObject(V,$){let Q=this.extensionCodec.tryToEncode(V,this.context);if(Q!=null)this.encodeExtension(Q);else if(Array.isArray(V))this.encodeArray(V,$);else if(ArrayBuffer.isView(V))this.encodeBinary(V);else if(typeof V==="object")this.encodeMap(V,$);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply(V)}`)}encodeBinary(V){let $=V.byteLength;if($<256)this.writeU8(196),this.writeU8($);else if($<65536)this.writeU8(197),this.writeU16($);else if($<4294967296)this.writeU8(198),this.writeU32($);else throw Error(`Too large binary: ${$}`);let Q=a0(V);this.writeU8a(Q)}encodeArray(V,$){let Q=V.length;if(Q<16)this.writeU8(144+Q);else if(Q<65536)this.writeU8(220),this.writeU16(Q);else if(Q<4294967296)this.writeU8(221),this.writeU32(Q);else throw Error(`Too large array: ${Q}`);for(let Z of V)this.doEncode(Z,$+1)}countWithoutUndefined(V,$){let Q=0;for(let Z of $)if(V[Z]!==void 0)Q++;return Q}encodeMap(V,$){let Q=Object.keys(V);if(this.sortKeys)Q.sort();let Z=this.ignoreUndefined?this.countWithoutUndefined(V,Q):Q.length;if(Z<16)this.writeU8(128+Z);else if(Z<65536)this.writeU8(222),this.writeU16(Z);else if(Z<4294967296)this.writeU8(223),this.writeU32(Z);else throw Error(`Too large map object: ${Z}`);for(let J of Q){let W=V[J];if(!(this.ignoreUndefined&&W===void 0))this.encodeString(J),this.doEncode(W,$+1)}}encodeExtension(V){if(typeof V.data==="function"){let Q=V.data(this.pos+6),Z=Q.length;if(Z>=4294967296)throw Error(`Too large extension object: ${Z}`);this.writeU8(201),this.writeU32(Z),this.writeI8(V.type),this.writeU8a(Q);return}let $=V.data.length;if($===1)this.writeU8(212);else if($===2)this.writeU8(213);else if($===4)this.writeU8(214);else if($===8)this.writeU8(215);else if($===16)this.writeU8(216);else if($<256)this.writeU8(199),this.writeU8($);else if($<65536)this.writeU8(200),this.writeU16($);else if($<4294967296)this.writeU8(201),this.writeU32($);else throw Error(`Too large extension object: ${$}`);this.writeI8(V.type),this.writeU8a(V.data)}writeU8(V){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,V),this.pos++}writeU8a(V){let $=V.length;this.ensureBufferSizeToWrite($),this.bytes.set(V,this.pos),this.pos+=$}writeI8(V){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,V),this.pos++}writeU16(V){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,V),this.pos+=2}writeI16(V){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,V),this.pos+=2}writeU32(V){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,V),this.pos+=4}writeI32(V){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,V),this.pos+=4}writeF32(V){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,V),this.pos+=4}writeF64(V){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,V),this.pos+=8}writeU64(V){this.ensureBufferSizeToWrite(8),h$(this.view,this.pos,V),this.pos+=8}writeI64(V){this.ensureBufferSizeToWrite(8),GV(this.view,this.pos,V),this.pos+=8}writeBigUint64(V){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,V),this.pos+=8}writeBigInt64(V){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,V),this.pos+=8}}function wV(V,$){return new MV($).encodeSharedRef(V)}function NV(V){return`${V<0?"-":""}0x${Math.abs(V).toString(16).padStart(2,"0")}`}var qZ=16,OZ=16;class yV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(V=qZ,$=OZ){this.maxKeyLength=V,this.maxLengthPerKey=$,this.caches=[];for(let Q=0;Q<this.maxKeyLength;Q++)this.caches.push([])}canBeCached(V){return V>0&&V<=this.maxKeyLength}find(V,$,Q){let Z=this.caches[Q-1];V:for(let J of Z){let W=J.bytes;for(let I=0;I<Q;I++)if(W[I]!==V[$+I])continue V;return J.str}return null}store(V,$){let Q=this.caches[V.length-1],Z={bytes:V,str:$};if(Q.length>=this.maxLengthPerKey)Q[Math.random()*Q.length|0]=Z;else Q.push(Z)}decode(V,$,Q){let Z=this.find(V,$,Q);if(Z!=null)return this.hit++,Z;this.miss++;let J=nV(V,$,Q),W=Uint8Array.prototype.slice.call(V,$,$+Q);return this.store(W,J),J}}var bV="array",t0="map_key",a$="map_value",HZ=(V)=>{if(typeof V==="string"||typeof V==="number")return V;throw new s("The type of key must be string or number but "+typeof V)};class s${stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(V){let $=this.getUninitializedStateFromPool();$.type=bV,$.position=0,$.size=V,$.array=Array(V)}pushMapState(V){let $=this.getUninitializedStateFromPool();$.type=t0,$.readCount=0,$.size=V,$.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let V={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(V)}return this.stack[this.stackHeadPosition]}release(V){if(this.stack[this.stackHeadPosition]!==V)throw Error("Invalid stack state. Released state is not on top of the stack.");if(V.type===bV){let Q=V;Q.size=0,Q.array=void 0,Q.position=0,Q.type=void 0}if(V.type===t0||V.type===a$){let Q=V;Q.size=0,Q.map=void 0,Q.readCount=0,Q.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var s0=-1,pV=new DataView(new ArrayBuffer(0)),PZ=new Uint8Array(pV.buffer);try{pV.getInt8(0)}catch(V){if(!(V instanceof RangeError))throw Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var o$=RangeError("Insufficient data"),CZ=new yV;class RV{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=pV;bytes=PZ;headByte=s0;stack=new s$;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??y0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.rawStrings=V?.rawStrings??!1,this.maxStrLength=V?.maxStrLength??n0,this.maxBinLength=V?.maxBinLength??n0,this.maxArrayLength=V?.maxArrayLength??n0,this.maxMapLength=V?.maxMapLength??n0,this.maxExtLength=V?.maxExtLength??n0,this.keyDecoder=V?.keyDecoder!==void 0?V.keyDecoder:CZ,this.mapKeyConverter=V?.mapKeyConverter??HZ}clone(){return new RV({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=s0,this.stack.reset()}setBuffer(V){let $=a0(V);this.bytes=$,this.view=new DataView($.buffer,$.byteOffset,$.byteLength),this.pos=0}appendBuffer(V){if(this.headByte===s0&&!this.hasRemaining(1))this.setBuffer(V);else{let $=this.bytes.subarray(this.pos),Q=a0(V),Z=new Uint8Array($.length+Q.length);Z.set($),Z.set(Q,$.length),this.setBuffer(Z)}}hasRemaining(V){return this.view.byteLength-this.pos>=V}createExtraByteError(V){let{view:$,pos:Q}=this;return RangeError(`Extra ${$.byteLength-Q} of ${$.byteLength} byte(s) found at buffer[${V}]`)}decode(V){if(this.entered)return this.clone().decode(V);try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);let $=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return $}finally{this.entered=!1}}*decodeMulti(V){if(this.entered){yield*this.clone().decodeMulti(V);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(V){if(this.entered)return this.clone().decodeAsync(V);try{this.entered=!0;let $=!1,Q;for await(let I of V){if($)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(I);try{Q=this.doDecodeSync(),$=!0}catch(Y){if(!(Y instanceof RangeError))throw Y}this.totalPos+=this.pos}if($){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Q}let{headByte:Z,pos:J,totalPos:W}=this;throw RangeError(`Insufficient data in parsing ${NV(Z)} at ${W} (${J} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(V){return this.decodeMultiAsync(V,!0)}decodeStream(V){return this.decodeMultiAsync(V,!1)}async*decodeMultiAsync(V,$){if(this.entered){yield*this.clone().decodeMultiAsync(V,$);return}try{this.entered=!0;let Q=$,Z=-1;for await(let J of V){if($&&Z===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(J),Q)Z=this.readArraySize(),Q=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--Z===0)break}catch(W){if(!(W instanceof RangeError))throw W}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){V:while(!0){let V=this.readHeadByte(),$;if(V>=224)$=V-256;else if(V<192)if(V<128)$=V;else if(V<144){let Z=V-128;if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V<160){let Z=V-144;if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else{let Z=V-160;$=this.decodeString(Z,0)}else if(V===192)$=null;else if(V===194)$=!1;else if(V===195)$=!0;else if(V===202)$=this.readF32();else if(V===203)$=this.readF64();else if(V===204)$=this.readU8();else if(V===205)$=this.readU16();else if(V===206)$=this.readU32();else if(V===207)if(this.useBigInt64)$=this.readU64AsBigInt();else $=this.readU64();else if(V===208)$=this.readI8();else if(V===209)$=this.readI16();else if(V===210)$=this.readI32();else if(V===211)if(this.useBigInt64)$=this.readI64AsBigInt();else $=this.readI64();else if(V===217){let Z=this.lookU8();$=this.decodeString(Z,1)}else if(V===218){let Z=this.lookU16();$=this.decodeString(Z,2)}else if(V===219){let Z=this.lookU32();$=this.decodeString(Z,4)}else if(V===220){let Z=this.readU16();if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else if(V===221){let Z=this.readU32();if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else if(V===222){let Z=this.readU16();if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V===223){let Z=this.readU32();if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V===196){let Z=this.lookU8();$=this.decodeBinary(Z,1)}else if(V===197){let Z=this.lookU16();$=this.decodeBinary(Z,2)}else if(V===198){let Z=this.lookU32();$=this.decodeBinary(Z,4)}else if(V===212)$=this.decodeExtension(1,0);else if(V===213)$=this.decodeExtension(2,0);else if(V===214)$=this.decodeExtension(4,0);else if(V===215)$=this.decodeExtension(8,0);else if(V===216)$=this.decodeExtension(16,0);else if(V===199){let Z=this.lookU8();$=this.decodeExtension(Z,1)}else if(V===200){let Z=this.lookU16();$=this.decodeExtension(Z,2)}else if(V===201){let Z=this.lookU32();$=this.decodeExtension(Z,4)}else throw new s(`Unrecognized type byte: ${NV(V)}`);this.complete();let Q=this.stack;while(Q.length>0){let Z=Q.top();if(Z.type===bV)if(Z.array[Z.position]=$,Z.position++,Z.position===Z.size)$=Z.array,Q.release(Z);else continue V;else if(Z.type===t0){if($==="__proto__")throw new s("The key __proto__ is not allowed");Z.key=this.mapKeyConverter($),Z.type=a$;continue V}else if(Z.map[Z.key]=$,Z.readCount++,Z.readCount===Z.size)$=Z.map,Q.release(Z);else{Z.key=null,Z.type=t0;continue V}}return $}}readHeadByte(){if(this.headByte===s0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=s0}readArraySize(){let V=this.readHeadByte();switch(V){case 220:return this.readU16();case 221:return this.readU32();default:if(V<160)return V-144;else throw new s(`Unrecognized array type byte: ${NV(V)}`)}}pushMapState(V){if(V>this.maxMapLength)throw new s(`Max length exceeded: map length (${V}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(V)}pushArrayState(V){if(V>this.maxArrayLength)throw new s(`Max length exceeded: array length (${V}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(V)}decodeString(V,$){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String(V,$);return this.decodeBinary(V,$)}decodeUtf8String(V,$){if(V>this.maxStrLength)throw new s(`Max length exceeded: UTF-8 byte length (${V}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+$+V)throw o$;let Q=this.pos+$,Z;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached(V))Z=this.keyDecoder.decode(this.bytes,Q,V);else Z=l$(this.bytes,Q,V);return this.pos+=$+V,Z}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===t0;return!1}decodeBinary(V,$){if(V>this.maxBinLength)throw new s(`Max length exceeded: bin length (${V}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(V+$))throw o$;let Q=this.pos+$,Z=this.bytes.subarray(Q,Q+V);return this.pos+=$+V,Z}decodeExtension(V,$){if(V>this.maxExtLength)throw new s(`Max length exceeded: ext length (${V}) > maxExtLength (${this.maxExtLength})`);let Q=this.view.getInt8(this.pos+$),Z=this.decodeBinary(V,$+1);return this.extensionCodec.decode(Z,Q,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let V=this.view.getUint8(this.pos);return this.pos++,V}readI8(){let V=this.view.getInt8(this.pos);return this.pos++,V}readU16(){let V=this.view.getUint16(this.pos);return this.pos+=2,V}readI16(){let V=this.view.getInt16(this.pos);return this.pos+=2,V}readU32(){let V=this.view.getUint32(this.pos);return this.pos+=4,V}readI32(){let V=this.view.getInt32(this.pos);return this.pos+=4,V}readU64(){let V=c$(this.view,this.pos);return this.pos+=8,V}readI64(){let V=KV(this.view,this.pos);return this.pos+=8,V}readU64AsBigInt(){let V=this.view.getBigUint64(this.pos);return this.pos+=8,V}readI64AsBigInt(){let V=this.view.getBigInt64(this.pos);return this.pos+=8,V}readF32(){let V=this.view.getFloat32(this.pos);return this.pos+=4,V}readF64(){let V=this.view.getFloat64(this.pos);return this.pos+=8,V}}function rV(V,$){return new RV($).decode(V)}class C0{listeners=new Map;addEventListener(V,$){let Q=this.listeners.get(V);if(!Q)Q=new Set,this.listeners.set(V,Q);return Q.add($),()=>{this.removeEventListener(V,$)}}removeEventListener(V,$){let Q=this.listeners.get(V);if(Q){if(Q.delete($),Q.size===0)this.listeners.delete(V)}}emit(V,$){let Q=this.listeners.get(V);if(Q){let Z=Array.from(Q);for(let J of Z)J($)}}emitAll(V){let $=Array.from(this.listeners.keys());for(let Q of $)this.emit(Q,V)}}class G0{getter;static eventName="update";emitter;constructor(V){this.getter=V;this.emitter=new C0}get=()=>this.getter();async emit(){let V=await this.getter();queueMicrotask(()=>this.emitter.emit(G0.eventName,V))}listen(V){return this.emitter.addEventListener(G0.eventName,V),()=>{this.emitter.removeEventListener(G0.eventName,V)}}}var T0=64;var t$=32,D0=8;var zV=32;var e$=30000,VQ=512,_;((C)=>{C[C.Success=0]="Success";C[C.InvalidSignature=3]="InvalidSignature";C[C.ClockOutOfSync=4]="ClockOutOfSync";C[C.UserNotRegistered=5]="UserNotRegistered";C[C.ServerMisconfigured=6]="ServerMisconfigured";C[C.MissingBody=7]="MissingBody";C[C.ExtraBodyContent=8]="ExtraBodyContent";C[C.MissingParam=9]="MissingParam";C[C.InvalidParam=10]="InvalidParam";C[C.InvalidRequest=11]="InvalidRequest";C[C.InternalError=12]="InternalError";C[C.NotFound=13]="NotFound";C[C.InvalidMessage=14]="InvalidMessage";C[C.NoChange=15]="NoChange";C[C.DatabaseClosed=16]="DatabaseClosed";C[C.StorageError=17]="StorageError";C[C.DatabaseError=18]="DatabaseError";C[C.HashMismatch=19]="HashMismatch";C[C.DecryptionError=20]="DecryptionError";C[C.NotImplemented=21]="NotImplemented";C[C.MissingSeed=22]="MissingSeed";C[C.OutOfBounds=23]="OutOfBounds";C[C.HostError=24]="HostError";C[C.CommunicationError=25]="CommunicationError";C[C.VarLimitExceeded=26]="VarLimitExceeded";C[C.InvalidResponse=27]="InvalidResponse";C[C.ConnectionClosed=28]="ConnectionClosed"})(_||={});function q(V){return[V,0]}function M(V){return[void 0,V]}function TZ(V){if(V<0)console.info("N",V),console.trace();if(typeof V!=="bigint")V=BigInt(V);if(V<0n)return M(10);let $=[];while(V>0n){let Q=Number(V&0x7fn);if(V>>=7n,V>0n)$.push(Q|128);else $.push(Q)}if($.length===0)return q(new Uint8Array([0]));if($.length>8)return M(26);return q(new Uint8Array($))}function DZ(V,$=0){let Q=0n,Z=0,J=$;while(!0){if(J>=V.length)return M(14);let W=V[J++];if(W===void 0)return M(14);if(Q|=BigInt(W&127)<<BigInt(Z),(W&128)===0){if(J-$>8)return M(26);return q({value:Q>0x1fffffffffffffn?Q:Number(Q),bytesRead:J-$})}if(Z+=7,Z>=56)return M(26)}}class B{data;pos=0;constructor(V){this.data=V}static async fromResponse(V){let $=await V.arrayBuffer(),Q=new Uint8Array($);return new B(Q)}readBigInt(){if(this.pos+8>this.data.length)return M(7);let V=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,q(V)}readDate(){let[V,$]=this.readVarInt();if($!==0)return M($);return q(new Date(V))}readVarInt(){let[V,$]=DZ(this.data,this.pos);if($!==0)return M($);this.pos+=V.bytesRead;let Q=V.value;return q(typeof Q==="bigint"?Number(Q):Q)}readVarString(){let[V,$]=this.readVarInt();if($!==0)return M($);let[Q,Z]=this.readBytes(V);if(Z!==0)return M(Z);let J=new TextDecoder().decode(Q);return q(J)}readBytes(V){if(V<0)return M(10);if(this.pos+V>this.data.length)return M(23);let $=this.data.slice(this.pos,this.pos+V);return this.pos+=V,q($)}readVarBytes(){let[V,$]=this.readVarInt();if($!==0)return M($);return this.readBytes(V)}readStruct(V){return V.decode(this)}readStructs(V){let $=[];while(!this.done()){let[Q,Z]=this.readStruct(V);if(Z!==0)return M(Z);$.push(Q)}return q($)}readBytesSeq(V){let $=[];while(!this.done()){let[Q,Z]=this.readBytes(V);if(Z!==0)return M(Z);$.push(Q)}return q($)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class k{parts=[];writeBigInt(V){let $=new Uint8Array(8);new DataView($.buffer).setBigUint64(0,V,!1),this.parts.push($)}writeDate(V){let $=V.getTime();return this.writeVarInt($)}writeVarInt(V){let[$,Q]=TZ(V);if(Q!==0)return Q;return this.parts.push($),0}writeVarString(V){let $=new TextEncoder().encode(V),Q=this.writeVarInt($.length);if(Q!==0)return Q;return this.writeBytes($),0}prependBytes(V){this.parts.unshift(V)}writeBytes(V){this.parts.push(V)}writeVarBytes(V){let $=this.writeVarInt(V.length);if($!==0)return $;return this.writeBytes(V),0}writeStruct(V,$){return V.encode(this,$)}writeStructs(V,$){for(let Q of $){let Z=this.writeStruct(V,Q);if(Z!==0)return Z}return 0}writeBytesSeq(V){for(let $ of V)this.writeBytes($)}result(){let V=this.parts.reduce((Z,J)=>Z+J.length,0),$=new Uint8Array(V),Q=0;for(let Z of this.parts)$.set(Z,Q),Q+=Z.length;return $}*scan(){for(let V of this.parts)yield V}}async function lV(V,$,Q){let Z=new k,J=Z.writeDate($);if(J!==0)return M(J);let W=Z.result(),I=await Q.signEd25519(W,V.privateKey);return q({pubKey:V.publicKey,sig:I,timestamp:$})}async function A0(V,$,Q){let Z=Q.now().getTime(),J=V.timestamp.getTime();if(Math.abs(Z-J)>e$)return 4;let I=new k;I.writeDate(V.timestamp);let Y=I.result();if(!await $.checkSigEd25519(V.sig,Y,V.pubKey))return 3;return 0}var t={encode(V,$){let Q=V.writeVarBytes($.id);if(Q!==0)return Q;let Z=V.writeDate($.ts);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return M(Q);let[Z,J]=V.readDate();if(J!==0)return M(J);return q({id:$,ts:Z})}};function b0(V){let $=new k,Q=$.writeStruct(t,V);if(Q!==0)return M(Q);let Z=$.result();return q(Z)}async function AZ(V){return b0({id:V,ts:new Date(0)})}var I0={encode(V,$){let Q=V.writeVarBytes($.eid);if(Q!==0)return Q;let Z=V.writeVarInt($.off);if(Z!==0)return Z;let J=V.writeVarInt($.ctr);if(J!==0)return J;let W=V.writeVarInt($.len);if(W!==0)return W;if($.hsh)V.writeBytes($.hsh);return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return M(Q);let Z=new B($),[,J]=t.decode(Z);if(J!==0)return M(J);let[W,I]=V.readVarInt();if(I!==0)return M(I);let[Y,X]=V.readVarInt();if(X!==0)return M(X);let[G,K]=V.readVarInt();if(K!==0)return M(K);let w;if(G>0){let[N,z]=V.readBytes(zV);if(z!==0)return M(z);w=N}return q({eid:$,off:W,ctr:Y,len:G,hsh:w})}};function o(V){return Array.from(V).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}function _0(V){if(V.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(V.length/2);for(let Q=0;Q<V.length;Q+=2)$[Q/2]=Number.parseInt(V.substr(Q,2),16);return $}function X0(V,$){if(V===$)return!0;if(V.byteLength!==$.byteLength)return!1;return V.every((Q,Z)=>Q===$[Z])}var x;if(typeof Uint8Array.prototype.toBase64==="function")x=(V)=>V.toBase64();else x=(V)=>btoa(String.fromCharCode(...V));var Y0;if(typeof Uint8Array.fromBase64==="function")Y0=(V)=>Uint8Array.fromBase64(V);else Y0=(V)=>Uint8Array.from(atob(V),($)=>$.charCodeAt(0));function e0(V,$){let Q=new Uint8Array(V.length+$.length);return Q.set(V,0),Q.set($,V.length),Q}function $Q(V,$,Q){return Q.checkSigEd25519(V.sig,V.headCph,$)}async function hV(V,$,Q){let Z=e0($.privateKey,V);return(await Q.blake3(Z)).slice(0,D0)}async function QQ(V,$,Q,Z){let J;if(V.bod&&V.len>0)J=await Q.blake3(V.bod);let W=new k,I=I0.encode(W,{...V,hsh:J});if(I!==0)return M(I);let Y=W.result(),X=await hV(Y,$,Q),G=await Z.deriveFromKDM(X),K=await Q.encryptXSalsa20Poly1305Combined(Y,G),w=V.bod?await Q.encryptXSalsa20Poly1305Combined(V.bod,G):new Uint8Array(0),N=await Q.signEd25519(K,$.privateKey);return q({sig:N,kdm:X,headCph:K,bodyCph:w})}async function cV(V,$,Q,Z,J){let W=new B(V),[I,Y]=I0.decode(W);if(Y!==0)return M(14);let X;try{X=$&&$.length>0?await Z.decryptXSalsa20Poly1305Combined($,Q):void 0}catch{return M(20)}let G=I.hsh&&X===void 0,K=I.hsh===void 0&&X!==void 0;if(G||K)return M(19);if(I.hsh&&X){let N=await Z.blake3(X);if(!X0(N,I.hsh))return M(19)}let w=J??await Z.blake3(V);return q({msgHead:I,bod:X,headHash:w})}class R0{now(){return new Date}}function ZQ(V,$,Q,Z){let J=$.getTime()-V.getTime(),W=Q.getTime()-Z.getTime();return(J+W)/2}var VV={encode(V,$){if(V.writeVarInt($.quota),$.quota>0){if($.usage===void 0)return 9;V.writeVarInt($.usage)}return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return M(Q);let Z;if($>0){let[J,W]=V.readVarInt();if(W!==0)return M(W);Z=J}return q({quota:$,usage:Z})}};var dV={encode(V,$){V.writeBytes(new Uint8Array([$.status]));let Q=V.writeDate($.timeRcvd);if(Q!==0)return Q;let Z=V.writeDate($.timeSent);if(Z!==0)return Z;let J=V.writeVarInt($.subscription.term);if(J!==0)return J;let W=V.writeVarInt($.subscription.elapsed);if(W!==0)return W;let I=V.writeStruct(VV,$.subscription.stat);if(I!==0)return I;let Y=V.writeStruct(VV,$.subscription.dyn);if(Y!==0)return Y;return 0},decode(V){let[$,Q]=V.readBytes(1);if(Q!==0)return M(Q);let Z=$[0],[J,W]=V.readDate();if(W!==0)return M(W);let[I,Y]=V.readDate();if(Y!==0)return M(Y);let[X,G]=V.readVarInt();if(G!==0)return M(G);let[K,w]=V.readVarInt();if(w!==0)return M(w);let[N,z]=V.readStruct(VV);if(z!==0)return M(z);let[U,R]=V.readStruct(VV);if(R!==0)return M(R);return q({status:Z,timeRcvd:J,timeSent:I,subscription:{term:X,elapsed:K,stat:N,dyn:U}})}};async function oV(V,$,Q){let{crypto:Z,enclave:J}=V,W=await J.derive($,Q);return await Z.deriveEd25519KeyPair(W)}var aV={encode(V,$){let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarInt($.seq);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return M(Q);let[Z,J]=V.readVarInt();if(J!==0)return M(J);return q({headCph:$,seq:Z})}};var Q0={encode(V,$){V.writeBytes($.pubKey),V.writeBytes($.sig);let Q=V.writeDate($.timestamp);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readBytes(t$);if(Q!==0)return M(Q);let[Z,J]=V.readBytes(T0);if(J!==0)return M(J);let[W,I]=V.readDate();if(I!==0)return M(I);return q({pubKey:$,sig:Z,timestamp:W})}};var JQ={async encodeReq(V,$,Q,Z,J){let W=J.writeStruct(Q0,Q);if(W!==0)return W;for(let I of Z)J.writeVarInt(I);return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:W}=V,[I,Y]=$.readStruct(Q0);if(Y!==0)return Y;let X=await A0(I,J,Z);if(X!==0)return X;let{pubKey:G}=I,[K,w]=await W.hasUser(G);if(w!==0)return w;if(!K)return 5;let[N,z]=$.readVarInt();if(z!==0)return z;if(!$.done())return 8;let[U,R]=await W.listHeads(G,N);if(R!==0)return R;return Q.writeStructs(aV,U)},decodeResp(V){return V.readStructs(aV)}};var sV={encode(V,$){V.writeVarInt($.seq);let Q=V.writeVarBytes($.bodyCph);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return M(Q);let[Z,J]=V.readVarBytes();if(J!==0)return M(J);return q({seq:$,bodyCph:Z})}};var WQ={async encodeReq(V,$,Q,Z,J){let W=J.writeStruct(Q0,Q);if(W!==0)return W;for(let I of Z){let Y=J.writeVarInt(I);if(Y!==0)return Y}return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:W}=V,[I,Y]=$.readStruct(Q0);if(Y!==0)return Y;let X=await A0(I,J,Z);if(X!==0)return X;let{pubKey:G}=I,[K,w]=await W.hasUser(G);if(w!==0)return w;if(!K)return 5;let N=[];while(!$.done()){let[R,O]=$.readVarInt();if(O!==0)return O;N.push(R)}console.info(`PULL: ${N.length} bags`);let[z,U]=await W.getBodies(G,N);if(U!==0)return U;if(!z)return 17;for(let{seq:R,bodyCph:O}of z){let H={seq:R,bodyCph:O},P=Q.writeStruct(sV,H);if(P!==0)return P}return 0},decodeResp(V){return V.readStructs(sV)}};var tV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarBytes($.bodyCph);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readBytes(T0);if(Q!==0)return M(Q);let[Z,J]=V.readBytes(D0);if(J!==0)return M(J);let[W,I]=V.readVarBytes();if(I!==0)return M(I);let[Y,X]=V.readVarBytes();if(X!==0)return M(X);return q({sig:$,kdm:Z,headCph:W,bodyCph:Y})}};var UV={encode(V,$){let Q=V.writeVarInt($.seq);if(Q!==0)return Q;let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=$.bodyCph?$.bodyCph.length:0,W=V.writeVarInt(J);if(W!==0)return W;if(J>0){if(!$.bodyCph)return 10;V.writeBytes($.bodyCph)}return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return M(Q);let[Z,J]=V.readVarBytes();if(J!==0)return M(J);let[W,I]=V.readVarInt();if(I!==0)return M(I);let Y;if(W>0){let[X,G]=V.readBytes(W);if(G!==0)return M(G);Y=X}return q({seq:$,headCph:Z,bodyCph:Y})}};var FV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readBytes(T0);if(Q!==0)return M(Q);let[Z,J]=V.readBytes(D0);if(J!==0)return M(J);let[W,I]=V.readVarBytes();if(I!==0)return M(I);return q({sig:$,kdm:Z,headCph:W})}};var qV={encode(V,$){if(V.writeVarInt($.idx),V.writeBytes(new Uint8Array([$.status])),$.status===0)V.writeVarInt($.seq);return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return M(Q);let[Z,J]=V.readBytes(1);if(J!==0)return M(J);let W=Z[0];if(W!==0)return q({idx:$,status:W});let[I,Y]=V.readVarInt();if(Y!==0)return M(Y);return q({idx:$,status:W,seq:I})}};var IQ={async encodeReq(V,$,Q,Z,J){let W=J.writeStruct(Q0,Q);if(W!==0)return W;let I=J.writeStructs(tV,Z);if(I!==0)return I;return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:W,notifier:I}=V,[Y,X]=$.readStruct(Q0);if(X!==0)return X;let G=await A0(Y,J,Z);if(G!==0)return G;let{pubKey:K}=Y,[w,N]=await W.hasUser(K);if(N!==0)return N;if(!w)return 5;let[z,U]=$.readStructs(tV);if(U!==0)return U;console.info(`PUSH: ${z.length} bags`);let R=[],O=[];for(let F=0;F<z.length;F++){let A=z[F];if(!await $Q(A,K,J)){let S={idx:F,status:3},E=Q.writeStruct(qV,S);if(E!==0)return E;continue}R.push(F),O.push(A)}let[H,P]=await W.setBags(K,O);if(P!==0)return P;if(!H||H.length!==O.length)return 17;let D=[];for(let F=0;F<O.length;F++){let A=O[F],m=R[F],S=H[F],E=new k,L=E.writeStruct(FV,A);if(L!==0)return L;let f=E.result(),C={seq:S,headCph:f};if(z.length===1&&A.bodyCph.length<=VQ)C.bodyCph=A.bodyCph;D.push(C);let g={idx:m,status:0,seq:S},v=Q.writeStruct(qV,g);if(v!==0)return v}if(D.length>0){let F=new k,A=F.writeStructs(UV,D);if(A!==0)return A;let m=F.result();await Promise.resolve(I.push(K,m))}return 0},decodeResp(V){return V.readStructs(qV)}};var YQ={async encodeReq(V,$,Q,Z,J){return J.writeStruct(Q0,Q)},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:W}=V,[I,Y]=$.readStruct(Q0);if(Y!==0)return Y;let X=await A0(I,J,Z);if(X!==0)return X;let{pubKey:G}=I;if(!$.done())return 8;let[K,w]=await W.addUser(G);if(w!==0)return w;return 0},decodeResp(V){return q(void 0)}};class eV{url;websocket;constructor(V){this.url=V}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(V,$,Q=()=>{},Z=()=>{}){let{url:J}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let W=new k;W.writeStruct(Q0,V);let I=W.result(),Y=o(I);return J.searchParams.set("t",Y),this.websocket=new WebSocket(J),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),Z()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Q()},this.websocket.onmessage=(X)=>{let G=new Uint8Array(X.data);$(G)},this.websocket.onerror=(X)=>{console.log(`ERROR: ${JSON.stringify(X)}`),this.websocket=void 0,Q()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var h={user:{path:"/user",endpoint:YQ,name:0},push:{path:"/push",endpoint:IQ,name:2},peek:{path:"/peek",endpoint:JQ,name:1},pull:{path:"/pull",endpoint:WQ,name:3}},_Z={0:h.user,2:h.push,1:h.peek,3:h.pull},qY={[h.user.path]:h.user,[h.push.path]:h.push,[h.peek.path]:h.peek,[h.pull.path]:h.pull};class V${url;listener;constructor(V){this.url=V;this.listener=new eV(V)}async call(V,$){let{path:Q}=_Z[V],Z=new URL(Q,this.url);try{return await jZ(Z,$)}catch{return M(25)}}}var OV=(V)=>{return new V$(V.handle)};async function jZ(V,$){let Q=await fetch(V,{method:"POST",body:$.result().slice()});if(!Q.ok)return M(24);let Z=await B.fromResponse(Q);return q(Z)}class HV{enclave;crypto;host;clock;transport;updateHostMeta;constructor(V,$,Q,Z,J,W){this.enclave=V;this.crypto=$;this.host=Q;this.clock=Z;this.transport=J;this.updateHostMeta=W}async call(V,$){let{clock:Q,crypto:Z,transport:J}=this,{endpoint:W,name:I}=V,Y=await this.keys(),X=Q.now(),[G,K]=await lV(Y,X,Z);if(K!==0)return M(K);let w=new k,N=await W.encodeReq(this,Y,G,$,w);if(N!==0)return M(N);let z=Q.now(),[U,R]=await J.call(I,w),O=Q.now();if(R!==0)return M(R);let[H,P]=U.readStruct(dV);if(P!==0)return M(P);if(H.status!==0)return M(H.status);let F={clockOffset:ZQ(z,H.timeRcvd,H.timeSent,O),subscription:H.subscription},A=await this.updateHostMeta(F);if(A!==0)return M(A);return W.decodeResp(U)}keys=()=>{let{host:V}=this;return oV(this,V.label,V.idx)};seal=async(V)=>{let{crypto:$,enclave:Q}=this,Z=await this.keys();return QQ(V,Z,$,Q)};register=()=>this.call(h.user,[]);peek=(V)=>this.call(h.peek,[V]);push=(V)=>this.call(h.push,V);pull=(V)=>this.call(h.pull,V);listen=async(V,$,Q)=>{let{clock:Z,crypto:J,host:W,transport:I}=this,{listener:Y}=I,X=await oV(this,W.label,W.idx),G=Z.now(),[K,w]=await lV(X,G,J);if(w!==0)return w;return await Y.connect(K,V,$,Q)};isConnected(){let V=this.transport?.listener;if(V&&typeof V.connected==="function")return V.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var $$={encode(V,$){let Q=V.writeVarString($.lbl);if(Q!==0)return Q;let Z=V.writeVarInt($.idx);if(Z!==0)return Z;let J=V.writeVarInt($.num);if(J!==0)return J;return V.writeBytes($.hsh),V.writeBytes($.sig),0},decode(V){let[$,Q]=V.readVarString();if(Q!==0)return M(Q);let[Z,J]=V.readVarInt();if(J!==0)return M(J);let[W,I]=V.readVarInt();if(I!==0)return M(I);let[Y,X]=V.readBytes(zV);if(X!==0)return M(X);let[G,K]=V.readBytes(T0);if(K!==0)return M(K);return q({lbl:$,idx:Z,num:W,hsh:Y,sig:G})}};var Q$={encode(V,$){let Q=V.writeStruct($$,$.head);if(Q!==0)return Q;let Z=V.writeVarBytes($.indexEnc);if(Z!==0)return Z;let J=V.writeVarBytes($.bodyEnc);if(J!==0)return J;return 0},decode(V){let[$,Q]=V.readStruct($$);if(Q!==0)return M(Q);let[Z,J]=V.readVarBytes();if(J!==0)return M(J);let[W,I]=V.readVarBytes();if(I!==0)return M(I);return q({head:$,indexEnc:Z,bodyEnc:W})}};var Z$={encode(V,$){V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarInt($.lenBody);if(Z!==0)return Z;if($.lenBody>0&&$.offBody!==void 0){let J=V.writeVarInt($.offBody);if(J!==0)return J}return 0},decode(V){let[$,Q]=V.readBytes(D0);if(Q!==0)return M(Q);let[Z,J]=V.readVarBytes();if(J!==0)return M(J);let[W,I]=V.readVarInt();if(I!==0)return M(I);let Y;if(W>0){let[X,G]=V.readVarInt();if(G!==0)return M(G);Y=X}return q({kdm:$,headCph:Z,lenBody:W,offBody:Y})}};async function XQ(V,$,Q,Z,J){let W=await J.derive(V,$),I=await Z.deriveEd25519KeyPair(W),Y=new k,X=new k,G=0,K=0;for(let P of Q){let D=new k,F=D.writeStruct(I0,P.head);if(F!==0)return M(F);let A=D.result(),m=await hV(A,I,Z),S=await J.deriveFromKDM(m),E=await Z.encryptXSalsa20Poly1305Combined(A,S),L=P.body?await Z.encryptXSalsa20Poly1305Combined(P.body,S):new Uint8Array(0),f=P.head.len>0&&P.head.hsh!==void 0?L.length:0,C={kdm:m,headCph:E,lenBody:f,offBody:f>0?K:void 0},g=Y.writeStruct(Z$,C);if(g!==0)return M(g);if(P.body)X.writeBytes(L),K+=L.length;G++}let w=X.result(),N=Y.result(),z=await Z.blake3(N),U=await Z.signEd25519(z,I.privateKey),R={lbl:V,idx:$,num:G,hsh:z,sig:U},O=new k;O.writeStruct(Q$,{head:R,indexEnc:N,bodyEnc:w});let H=O.result();return q(H)}async function GQ(V,$,Q){let[Z,J]=Q$.decode(new B(V));if(J!==0)return M(J);let{head:W,indexEnc:I,bodyEnc:Y}=Z,X=await Q.derive(W.lbl,W.idx),G=await $.deriveEd25519KeyPair(X);if(!await $.checkSigEd25519(W.sig,W.hsh,G.publicKey))return M(3);let w=await $.blake3(I);if(!X0(w,W.hsh))return M(19);let N=new B(I),z=[];for(let R=0;R<W.num;R++){let[O,H]=N.readStruct(Z$);if(H!==0)return M(H);z.push(O)}if(z.length!==W.num)return M(14);let U=[];for(let R of z){let O=await Q.deriveFromKDM(R.kdm),H=await $.decryptXSalsa20Poly1305Combined(R.headCph,O),[P,D]=I0.decode(new B(H));if(D!==0)return M(D);let F;if(R.lenBody>0&&R.offBody!==void 0){if(P.hsh===void 0)return M(14);let A=Y.slice(R.offBody,R.offBody+R.lenBody);F=await $.decryptXSalsa20Poly1305Combined(A,O);let m=await $.blake3(F);if(!X0(m,P.hsh))return M(19)}U.push({head:P,body:F})}return q(U)}async function KQ({now:V,bod:$,crypto:Q}){let Z=await Q.genRandomBytes(8),J=new k,W=J.writeStruct(t,{id:Z,ts:V});if(W!==0)return M(W);let I=J.result();return PV({now:V,eid:I,ctr:0,bod:$,crypto:Q})}async function PV({now:V,eid:$,ctr:Q,bod:Z,crypto:J}){let W=new B($),[I,Y]=t.decode(W);if(Y!==0)return M(Y);let X=V.getTime()-I.ts.getTime(),G,K=Z?.length??0;if(Z&&K>0)G=await J.blake3(Z);return q({eid:$,off:X,ctr:Q,len:K,hsh:G})}class CV{inflight=null;again=!1;run(V){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain(V),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain(V){try{this.again=!1;let $=await V();while(this.again)this.again=!1,$=await V();return $}finally{this.inflight=null}}}var TV=100;class $V{timer=null;delayMs;work;tail=new CV;constructor(V,$){this.delayMs=V<0?0:V,this.work=$}schedule(){if(this.delayMs<=0){this.fire();return}if(this.timer!==null)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=null,this.fire()},this.delayMs)}async flush(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null,this.fire();await this.tail.flush()}cancel(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null}fire(){return this.tail.run(this.work)}}function MQ(V){let $=new B(V.eid),[Q,Z]=t.decode($);if(Z!==0)return;return Q.ts.getTime()+V.off}function mZ(V,$){let Q=MQ(V),Z=MQ($);if(Q===void 0&&Z===void 0)return 0;if(Q===void 0)return 1;if(Z===void 0)return-1;if(Z!==Q)return Z-Q;return $.ctr-V.ctr}function QV(V,$){return V.slice().sort((Q,Z)=>mZ($(Q),$(Z)))}var p0={phase:"idle"},ZV=50;function J$(V,$,Q){if(V<=0||$<=0)return!1;if(V===1||V===$)return!0;return V%Q===0}function DV(V,$){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(V,$);return}let Q=URL.createObjectURL(V),Z=document.createElement("a");Z.href=Q,Z.download=$,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(Q)}function wQ(V,$,Q){let Z=[],J=[],W=0;for(let I of V){let Y=$(I);if(J.length>0&&W+Y>Q)Z.push(J),J=[],W=0;if(J.push(I),W+=Y,W>=Q)Z.push(J),J=[],W=0}if(J.length>0)Z.push(J);return Z}async function NQ(V,$,Q){let Z=V.length;if(Z<1)return[];let J=Array(Z),W=0,I=Math.min(Math.max(1,$),Z),Y=async()=>{while(!0){let G=W;if(W+=1,G>=Z)return;J[G]=await Q(V[G],G)}},X=[];for(let G=0;G<I;G++)X.push(Y());return await Promise.all(X),J}async function W$(V,$,Q,Z){let J=new B(V.headCph),[W,I]=J.readStruct(FV);if(I!==0)return M(I);let{sig:Y,kdm:X,headCph:G}=W;if(!await Z.checkSigEd25519(Y,G,$.publicKey))return M(3);let w=await Q.deriveFromKDM(X),N;try{N=await Z.decryptXSalsa20Poly1305Combined(G,w)}catch{return M(20)}return q({kdm:X,headEnc:N})}var z0="f",j0="t",K0="e";function LZ(V){return V===z0||V===j0||V===K0}function JV(V){if(V===!0||V===j0)return j0;if(V===K0)return K0;return z0}function SZ(V){return JV(V.apld)===z0}function I$(V){return V!==0&&V!==15&&V!==18&&V!==17}function L0(V,$,Q){if(V.apld=$,$===K0&&Q!==void 0)V.err=Q;else delete V.err}async function m0(V,$,Q){let Z=JV($.apld),J=$.body,W=J?.length??0,I;if(J&&W>0)I=await Q.blake3(J);let Y={eid:$.eid,off:$.off??0,ctr:$.ctr??0,len:W,hsh:I},X={hash:V,head:Y,apld:Z};if(J!==void 0)X.body=J;if(Z===K0&&$.err!==void 0)X.err=$.err;return X}var Y$=1048576,X$=1048576,EZ=64;function xZ(V){return V.sig.length+V.kdm.length+V.headCph.length+V.bodyCph.length}async function kZ(V,$,Q,Z,J){if(Z.length<1)return 0;let[W,I]=await V.push(Z);if(I!==0)return I;if(!W)return 27;for(let X of W){if(X.status!==0){console.error("push err",X);continue}let G=J[X.idx];if(!G){console.error("no hash",X);continue}await $.uploads.deq(Q,[G])}let Y=await $.hosts.get(Q);if(Y){let X=Y.lastSeq,G=X,K=[];for(let w of W)if(w.status===0)K.push(w.seq);K.sort((w,N)=>w-N);for(let w of K)if(w===X+1)X=w;if(X>G)await $.hosts.touch(Q,X)}return 0}async function RQ(V,$){if($.length<1)return q([]);let Q=new Map,Z=[];for(let Y of $)Q.set(Y.seq,Y),Z.push(Y.seq);let[J,W]=await V.pull(Z);if(W!==0)return M(W);if(!J)return M(27);let I=[];for(let{seq:Y,bodyCph:X}of J){let G=Q.get(Y);if(!G)continue;I.push({dl:G,bodyCph:X})}return q(I)}async function fZ(V,$,Q,Z){if(Z.length<1)return q({parts:[],hashes:[]});let J=[],W=[],I=[],Y=new Map;for(let{dl:G,bodyCph:K}of Z){let{head:w,kdm:N,seq:z,host:U}=G,[R,O]=await zQ(G,Q);if(O!==0||!R){let L=Y.get(U)??[];L.push(z),Y.set(U,L);continue}let{headEnc:H,headEncHash:P}=R,D=await $.deriveFromKDM(N),[F,A]=await cV(H,K,D,Q,P);if(A!==0||!F){let L=Y.get(U)??[];L.push(z),Y.set(U,L);continue}let m={head:w,body:F.bod},S=F.headHash;I.push({key:S,data:HQ(m)}),J.push(m),W.push(S);let E=Y.get(U)??[];E.push(z),Y.set(U,E)}let X=await V.messages.add(I);for(let[G,K]of Y)await V.downloads.deq(G,K);for(let G=0;G<X.length;G++){let K=X[G];if(K!==0&&K!==15)console.error("ERR storing",_[K],"for message",G)}return q({parts:J,hashes:W})}async function zQ(V,$){let Q=V.headEnc;if(!Q){let J=new k,W=J.writeStruct(I0,V.head);if(W!==0)return M(W);Q=J.result()}if(V.headEncHash)return q({headEnc:Q,headEncHash:V.headEncHash});let Z=await $.blake3(Q);return q({headEnc:Q,headEncHash:Z})}async function UQ(V,$,Q){let Z=new Set;for(let I of $)Z.add(x(I));if(Z.size<1)return;let J=Array.from(await V.downloads.list());if(J.length<1)return;let W=new Map;for(let I of J){let Y;if(I.headEncHash)Y=x(I.headEncHash);else{let[G,K]=await zQ(I,Q);if(K!==0||!G)continue;Y=x(G.headEncHash)}if(!Z.has(Y))continue;let X=W.get(I.host)??[];X.push(I.seq),W.set(I.host,X)}for(let[I,Y]of W)await V.downloads.deq(I,Y)}async function FQ({conn:V,store:$,enclave:Q,host:Z,crypto:J,onProgress:W,peekProgressEvery:I,peekConcurrency:Y}){let X=await V.keys(),G=[],[K,w]=await V.peek(Z.lastSeq);if(w!==0)return w;let N=K.length,z=I??ZV,U=Y??EZ;if(W&&N>0)W({phase:"peek",host:Z.label,done:0,total:N});let R=0,O=await NQ(K,U,async(H)=>{let[P,D]=await W$(H,X,Q,J),F;if(D!==0||!P)F={ok:!1,seq:H.seq,stat:D};else{let A=await J.blake3(P.headEnc);F={ok:!0,seq:H.seq,kdm:P.kdm,headEnc:P.headEnc,headEncHash:A}}if(R+=1,W&&J$(R,N,z))W({phase:"peek",host:Z.label,done:R,total:N});return F});for(let H of O){if(!H.ok){console.error("peek: decrypting item head",H.stat);continue}if(await $.messages.has(H.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await $.uploads.deq(Z.label,[H.headEncHash]),await $.downloads.deq(Z.label,[H.seq]);continue}let D=new B(H.headEnc),[F,A]=D.readStruct(I0);if(A!==0){console.error("peek: reading item head",A);continue}G.push({kdm:H.kdm,head:F,seq:H.seq,host:Z.label,headEnc:H.headEnc,headEncHash:H.headEncHash})}if(await $.downloads.enq(G),K.length>0){let H=Math.max(...K.map((P)=>P.seq));await $.hosts.touch(Z.label,H)}if(W)W({phase:"peek",host:Z.label,done:N,total:N});return 0}async function qQ({conn:V,store:$,host:Q,maxPushBytes:Z,onProgress:J}){let W=Z??Y$,I=await $.uploads.list(Q.label),Y=I.length,X=0;if(J&&Y>0)J({phase:"push",host:Q.label,done:0,total:Y});let G=[],K=[],w=0,N=async()=>{if(G.length<1)return 0;let z=G.length,U=await kZ(V,$,Q.label,G,K);if(G=[],K=[],w=0,U===0){if(X+=z,J)J({phase:"push",host:Q.label,done:X,total:Y})}return U};for(let z of I){let U=await $.messages.get(z);if(!U){X+=1;continue}let R={...U.head,bod:U.body},[O,H]=await V.seal(R);if(H!==0)return H;if(!O)return 12;let P=xZ(O);if(G.length>0&&w+P>W){let D=await N();if(D!==0)return D}if(G.push(O),K.push(z),w+=P,w>=W){let D=await N();if(D!==0)return D}}return N()}async function OQ({conn:V,store:$,enclave:Q,host:Z,crypto:J,maxPullBytes:W,onProgress:I},Y){let X=W??X$,G=await $.downloads.list(),K=Array.from(G).filter((O)=>O.host===Z.label);if(K.length<1)return 15;let w=QV(K,(O)=>O.head),N=wQ(w,(O)=>O.head.len,X),z=w.length,U=0;if(I)I({phase:"pull",host:Z.label,done:0,total:z});let R=RQ(V,N[0]);for(let O=0;O<N.length;O++){let[H,P]=await R;if(P!==0||!H)return P;if(U+=N[O].length,I)I({phase:"pull",host:Z.label,done:U,total:z});let D=N[O+1];if(D)R=RQ(V,D);if(I)I({phase:"open",host:Z.label,done:U,total:z});let F=QV(H,(m)=>m.dl.head),[,A]=await fZ($,Q,J,F);if(A!==0)return A;if(Y){if(I)I({phase:"exec",host:Z.label,done:U,total:z});await Y()}}return 0}function HQ({head:V,body:$}){let Q={eid:V.eid,body:$,apld:z0};if(V.off!==0)Q.off=V.off;if(V.ctr!==0)Q.ctr=V.ctr;return Q}async function PQ(V,{conn:$,store:Q,enclave:Z,host:J,crypto:W,onProgress:I},Y){let X=J.label,G=await $.keys(),K=new B(V),[w,N]=K.readStructs(UV);if(N!==0){console.error("Failed decoding notif",_[N]);return}let z=!1,R=(await Q.hosts.get(X))?.lastSeq,O=[],H=!1;for(let F of w){let[A,m]=await W$({seq:F.seq,headCph:F.headCph},G,Z,W);if(m!==0){console.error("Failed decrypting notif",_[m]);continue}let S=await W.blake3(A.headEnc);if(await Q.messages.has(S))continue;let E=new B(A.headEnc),[L,f]=E.readStruct(I0);if(f!==0){console.error("Failed to parse head",_[f]);continue}if(!F.bodyCph&&L.len>0)H=!0,await Q.downloads.enq([{seq:F.seq,host:X,kdm:A.kdm,head:L,headEnc:A.headEnc,headEncHash:S}]);else O.push({...A,head:L,bodyCph:F.bodyCph,headEncHash:S});if(R===void 0||F.seq!==R+1)console.log("out of seq",F.seq,R),z=!0;else R=F.seq}if(R!==void 0)await Q.hosts.touch(J.label,R);let P=[];for(let F of O){let A=await Z.deriveFromKDM(F.kdm),[m,S]=await cV(F.headEnc,F.bodyCph,A,W);if(S!==0){console.error("Failed to open body",_[S]);continue}P.push({key:F.headEncHash,data:HQ({head:F.head,body:m.bod})})}let D=await Q.messages.add(P);for(let F=0;F<D.length;F++){let A=D[F];if(A!==0&&A!==15)console.error("ERR storing",_[A],"for message",F)}if(I&&P.length>0)I({phase:"open",host:J.label,done:P.length,total:P.length});if(z||H||P.length>0)Y()}class S0{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new CV;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=ZV;lastProgress=p0;scheduledSync;constructor(V,$,Q,Z,J,W=!0,I=Y$,Y=X$,X){this.clock=V;this.state=$;this.store=Q;this.transport=Z;this.crypto=J;this.forceSkewHandlingByDefault=W;this.onScheduleSync=X;this.maxPushBytes=I,this.maxPullBytes=Y,this.clientState=new G0(()=>this.getClientState()),this.xferState=new G0(()=>this.getXferState()),this.scheduledSync=new $V(TV,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(G){console.error("Debounced sync failed:",G)}})}emitProgress=(V)=>{this.lastProgress=V,this.xferState.emit()};async setSeed(V){await this.store.seed.save(V),this.clientState.emit()}async getClientState(){let{store:V,connections:$}=this,Q=await V.seed.load(),Z=await V.hosts.list(),J=!1;for(let W of $.values())if(W.isConnected()){J=!0;break}return{hasSeed:Q!==void 0,hasHost:Array.from(Z).length>0,connected:J}}async getXferState(){let{uploads:V,downloads:$}=this.store,Q=await V.count();return{numDownloads:await $.count(),numUploads:Q,progress:this.lastProgress}}apply=async(V,$={enqueueUpload:!0,triggerUpload:!0})=>{let Q=[],Z=[];for(let{head:W,body:I}of V){let Y=new k;Y.writeStruct(I0,W);let X=Y.result(),G=await this.crypto.blake3(X),K={eid:W.eid,body:I,apld:z0};if(W.off!==0)K.off=W.off;if(W.ctr!==0)K.ctr=W.ctr;Q.push(G),Z.push({key:G,data:K})}await this.store.messages.add(Z),await UQ(this.store,Q,this.crypto);let J=await this.applyHashes(Q);if($.enqueueUpload){let W=[];for(let I=0;I<Q.length;I++){let Y=J[I];if(Y===0||Y===15)W.push(Q[I])}if(W.length>0){let I=await this.store.hosts.list();for(let Y of I)await this.store.uploads.enq(Y.label,W);this.xferState.emit()}}if($.triggerUpload)this.scheduleSync();return J};enqueueApplyJob(V){let $=this.applyChain.then(V,V);return this.applyChain=$.then(()=>{return},()=>{return}),$}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let V=await this.store.messages.list(z0);if(V.length<1)return[];let $=QV(V,(Q)=>Q.head);return this.applyStored($)}applyHashes=(V)=>{return this.enqueueApplyJob(async()=>{let $=[];for(let J of V){let W=await this.store.messages.get(J);if(W)$.push(W)}let Q=await this.applyStored($),Z=new Map;for(let J=0;J<$.length;J++)Z.set(x($[J].hash),Q[J]??12);return V.map((J)=>Z.get(x(J))??13)})};async applyStored(V){if(V.length<1)return[];let $=V.map((W)=>({...W.head,bod:W.body})),Q=await this.state.apply($),Z=[],J=[];for(let W=0;W<V.length;W++){let I=Q[W];if(I===0||I===15)Z.push(V[W].hash);else if(I!==void 0&&I$(I))J.push({key:V[W].hash,err:I})}if(Z.length>0)await this.store.messages.markApplied(Z);if(J.length>0)await this.store.messages.markFailed(J);return Q}async insertRaw(V){let{clock:$,crypto:Q}=this,[Z,J]=await KQ({now:$.now(),bod:V,crypto:Q});if(J!==0)return M(J);return await this.apply([{head:Z,body:V}]),q(Z)}async upsertRaw(V,$,Q=!1){let{clock:Z,crypto:J,store:W}=this,I=Z.now(),Y=await W.messages.last(V);if(Y){let z=new B(V),[U,R]=z.readStruct(t);if(R!==0)return M(R);if(U.ts.getTime()+Y.head.off>I.getTime()){if(Q===!1)return M(4);let H=Y.head.off+1,P=Y.head.ctr+1,D={eid:V,off:H,ctr:P,len:0},A=(await this.apply([{head:D,body:void 0}]))[0];if(A!==0)return M(A);if($===void 0)return q(D);let[m,S]=b0({id:U.id,ts:I});if(S!==0)return M(S);let E={now:I,eid:m,ctr:0,bod:$,crypto:J},[L,f]=await PV(E);if(f!==0)return M(f);let g=(await this.apply([{head:L,body:$}]))[0];if(g!==0)return M(g);return q(L)}}let X=(Y?.head.ctr??-1)+1,[G,K]=await PV({now:I,eid:V,ctr:X,bod:$,crypto:J});if(K!==0)return M(K);let N=(await this.apply([{head:G,body:$}]))[0];if(N!==0)return M(N);return q(G)}async insert(V){let{body:$,type:Q,gid:Z,pid:J}=V,I=wV({body:$,type:Q,gid:Z,pid:J});return this.insertRaw(I)}async upsert(V,$=this.forceSkewHandlingByDefault){let{eid:Q,body:Z,type:J,gid:W,pid:I}=V;if(Q===void 0)return this.insert(V);let X=wV({body:Z,type:J,gid:W,pid:I});return this.upsertRaw(Q,X,$)}async delete(V){return this.upsertRaw(V,void 0,!0)}async genEID(V){let{clock:$,crypto:Q}=this,Z=$.now();if(V!==void 0)return b0({id:V,ts:Z});let J=await Q.genRandomBytes(8);return b0({id:J,ts:Z})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:V,crypto:$,store:Q}=this,Z=await Q.seed.load();if(!Z)return 22;await this.drainApplyQueue();for(let[J,W]of V){let I=await Q.hosts.get(J);if(!I)continue;let Y={conn:W,store:Q,enclave:Z,host:I,crypto:$,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},X=await FQ(Y);if(X!==0)return console.error(`Failed to peek: ${X}`),X;this.xferState.emit();let G=await qQ(Y);if(G!==0)return console.error(`Failed to push: ${G}`),G;this.xferState.emit();let K=await OQ(Y,async()=>{await this.drainApplyQueue()});if(K!==0&&K!==15)return console.error(`Failed to pull: ${K}`),K;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async wipe(){this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush(),await this.store.wipe(),await this.state.clear(),this.lastProgress=p0,this.clientState.emit(),this.xferState.emit()}import=async(V,$)=>{let{crypto:Q,store:Z}=this,J=$?.onProgress,W=await Z.seed.load();if(!W)return 22;console.time("import: decoding file...");let I=await V.bytes(),[Y,X]=await GQ(I,Q,W);if(X!==0)return X;console.timeEnd("import: decoding file...");let G=0;while(G<Y.length){let K=0,w=0,N=G;for(let R=G;R<Y.length&&w<100&&K<102400;R++)K+=Y[R].head.len,w++,N=R+1;let z=Y.slice(G,N);console.time(`import: applying [${G}, ${N}]`);let U=await this.apply(z,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${G}, ${N}]`);for(let R=0;R<z.length;R++){let O=U[R];if(O!==0&&O!==15)console.warn(`failed to import msg ${G+R}: ${_[O]}`)}if(J)queueMicrotask(()=>J(N,Y.length,0));this.emitProgress({phase:"import",done:N,total:Y.length}),G=N}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:V,store:$}=this,Q=await $.seed.load();if(!Q)return M(22);let Z=await $.messages.list();return XQ("export",0,Z,V,Q)}async export(V){let[$,Q]=await this.exportBytes();if(Q!==0)return Q;if(!$)return 12;let Z=new Blob([$.slice()]);return DV(Z,V),0}async link(V,$=!0){if(await this.store.hosts.add(V),this.clientState.emit(),$){let Q=await this.store.hosts.get(V.label);if(Q)await this.connectToHost(Q)}}async unlink(V){await this.store.hosts.del(V),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async(V,$=!0,Q=!0)=>{let{clock:Z,connections:J,crypto:W,store:I,transport:Y}=this,X=J.get(V.label);if(X){if(X.isConnected())return;try{X.closeListener()}catch{}J.delete(V.label)}let G=await I.seed.load();if(!G)return;console.info(`Connecting to ${V.handle} (${V.label})`);let K=new HV(G,W,V,Z,Y(V),(w)=>I.hosts.set(V.label,w));if(await K.register(),$)await K.listen(async(w)=>{let N={conn:K,store:I,enclave:G,host:V,crypto:W,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return PQ(w,N,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(J.set(V.label,K),this.clientState.emit(),Q)this.scheduleSync()};async connect(V=!0,$=!0){let{connectToHost:Q,scheduleSync:Z,store:J}=this;if(!await J.seed.load())return;await this.drainApplyQueue();let I=await J.hosts.list();for(let Y of I)await Q(Y,V,!1);if($)Z()}disconnect=async()=>{for(let V of this.connections.values())try{V.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var E0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function AV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function G$(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function l(V,...$){if(!G$(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function K$(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function CQ(V,$){l(V);let Q=$.outputLen;if(V.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function M$(V){if(typeof V!=="boolean")throw Error(`boolean expected, not ${V}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var U0=(V)=>new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4));var BZ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!BZ)throw Error("Non little-endian hardware is not supported");function gZ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function _V(V){if(typeof V==="string")V=gZ(V);else if(G$(V))V=jV(V);else throw Error("Uint8Array expected, got "+typeof V);return V}function TQ(V,$){if($==null||typeof $!=="object")throw Error("options must be defined");return Object.assign(V,$)}function DQ(V,$){if(V.length!==$.length)return!1;let Q=0;for(let Z=0;Z<V.length;Z++)Q|=V[Z]^$[Z];return Q===0}var AQ=(V,$)=>{function Q(Z,...J){if(l(Z),V.nonceLength!==void 0){let K=J[0];if(!K)throw Error("nonce / iv required");if(V.varSizeNonce)l(K);else l(K,V.nonceLength)}let W=V.tagLength;if(W&&J[1]!==void 0)l(J[1]);let I=$(Z,...J),Y=(K,w)=>{if(w!==void 0){if(K!==2)throw Error("cipher output not supported");l(w)}},X=!1;return{encrypt(K,w){if(X)throw Error("cannot encrypt() twice with same key + nonce");return X=!0,l(K),Y(I.encrypt.length,w),I.encrypt(K,w)},decrypt(K,w){if(l(K),W&&K.length<W)throw Error("invalid ciphertext length: smaller than tagLength="+W);return Y(I.decrypt.length,w),I.decrypt(K,w)}}}return Object.assign(Q,V),Q};function w$(V,$,Q=!0){if($===void 0)return new Uint8Array(V);if($.length!==V)throw Error("invalid output length, expected "+V+", got: "+$.length);if(Q&&!iZ($))throw Error("invalid output, must be aligned");return $}function iZ(V){return V.byteOffset%4===0}function jV(V){return Uint8Array.from(V)}function M0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function mV(V=32){if(E0&&typeof E0.getRandomValues==="function")return E0.getRandomValues(new Uint8Array(V));if(E0&&typeof E0.randomBytes==="function")return E0.randomBytes(V);throw Error("crypto.getRandomValues must be defined")}var jQ=(V)=>Uint8Array.from(V.split("").map(($)=>$.charCodeAt(0))),vZ=jQ("expand 16-byte k"),uZ=jQ("expand 32-byte k"),nZ=U0(vZ),yZ=U0(uZ);function T(V,$){return V<<$|V>>>32-$}function N$(V){return V.byteOffset%4===0}var LV=64,bZ=16,mQ=4294967295,_Q=new Uint32Array;function pZ(V,$,Q,Z,J,W,I,Y){let X=J.length,G=new Uint8Array(LV),K=U0(G),w=N$(J)&&N$(W),N=w?U0(J):_Q,z=w?U0(W):_Q;for(let U=0;U<X;I++){if(V($,Q,Z,K,I,Y),I>=mQ)throw Error("arx: counter overflow");let R=Math.min(LV,X-U);if(w&&R===LV){let O=U/4;if(U%4!==0)throw Error("arx: invalid block position");for(let H=0,P;H<bZ;H++)P=O+H,z[P]=N[P]^K[H];U+=LV;continue}for(let O=0,H;O<R;O++)H=U+O,W[H]=J[H]^G[O];U+=R}}function LQ(V,$){let{allowShortKeys:Q,extendNonceFn:Z,counterLength:J,counterRight:W,rounds:I}=TQ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},$);if(typeof V!=="function")throw Error("core must be a function");return AV(J),AV(I),M$(W),M$(Q),(Y,X,G,K,w=0)=>{l(Y),l(X),l(G);let N=G.length;if(K===void 0)K=new Uint8Array(N);if(l(K),AV(w),w<0||w>=mQ)throw Error("arx: counter overflow");if(K.length<N)throw Error(`arx: output (${K.length}) is shorter than data (${N})`);let z=[],U=Y.length,R,O;if(U===32)z.push(R=jV(Y)),O=yZ;else if(U===16&&Q)R=new Uint8Array(32),R.set(Y),R.set(Y,16),O=nZ,z.push(R);else throw Error(`arx: invalid 32-byte key, got length=${U}`);if(!N$(X))z.push(X=jV(X));let H=U0(R);if(Z){if(X.length!==24)throw Error("arx: extended nonce must be 24 bytes");Z(O,H,U0(X.subarray(0,16)),H),X=X.subarray(16)}let P=16-J;if(P!==X.length)throw Error(`arx: nonce must be ${P} or 16 bytes`);if(P!==12){let F=new Uint8Array(12);F.set(X,W?0:12-X.length),X=F,z.push(X)}let D=U0(X);return pZ(V,O,H,D,G,K,w,I),M0(...z),K}}var c=(V,$)=>V[$++]&255|(V[$++]&255)<<8;class SQ{constructor(V){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,V=_V(V),l(V,32);let $=c(V,0),Q=c(V,2),Z=c(V,4),J=c(V,6),W=c(V,8),I=c(V,10),Y=c(V,12),X=c(V,14);this.r[0]=$&8191,this.r[1]=($>>>13|Q<<3)&8191,this.r[2]=(Q>>>10|Z<<6)&7939,this.r[3]=(Z>>>7|J<<9)&8191,this.r[4]=(J>>>4|W<<12)&255,this.r[5]=W>>>1&8190,this.r[6]=(W>>>14|I<<2)&8191,this.r[7]=(I>>>11|Y<<5)&8065,this.r[8]=(Y>>>8|X<<8)&8191,this.r[9]=X>>>5&127;for(let G=0;G<8;G++)this.pad[G]=c(V,16+2*G)}process(V,$,Q=!1){let Z=Q?0:2048,{h:J,r:W}=this,I=W[0],Y=W[1],X=W[2],G=W[3],K=W[4],w=W[5],N=W[6],z=W[7],U=W[8],R=W[9],O=c(V,$+0),H=c(V,$+2),P=c(V,$+4),D=c(V,$+6),F=c(V,$+8),A=c(V,$+10),m=c(V,$+12),S=c(V,$+14),E=J[0]+(O&8191),L=J[1]+((O>>>13|H<<3)&8191),f=J[2]+((H>>>10|P<<6)&8191),C=J[3]+((P>>>7|D<<9)&8191),g=J[4]+((D>>>4|F<<12)&8191),v=J[5]+(F>>>1&8191),y=J[6]+((F>>>14|A<<2)&8191),b=J[7]+((A>>>11|m<<5)&8191),p=J[8]+((m>>>8|S<<8)&8191),r=J[9]+(S>>>5|Z),j=0,d=j+E*I+L*(5*R)+f*(5*U)+C*(5*z)+g*(5*N);j=d>>>13,d&=8191,d+=v*(5*w)+y*(5*K)+b*(5*G)+p*(5*X)+r*(5*Y),j+=d>>>13,d&=8191;let a=j+E*Y+L*I+f*(5*R)+C*(5*U)+g*(5*z);j=a>>>13,a&=8191,a+=v*(5*N)+y*(5*w)+b*(5*K)+p*(5*G)+r*(5*X),j+=a>>>13,a&=8191;let $0=j+E*X+L*Y+f*I+C*(5*R)+g*(5*U);j=$0>>>13,$0&=8191,$0+=v*(5*z)+y*(5*N)+b*(5*w)+p*(5*K)+r*(5*G),j+=$0>>>13,$0&=8191;let i=j+E*G+L*X+f*Y+C*I+g*(5*R);j=i>>>13,i&=8191,i+=v*(5*U)+y*(5*z)+b*(5*N)+p*(5*w)+r*(5*K),j+=i>>>13,i&=8191;let N0=j+E*K+L*G+f*X+C*Y+g*I;j=N0>>>13,N0&=8191,N0+=v*(5*R)+y*(5*U)+b*(5*z)+p*(5*N)+r*(5*w),j+=N0>>>13,N0&=8191;let f0=j+E*w+L*K+f*G+C*X+g*Y;j=f0>>>13,f0&=8191,f0+=v*I+y*(5*R)+b*(5*U)+p*(5*z)+r*(5*N),j+=f0>>>13,f0&=8191;let B0=j+E*N+L*w+f*K+C*G+g*X;j=B0>>>13,B0&=8191,B0+=v*Y+y*I+b*(5*R)+p*(5*U)+r*(5*z),j+=B0>>>13,B0&=8191;let g0=j+E*z+L*N+f*w+C*K+g*G;j=g0>>>13,g0&=8191,g0+=v*X+y*Y+b*I+p*(5*R)+r*(5*U),j+=g0>>>13,g0&=8191;let i0=j+E*U+L*z+f*N+C*w+g*K;j=i0>>>13,i0&=8191,i0+=v*G+y*X+b*Y+p*I+r*(5*R),j+=i0>>>13,i0&=8191;let v0=j+E*R+L*U+f*z+C*N+g*w;j=v0>>>13,v0&=8191,v0+=v*K+y*G+b*X+p*Y+r*I,j+=v0>>>13,v0&=8191,j=(j<<2)+j|0,j=j+d|0,d=j&8191,j=j>>>13,a+=j,J[0]=d,J[1]=a,J[2]=$0,J[3]=i,J[4]=N0,J[5]=f0,J[6]=B0,J[7]=g0,J[8]=i0,J[9]=v0}finalize(){let{h:V,pad:$}=this,Q=new Uint16Array(10),Z=V[1]>>>13;V[1]&=8191;for(let I=2;I<10;I++)V[I]+=Z,Z=V[I]>>>13,V[I]&=8191;V[0]+=Z*5,Z=V[0]>>>13,V[0]&=8191,V[1]+=Z,Z=V[1]>>>13,V[1]&=8191,V[2]+=Z,Q[0]=V[0]+5,Z=Q[0]>>>13,Q[0]&=8191;for(let I=1;I<10;I++)Q[I]=V[I]+Z,Z=Q[I]>>>13,Q[I]&=8191;Q[9]-=8192;let J=(Z^1)-1;for(let I=0;I<10;I++)Q[I]&=J;J=~J;for(let I=0;I<10;I++)V[I]=V[I]&J|Q[I];V[0]=(V[0]|V[1]<<13)&65535,V[1]=(V[1]>>>3|V[2]<<10)&65535,V[2]=(V[2]>>>6|V[3]<<7)&65535,V[3]=(V[3]>>>9|V[4]<<4)&65535,V[4]=(V[4]>>>12|V[5]<<1|V[6]<<14)&65535,V[5]=(V[6]>>>2|V[7]<<11)&65535,V[6]=(V[7]>>>5|V[8]<<8)&65535,V[7]=(V[8]>>>8|V[9]<<5)&65535;let W=V[0]+$[0];V[0]=W&65535;for(let I=1;I<8;I++)W=(V[I]+$[I]|0)+(W>>>16)|0,V[I]=W&65535;M0(Q)}update(V){K$(this);let{buffer:$,blockLen:Q}=this;V=_V(V);let Z=V.length;for(let J=0;J<Z;){let W=Math.min(Q-this.pos,Z-J);if(W===Q){for(;Q<=Z-J;J+=Q)this.process(V,J);continue}if($.set(V.subarray(J,J+W),this.pos),this.pos+=W,J+=W,this.pos===Q)this.process($,0,!1),this.pos=0}return this}destroy(){M0(this.h,this.r,this.buffer,this.pad)}digestInto(V){K$(this),CQ(V,this),this.finished=!0;let{buffer:$,h:Q}=this,{pos:Z}=this;if(Z){$[Z++]=1;for(;Z<16;Z++)$[Z]=0;this.process($,0,!0)}this.finalize();let J=0;for(let W=0;W<8;W++)V[J++]=Q[W]>>>0,V[J++]=Q[W]>>>8;return V}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Q=V.slice(0,$);return this.destroy(),Q}}function rZ(V){let $=(Z,J)=>V(J).update(_V(Z)).digest(),Q=V(new Uint8Array(32));return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=(Z)=>V(Z),$}var R$=rZ((V)=>new SQ(V));function lZ(V,$,Q,Z,J,W=20){let I=V[0],Y=$[0],X=$[1],G=$[2],K=$[3],w=V[1],N=Q[0],z=Q[1],U=J,R=0,O=V[2],H=$[4],P=$[5],D=$[6],F=$[7],A=V[3],m=I,S=Y,E=X,L=G,f=K,C=w,g=N,v=z,y=U,b=R,p=O,r=H,j=P,d=D,a=F,$0=A;for(let N0=0;N0<W;N0+=2)f^=T(m+j|0,7),y^=T(f+m|0,9),j^=T(y+f|0,13),m^=T(j+y|0,18),b^=T(C+S|0,7),d^=T(b+C|0,9),S^=T(d+b|0,13),C^=T(S+d|0,18),a^=T(p+g|0,7),E^=T(a+p|0,9),g^=T(E+a|0,13),p^=T(g+E|0,18),L^=T($0+r|0,7),v^=T(L+$0|0,9),r^=T(v+L|0,13),$0^=T(r+v|0,18),S^=T(m+L|0,7),E^=T(S+m|0,9),L^=T(E+S|0,13),m^=T(L+E|0,18),g^=T(C+f|0,7),v^=T(g+C|0,9),f^=T(v+g|0,13),C^=T(f+v|0,18),r^=T(p+b|0,7),y^=T(r+p|0,9),b^=T(y+r|0,13),p^=T(b+y|0,18),j^=T($0+a|0,7),d^=T(j+$0|0,9),a^=T(d+j|0,13),$0^=T(a+d|0,18);let i=0;Z[i++]=I+m|0,Z[i++]=Y+S|0,Z[i++]=X+E|0,Z[i++]=G+L|0,Z[i++]=K+f|0,Z[i++]=w+C|0,Z[i++]=N+g|0,Z[i++]=z+v|0,Z[i++]=U+y|0,Z[i++]=R+b|0,Z[i++]=O+p|0,Z[i++]=H+r|0,Z[i++]=P+j|0,Z[i++]=D+d|0,Z[i++]=F+a|0,Z[i++]=A+$0|0}function hZ(V,$,Q,Z){let J=V[0],W=$[0],I=$[1],Y=$[2],X=$[3],G=V[1],K=Q[0],w=Q[1],N=Q[2],z=Q[3],U=V[2],R=$[4],O=$[5],H=$[6],P=$[7],D=V[3];for(let A=0;A<20;A+=2)X^=T(J+O|0,7),N^=T(X+J|0,9),O^=T(N+X|0,13),J^=T(O+N|0,18),z^=T(G+W|0,7),H^=T(z+G|0,9),W^=T(H+z|0,13),G^=T(W+H|0,18),P^=T(U+K|0,7),I^=T(P+U|0,9),K^=T(I+P|0,13),U^=T(K+I|0,18),Y^=T(D+R|0,7),w^=T(Y+D|0,9),R^=T(w+Y|0,13),D^=T(R+w|0,18),W^=T(J+Y|0,7),I^=T(W+J|0,9),Y^=T(I+W|0,13),J^=T(Y+I|0,18),K^=T(G+X|0,7),w^=T(K+G|0,9),X^=T(w+K|0,13),G^=T(X+w|0,18),R^=T(U+z|0,7),N^=T(R+U|0,9),z^=T(N+R|0,13),U^=T(z+N|0,18),O^=T(D+P|0,7),H^=T(O+D|0,9),P^=T(H+O|0,13),D^=T(P+H|0,18);let F=0;Z[F++]=J,Z[F++]=G,Z[F++]=U,Z[F++]=D,Z[F++]=K,Z[F++]=w,Z[F++]=N,Z[F++]=z}var z$=LQ(lZ,{counterRight:!0,extendNonceFn:hZ}),U$=AQ({blockSize:64,nonceLength:24,tagLength:16},(V,$)=>{return{encrypt(Q,Z){Z=w$(Q.length+32,Z,!1);let J=Z.subarray(0,32),W=Z.subarray(32);Z.set(Q,32),M0(J),z$(V,$,Z,Z);let I=R$(W,J);return Z.set(I,16),M0(Z.subarray(0,16),I),Z.subarray(16)},decrypt(Q,Z){l(Q),Z=w$(Q.length+32,Z,!1);let J=Z.subarray(0,32),W=Z.subarray(32,48),I=Z.subarray(48);Z.set(Q,32),M0(J);let Y=z$(V,$,J,J),X=R$(I,Y);if(!DQ(W,X))throw Error("invalid tag");return z$(V,$,Z.subarray(16),Z.subarray(16)),M0(J,W,X),I}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function cZ(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function WV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function x0(V,...$){if(!cZ(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function IV(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function SV(V,$){x0(V);let Q=$.outputLen;if(V.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function EQ(V){return new Uint8Array(V.buffer,V.byteOffset,V.byteLength)}function r0(V){return new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4))}function l0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function YV(V,$){return V<<32-$|V>>>$}var xQ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function kQ(V){return V<<24&4278190080|V<<8&16711680|V>>>8&65280|V>>>24&255}var fQ=xQ?(V)=>V:(V)=>kQ(V);function dZ(V){for(let $=0;$<V.length;$++)V[$]=kQ(V[$]);return V}var e=xQ?(V)=>V:dZ;function oZ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function h0(V){if(typeof V==="string")V=oZ(V);return x0(V),V}class F${}function BQ(V){let $=(Z,J)=>V(J).update(h0(Z)).digest(),Q=V({});return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=(Z)=>V(Z),$}var gQ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var EV=BigInt(4294967295),iQ=BigInt(32);function q$(V,$=!1){if($)return{h:Number(V&EV),l:Number(V>>iQ&EV)};return{h:Number(V>>iQ&EV)|0,l:Number(V&EV)|0}}function F0(V,$,Q,Z,J){return V=V+$+J|0,Z=YV(Z^V,16),Q=Q+Z|0,$=YV($^Q,12),{a:V,b:$,c:Q,d:Z}}function q0(V,$,Q,Z,J){return V=V+$+J|0,Z=YV(Z^V,8),Q=Q+Z|0,$=YV($^Q,7),{a:V,b:$,c:Q,d:Z}}class O$ extends F${constructor(V,$){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,WV(V),WV($),this.blockLen=V,this.outputLen=$,this.buffer=new Uint8Array(V),this.buffer32=r0(this.buffer)}update(V){IV(this),V=h0(V),x0(V);let{blockLen:$,buffer:Q,buffer32:Z}=this,J=V.length,W=V.byteOffset,I=V.buffer;for(let Y=0;Y<J;){if(this.pos===$)e(Z),this.compress(Z,0,!1),e(Z),this.pos=0;let X=Math.min($-this.pos,J-Y),G=W+Y;if(X===$&&!(G%4)&&Y+X<J){let K=new Uint32Array(I,G,Math.floor((J-Y)/4));e(K);for(let w=0;Y+$<J;w+=Z.length,Y+=$)this.length+=$,this.compress(K,w,!1);e(K);continue}Q.set(V.subarray(Y,Y+X),this.pos),this.pos+=X,this.length+=X,Y+=X}return this}digestInto(V){IV(this),SV(V,this);let{pos:$,buffer32:Q}=this;this.finished=!0,l0(this.buffer.subarray($)),e(Q),this.compress(Q,0,!0),e(Q);let Z=r0(V);this.get().forEach((J,W)=>Z[W]=fQ(J))}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Q=V.slice(0,$);return this.destroy(),Q}_cloneInto(V){let{buffer:$,length:Q,finished:Z,destroyed:J,outputLen:W,pos:I}=this;return V||(V=new this.constructor({dkLen:W})),V.set(...this.get()),V.buffer.set($),V.destroyed=J,V.finished=Z,V.length=Q,V.pos=I,V.outputLen=W,V}clone(){return this._cloneInto()}}function H$(V,$,Q,Z,J,W,I,Y,X,G,K,w,N,z,U,R,O,H,P,D){let F=0;for(let A=0;A<Z;A++)({a:J,b:X,c:N,d:O}=F0(J,X,N,O,Q[$+V[F++]])),{a:J,b:X,c:N,d:O}=q0(J,X,N,O,Q[$+V[F++]]),{a:W,b:G,c:z,d:H}=F0(W,G,z,H,Q[$+V[F++]]),{a:W,b:G,c:z,d:H}=q0(W,G,z,H,Q[$+V[F++]]),{a:I,b:K,c:U,d:P}=F0(I,K,U,P,Q[$+V[F++]]),{a:I,b:K,c:U,d:P}=q0(I,K,U,P,Q[$+V[F++]]),{a:Y,b:w,c:R,d:D}=F0(Y,w,R,D,Q[$+V[F++]]),{a:Y,b:w,c:R,d:D}=q0(Y,w,R,D,Q[$+V[F++]]),{a:J,b:G,c:U,d:D}=F0(J,G,U,D,Q[$+V[F++]]),{a:J,b:G,c:U,d:D}=q0(J,G,U,D,Q[$+V[F++]]),{a:W,b:K,c:R,d:O}=F0(W,K,R,O,Q[$+V[F++]]),{a:W,b:K,c:R,d:O}=q0(W,K,R,O,Q[$+V[F++]]),{a:I,b:w,c:N,d:H}=F0(I,w,N,H,Q[$+V[F++]]),{a:I,b:w,c:N,d:H}=q0(I,w,N,H,Q[$+V[F++]]),{a:Y,b:X,c:z,d:P}=F0(Y,X,z,P,Q[$+V[F++]]),{a:Y,b:X,c:z,d:P}=q0(Y,X,z,P,Q[$+V[F++]]);return{v0:J,v1:W,v2:I,v3:Y,v4:X,v5:G,v6:K,v7:w,v8:N,v9:z,v10:U,v11:R,v12:O,v13:H,v14:P,v15:D}}var w0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},O0=gQ.slice(),vQ=(()=>{let V=Array.from({length:16},(Z,J)=>J),$=(Z)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((J)=>Z[J]),Q=[];for(let Z=0,J=V;Z<7;Z++,J=$(J))Q.push(...J);return Uint8Array.from(Q)})();class P$ extends O${constructor(V={},$=0){super(64,V.dkLen===void 0?32:V.dkLen);this.chunkPos=0,this.chunksDone=0,this.flags=0,this.stack=[],this.posOut=0,this.bufferOut32=new Uint32Array(16),this.chunkOut=0,this.enableXOF=!0;let{key:Q,context:Z}=V,J=Z!==void 0;if(Q!==void 0){if(J)throw Error('Only "key" or "context" can be specified at same time');let W=h0(Q).slice();x0(W,32),this.IV=r0(W),e(this.IV),this.flags=$|w0.KEYED_HASH}else if(J){let W=h0(Z),I=new P$({dkLen:32},w0.DERIVE_KEY_CONTEXT).update(W).digest();this.IV=r0(I),e(this.IV),this.flags=$|w0.DERIVE_KEY_MATERIAL}else this.IV=O0.slice(),this.flags=$;this.state=this.IV.slice(),this.bufferOut=EQ(this.bufferOut32)}get(){return[]}set(){}b2Compress(V,$,Q,Z=0){let{state:J,pos:W}=this,{h:I,l:Y}=q$(BigInt(V),!0),{v0:X,v1:G,v2:K,v3:w,v4:N,v5:z,v6:U,v7:R,v8:O,v9:H,v10:P,v11:D,v12:F,v13:A,v14:m,v15:S}=H$(vQ,Z,Q,7,J[0],J[1],J[2],J[3],J[4],J[5],J[6],J[7],O0[0],O0[1],O0[2],O0[3],I,Y,W,$);J[0]=X^O,J[1]=G^H,J[2]=K^P,J[3]=w^D,J[4]=N^F,J[5]=z^A,J[6]=U^m,J[7]=R^S}compress(V,$=0,Q=!1){let Z=this.flags;if(!this.chunkPos)Z|=w0.CHUNK_START;if(this.chunkPos===15||Q)Z|=w0.CHUNK_END;if(!Q)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,Z,V,$),this.chunkPos+=1,this.chunkPos===16||Q){let J=this.state;this.state=this.IV.slice();for(let W,I=this.chunksDone+1;Q||!(I&1);I>>=1){if(!(W=this.stack.pop()))break;this.buffer32.set(W,0),this.buffer32.set(J,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|w0.PARENT,this.buffer32,0),J=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(J)}this.pos=0}_cloneInto(V){V=super._cloneInto(V);let{IV:$,flags:Q,state:Z,chunkPos:J,posOut:W,chunkOut:I,stack:Y,chunksDone:X}=this;return V.state.set(Z.slice()),V.stack=Y.map((G)=>Uint32Array.from(G)),V.IV.set($),V.flags=Q,V.chunkPos=J,V.chunksDone=X,V.posOut=W,V.chunkOut=I,V.enableXOF=this.enableXOF,V.bufferOut32.set(this.bufferOut32),V}destroy(){this.destroyed=!0,l0(this.state,this.buffer32,this.IV,this.bufferOut32),l0(...this.stack)}b2CompressOut(){let{state:V,pos:$,flags:Q,buffer32:Z,bufferOut32:J}=this,{h:W,l:I}=q$(BigInt(this.chunkOut++));e(Z);let{v0:Y,v1:X,v2:G,v3:K,v4:w,v5:N,v6:z,v7:U,v8:R,v9:O,v10:H,v11:P,v12:D,v13:F,v14:A,v15:m}=H$(vQ,0,Z,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],O0[0],O0[1],O0[2],O0[3],I,W,$,Q);J[0]=Y^R,J[1]=X^O,J[2]=G^H,J[3]=K^P,J[4]=w^D,J[5]=N^F,J[6]=z^A,J[7]=U^m,J[8]=V[0]^R,J[9]=V[1]^O,J[10]=V[2]^H,J[11]=V[3]^P,J[12]=V[4]^D,J[13]=V[5]^F,J[14]=V[6]^A,J[15]=V[7]^m,e(Z),e(J),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,l0(this.buffer.subarray(this.pos));let V=this.flags|w0.ROOT;if(this.stack.length)V|=w0.PARENT,e(this.buffer32),this.compress(this.buffer32,0,!0),e(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else V|=(!this.chunkPos?w0.CHUNK_START:0)|w0.CHUNK_END;this.flags=V,this.b2CompressOut()}writeInto(V){IV(this,!1),x0(V),this.finish();let{blockLen:$,bufferOut:Q}=this;for(let Z=0,J=V.length;Z<J;){if(this.posOut>=$)this.b2CompressOut();let W=Math.min($-this.posOut,J-Z);V.set(Q.subarray(this.posOut,this.posOut+W),Z),this.posOut+=W,Z+=W}return V}xofInto(V){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(V)}xof(V){return WV(V),this.xofInto(new Uint8Array(V))}digestInto(V){if(SV(V,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto(V),this.destroy(),V}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var uQ=BQ((V)=>new P$(V));var C$=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function nQ(V){let $=new Uint8Array(C$.length+32);return $.set(C$),$.set(V.subarray(0,32),C$.length),$}function yQ(V){return typeof V==="string"?new TextEncoder().encode(V):V}function c0(V){let $=new ArrayBuffer(V.byteLength);return new Uint8Array($).set(V),$}class T${verifyKeys=new Map;signKeys=new Map;async genRandomBytes(V){return mV(V)}async gen256BitSecureRandomSeed(){return mV(32)}async encryptXSalsa20Poly1305Combined(V,$){let Q=mV(24),J=U$($,Q).encrypt(V);return new Uint8Array([...Q,...J])}async decryptXSalsa20Poly1305Combined(V,$){let Q=V.slice(0,24),Z=V.slice(24);return U$($,Q).decrypt(Z)}async deriveEd25519KeyPair(V){let $=V,Q=nQ($),Z=await globalThis.crypto.subtle.importKey("pkcs8",c0(Q),{name:"Ed25519"},!0,["sign"]),J=await globalThis.crypto.subtle.exportKey("jwk",Z);if(typeof J.x!=="string")throw Error("Ed25519 JWK missing x");let W=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:J.x},{name:"Ed25519"},!0,["verify"]),I=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",W)),Y=new Uint8Array(64);return Y.set($,0),Y.set(I,32),this.signKeys.set(o($),Z),this.verifyKeys.set(o(I),W),{keyType:"ed25519",privateKey:Y,publicKey:I}}async importSignKey(V){let $=V.subarray(0,32),Q=o($),Z=this.signKeys.get(Q);if(Z)return Z;let J=nQ($),W=await globalThis.crypto.subtle.importKey("pkcs8",c0(J),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Q,W),W}async importVerifyKey(V){let $=o(V),Q=this.verifyKeys.get($);if(Q)return Q;let Z=await globalThis.crypto.subtle.importKey("raw",c0(V),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set($,Z),Z}async signEd25519(V,$){let Q=yQ(V),Z=await this.importSignKey($),J=await globalThis.crypto.subtle.sign({name:"Ed25519"},Z,c0(Q));return new Uint8Array(J)}async checkSigEd25519(V,$,Q){let Z=yQ($);try{let J=await this.importVerifyKey(Q);return await globalThis.crypto.subtle.verify({name:"Ed25519"},J,c0(V),c0(Z))}catch{return!1}}async blake3(V){return uQ(V)}}var aZ=new T$,Z0=aZ;var GG=Symbol("EntityID");function bQ(V){return"type"in V}var KG=Symbol("MasterSeed"),MG=Symbol("DerivationSeed"),wG=Symbol("PublicKey"),NG=Symbol("PrivateKey"),RG=Symbol("HostSpecificKeyPair"),zG=Symbol("Hash");function sZ(V){if(!V)return!1;if(typeof V!=="object")return!1;if("body"in V===!1)return!1;if("type"in V===!1)return!1;return!0}function tZ(V){if(!V.bod||V.bod.length===0){let Z={off:V.off,ctr:V.ctr,eid:V.eid};return q(Z)}let $=rV(V.bod);if(sZ($)===!1)return console.warn("msg body invalid",$),M(14);let Q={off:V.off,ctr:V.ctr,eid:V.eid,gid:$.gid,pid:$.pid,type:$.type,body:$.body};return q(Q)}class xV{applier;emitter=new C0;clearer;onTypes;constructor(V,$,Q){this.applier=V;this.clearer=$,this.onTypes=Q}apply=async(V)=>{let $=[],Q=[];for(let I of V){let[Y,X]=tZ(I);if(Q.push(X),X!==0)continue;$.push(Y)}let{stats:Z,types:J}=await this.applier($),W=[];for(let I=0;I<V.length;I++){let Y=Q[I],X=Z[I];if(Y!==0){W.push(Y);continue}if(X!==0){W.push(X);continue}W.push(0)}for(let I of J)this.emitter.emit(I,null);if(J.size>0)this.onTypes?.(J);return W};clear=async()=>{let V=await this.clearer();if(V!==0)return V;return this.emitter.emitAll(null),V};notify=(V)=>{for(let $ of V)this.emitter.emit($,null)};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}var D$={apply:async function(V){return V.map(()=>0)},clear:async function(){return 0},notify:function(V){},on:function(V,$){},off:function(V,$){}};function A$(V){return new xV(($)=>V.apply($),()=>V.clear())}function kV(V,$){let Q=new B($.eid),[Z,J]=Q.readStruct(t);if(J!==0)return M(J);let W=new Date(Z.ts.getTime()+$.off);if(V!==void 0&&W<=V.updatedAt)return M(15);if(bQ($))return q({eid:$.eid,gid:$.gid,pid:$.pid,type:$.type,createdAt:Z.ts,updatedAt:W,ctr:$.ctr,body:$.body});else return q(void 0)}var eZ={getEnt:async()=>M(21),getEntities:async(V)=>M(21),countEntities:async()=>M(21),apply:async(V)=>({stats:V.map(()=>21),types:new Set}),clear:async()=>21};var n="entities",fV="entity_type_created_at",_$="entity_type_updated_at",j$="entity_type_group_id",m$="entity_type_parent_id";function VJ(V){let $={bod:V.body,crd:V.createdAt,...V.ctr!==0?{ctr:V.ctr}:{},eid:x(V.eid),gid:V.gid,pid:V.pid?x(V.pid):void 0,typ:V.type,upd:V.updatedAt};if($.gid===void 0)delete $.gid;if($.pid===void 0)delete $.pid;if($.ctr===void 0)delete $.ctr;return $}function d0(V){return{body:V.bod,createdAt:V.crd,updatedAt:V.upd,ctr:V.ctr??0,type:V.typ,eid:Y0(V.eid),gid:V.gid,pid:V.pid?Y0(V.pid):void 0}}class L${db;async init(){this.db=await new Promise((V,$)=>{let Q=indexedDB.open("db",11);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!J)throw Error("Transaction is null during upgrade");if(!Z.objectStoreNames.contains(n))Z.createObjectStore(n,{keyPath:"eid",autoIncrement:!1});let W=J.objectStore(n);if(!W.indexNames.contains(fV))W.createIndex(fV,["typ","crd"],{unique:!1});if(!W.indexNames.contains(_$))W.createIndex(_$,["typ","upd"],{unique:!1});if(!W.indexNames.contains(j$))W.createIndex(j$,["typ","gid"],{unique:!1});if(!W.indexNames.contains(m$))W.createIndex(m$,["typ","pid"],{unique:!1})},Q.onsuccess=()=>V(Q.result),Q.onerror=()=>$(Q.error)})}apply=async(V)=>{let $=new Set;if(!this.db)return{stats:V.map(()=>16),types:$};let Q=this.db.transaction(n,"readwrite"),Z=Q.objectStore(n);return new Promise((J)=>{let W=Array(V.length).fill(0);if(V.length<1){J({stats:[],types:$});return}Q.oncomplete=()=>{J({stats:W,types:$})},Q.onerror=()=>{for(let Y=0;Y<W.length;Y++)if(W[Y]===void 0)W[Y]=18;J({stats:W,types:$})};let I=new Map;for(let Y=0;Y<V.length;Y++){let X=V[Y],G=x(X.eid),K={op:X,index:Y},w=I.get(G);if(w)w.push(K);else I.set(G,[K])}for(let[Y,X]of I){if(X.length<1)continue;let G=Z.get(Y);G.onsuccess=()=>{let K=G.result,w=K?d0(K):void 0;for(let{op:N,index:z}of X){let[U,R]=kV(w,N);if(R!==0){W[z]=R;continue}if(U)$.add(U.type);else if(w)$.add(w.type);w=U}if(w){let N=VJ(w),z=Z.put(N);z.onerror=(U)=>{U.preventDefault();for(let{index:R}of X)W[R]=18}}else{let N=Z.delete(Y);N.onerror=()=>{for(let{index:z}of X)W[z]=18}}},G.onerror=()=>{for(let{index:K}of X)W[K]=18}}})};async clear(){if(!this.db)return 16;let V=this.db.transaction(n,"readwrite"),$=V.objectStore(n);return new Promise((Q)=>{V.oncomplete=()=>Q(0),V.onerror=()=>Q(18),$.clear()})}async getEnt(V){if(!this.db)return M(16);let $=x(V),Z=this.db.transaction(n,"readonly").objectStore(n);return new Promise((J)=>{let W=Z.get($);W.onsuccess=()=>{let I=W.result;if(!I)J(q(void 0));else{let Y=d0(I);J(q(Y))}},W.onerror=()=>J(M(18))})}async getAllOfTypeUpdatedBetween(V,$,Q){if(!this.db)return M(16);let J=this.db.transaction(n,"readonly").objectStore(n).index(_$);return new Promise((W)=>{let I=J.getAll(IDBKeyRange.bound([V,$],[V,Q]));I.onsuccess=()=>{let Y=I.result;W(q(Y.map(d0)))},I.onerror=()=>W(M(18))})}async getGroupMembers(V,$){if(!this.db)return M(16);let Z=this.db.transaction(n,"readonly").objectStore(n).index(j$);return new Promise((J)=>{let W=Z.getAll(IDBKeyRange.only([V,$]));W.onsuccess=()=>{let I=W.result;J(q(I.map(d0)))},W.onerror=()=>J(M(18))})}async getAllOfType(V){if(!this.db)return M(16);let Q=this.db.transaction(n,"readonly").objectStore(n).index(fV);return new Promise((Z)=>{let J=Q.getAll(IDBKeyRange.bound([V],[V,[]]));J.onsuccess=()=>{let W=J.result;Z(q(W.map(d0)))},J.onerror=()=>Z(M(18))})}async getAllEntities(V){if(!this.db)return M(16);if("pid"in V){let $=x(V.pid),Z=this.db.transaction(n,"readonly").objectStore(n).index(m$);return new Promise((J)=>{let W=Z.getAll(IDBKeyRange.only([V.type,$]));W.onsuccess=()=>{let Y=W.result.map(d0);J(q(Y))},W.onerror=()=>J(M(18))})}else if("gid"in V)return await this.getGroupMembers(V.type,V.gid);else if("updatedBetween"in V)return await this.getAllOfTypeUpdatedBetween(V.type,V.updatedBetween.start,V.updatedBetween.end);return await this.getAllOfType(V.type)}async getEntities(V){let[$,Q]=await this.getAllEntities(V);if(Q!==0)return M(Q);return q($)}async countEntities({type:V}){if(!this.db)return M(16);let Q=this.db.transaction(n,"readonly").objectStore(n).index(fV);return new Promise((Z)=>{let J=IDBKeyRange.bound([V],[V,[]]),W=Q.count(J);W.onsuccess=()=>Z(q(W.result)),W.onerror=()=>Z(M(18))})}}async function S$(){let V=new L$;return await V.init(),V}class pQ{ents=new Map;constructor(V=[]){for(let $ of V){let Q=x($.eid);this.ents.set(Q,$)}}async apply(V){let $=new Set,Q=[];for(let Z of V){let J=x(Z.eid),W=this.ents.get(J),[I,Y]=kV(W,Z);if(Y!==0){Q.push(Y);continue}if(I)$.add(I.type);else if(W)$.add(W.type);if(I)this.ents.set(J,I);else this.ents.delete(J);Q.push(0)}return{stats:Q,types:$}}async clear(){return this.ents.clear(),0}async getEnt(V){let $=x(V),Q=this.ents.get($);return q(Q)}async getAllEntities({type:V,gid:$,pid:Q,updatedBetween:Z}){let J=[];if(Q!==void 0){for(let W of this.ents.values())if(W.type===V&&W.pid&&X0(W.pid,Q))J.push(W)}else if($!==void 0){for(let W of this.ents.values())if(W.type===V&&(typeof W.gid==="string"&&W.gid===$))J.push(W)}else if(Z!==void 0){for(let W of this.ents.values())if(W.type===V&&W.updatedAt>=Z.start&&W.updatedAt<=Z.end)J.push(W)}else for(let W of this.ents.values())if(W.type===V)J.push(W);return q(J)}async getEntities(V){let[$,Q]=await this.getAllEntities(V);if(Q!==0)return M(Q);return q($)}async countEntities({type:V}){let $=0;for(let Q of this.ents.values())if(Q.type===V)$+=1;return q($)}}import{useEffect as uV,useState as i$}from"react";class E${db;constructor(V){this.db=V}async enq(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(J0,"readwrite"),Z=Q.objectStore(J0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let I of $){let Y=`${I.host}:${I.seq}`;Z.put(I,Y)}})}async deq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(J0,"readwrite"),J=Z.objectStore(J0);return new Promise((W,I)=>{Z.oncomplete=()=>W(),Z.onerror=()=>I(Z.error);for(let Y of Q){let X=`${V}:${Y}`;J.delete(X)}})}async list(){let $=this.db.transaction(J0,"readonly").objectStore(J0);return new Promise((Q,Z)=>{let J=$.getAll();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async count(){let $=this.db.transaction(J0,"readonly").objectStore(J0);return new Promise((Q,Z)=>{let J=$.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(J0,"readwrite"),$=V.objectStore(J0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}function rQ(V){return{label:V.label,handle:new URL(V.handle),idx:V.idx,lastSeq:V.lastSeq||0,clockOffset:V.clockOffset,subscription:V.subscription}}class x${db;constructor(V){this.db=V}async add(V){return this.put(V)}async put(V){let $={...V,handle:V.handle.toString(),lastSeq:V.lastSeq??0},Q=this.db.transaction(V0,"readwrite"),Z=Q.objectStore(V0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error),Z.put($)})}async touch(V,$){let Q=this.db.transaction(V0,"readwrite"),Z=Q.objectStore(V0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);let I=Z.get(V);I.onsuccess=()=>{let Y=I.result;if(!Y)return;let X=Y.lastSeq||0;if($<=X)return;Z.put({...Y,lastSeq:$})}})}async get(V){let Q=this.db.transaction(V0,"readonly").objectStore(V0);return new Promise((Z,J)=>{let W=Q.get(V);W.onsuccess=()=>{let I=W.result;if(!I)Z(void 0);else Z(rQ(I))},W.onerror=()=>J(W.error)})}async set(V,$){let Q=await this.get(V);if(!Q)return 13;try{return await this.put({...Q,...$}),0}catch{return 18}}async del(V){let $=this.db.transaction(V0,"readwrite"),Q=$.objectStore(V0);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),Q.delete(V)})}async list(){let $=this.db.transaction(V0,"readonly").objectStore(V0);return new Promise((Q,Z)=>{let J=$.getAll();J.onsuccess=()=>{let W=J.result;Q(W.map(rQ))},J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(V0,"readwrite"),$=V.objectStore(V0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}class k${crypto;db;constructor(V,$){this.crypto=$;this.db=V}async add(V){let $=this.db.transaction(u,"readwrite"),Q=$.objectStore(u);return new Promise((Z)=>{if(V.length===0){Z([]);return}let J=Array(V.length).fill(0);$.oncomplete=()=>Z(J),$.onerror=()=>{for(let W=0;W<J.length;W++)J[W]=18;Z(J)};for(let W=0;W<V.length;W++){let{key:I,data:Y}=V[W],X=x(I),G=Q.put(Y,X);G.onerror=(K)=>{K.preventDefault(),J[W]=18}}})}async del(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let I of $){let Y=x(I);Z.delete(Y)}})}async get(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let W=x(V),I=Q.get(W);I.onsuccess=async()=>{let Y=I.result;if(Y)Z(await m0(V,Y,this.crypto));else Z(void 0)},I.onerror=()=>J(I.error)})}async has(V){return await this.get(V)!==void 0}async list(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let W=[],I=V===void 0?Q.openCursor():Q.index(BV).openCursor(IDBKeyRange.only(V));I.onsuccess=(Y)=>{let X=Y.target.result;if(X){let G=V===void 0?X.key:X.primaryKey,K=X.value;W.push({hash:Y0(G),data:K}),X.continue()}else Promise.all(W.map(({hash:G,data:K})=>m0(G,K,this.crypto))).then(Z).catch(J)},I.onerror=()=>J(I.error)})}async last(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let W,I=Q.openCursor();I.onsuccess=async(Y)=>{let X=Y.target.result;if(X){let{key:G,value:K}=X;if(X0(V,K.eid)){if(!W||(K.ctr??0)>(W.data.ctr??0)||(K.ctr??0)===(W.data.ctr??0)&&(K.off??0)>(W.data.off??0))W={key:G,data:K}}X.continue()}else if(W){let G=Y0(W.key);Z(await m0(G,W.data,this.crypto))}else Z(void 0)},I.onerror=()=>J(I.error)})}async markApplied(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let I of $){let Y=x(I),X=Z.get(Y);X.onsuccess=()=>{let G=X.result;if(!G)return;L0(G,j0),Z.put(G,Y)},X.onerror=(G)=>{G.preventDefault()}}})}async markFailed(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let{key:I,err:Y}of $){let X=x(I),G=Z.get(X);G.onsuccess=()=>{let K=G.result;if(!K)return;L0(K,K0,Y),Z.put(K,X)},G.onerror=(K)=>{K.preventDefault()}}})}async wipe(){let V=this.db.transaction(u,"readwrite"),$=V.objectStore(u);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}class o0{seed;crypto;constructor(V,$){this.seed=V,this.crypto=$}async deriveFromKDM(V){let $=e0(this.seed,V);return await this.crypto.blake3($)}async derive(V,$=0){let Q=new TextEncoder().encode(V),Z=new Uint8Array(8);new DataView(Z.buffer).setBigUint64(0,BigInt($),!1);let J=e0(Q,Z);return await this.deriveFromKDM(J)}}class f${enclave;db;constructor(V){this.db=V}async save(V){let $=o(V),Q=this.db.transaction(H0,"readwrite"),Z=Q.objectStore(H0);return new Promise((J,W)=>{Q.oncomplete=()=>{this.enclave=new o0(V,Z0),J(this.enclave)},Q.onerror=()=>W(Q.error),Z.put($,"seed")})}async load(){if(this.enclave)return this.enclave;let $=this.db.transaction(H0,"readonly").objectStore(H0);return new Promise((Q,Z)=>{let J=$.get("seed");J.onsuccess=()=>{let W=J.result;if(!W)Q(void 0);else{let I=_0(W);this.enclave=new o0(I,Z0),Q(this.enclave)}},J.onerror=()=>Z(J.error)})}async wipe(){this.enclave=void 0;let V=this.db.transaction(H0,"readwrite"),$=V.objectStore(H0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.delete("seed")})}}class B${db;constructor(V){this.db=V}async enq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((W,I)=>{Z.oncomplete=()=>W(),Z.onerror=()=>I(Z.error);for(let Y of Q){let X=o(Y);J.put({host:V,hash:X})}})}async deq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((W,I)=>{Z.oncomplete=()=>W(),Z.onerror=()=>I(Z.error);for(let Y of Q){let X=o(Y);J.delete([V,X])}})}async list(V){let Q=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Z,J)=>{let W=Q.getAll();W.onsuccess=()=>{let Y=W.result.filter((X)=>X.host===V).map((X)=>X.hash);Z(Y.map((X)=>_0(X)))},W.onerror=()=>J(W.error)})}async count(){let $=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Q,Z)=>{let J=$.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(W0,"readwrite"),$=V.objectStore(W0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}var H0="seedMeta",V0="hosts",W0="uploadQueue",J0="downloadQueue",u="messages",BV="apld",$J=3;class g${seed;hosts;uploads;downloads;messages;db;constructor(V,$){this.db=V,this.seed=new f$(V),this.hosts=new x$(V),this.uploads=new B$(V),this.downloads=new E$(V),this.messages=new k$(V,$)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function QJ(){return new Promise((V,$)=>{let Q=indexedDB.open("diplomatic-store-db",$J);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!Z.objectStoreNames.contains(H0))Z.createObjectStore(H0);if(!Z.objectStoreNames.contains(V0))Z.createObjectStore(V0,{keyPath:"label"});if(!Z.objectStoreNames.contains(W0))Z.createObjectStore(W0,{keyPath:["host","hash"]});if(!Z.objectStoreNames.contains(J0))Z.createObjectStore(J0);let W;if(!Z.objectStoreNames.contains(u))W=Z.createObjectStore(u);else{if(!J)throw Error("missing upgrade transaction for messages store");W=J.objectStore(u)}if(!W.indexNames.contains(BV))W.createIndex(BV,"apld",{unique:!1})},Q.onsuccess=()=>V(Q.result),Q.onerror=()=>$(Q.error)})}async function gV(V){let $=await QJ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new g$($,V)}function lQ(V){if(!V||typeof V!=="object")return!1;if(!("kind"in V))return!1;return typeof V.kind==="string"}function hQ(V){if(typeof V!=="number")return;return V}var P0="[DIPLOMATIC]";class XV{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:p0};clientState;xferState;constructor(V,$,Q,Z,J){this.worker=V,this.state=$,this.clientState=new G0(async()=>this.cachedClientState),this.xferState=new G0(async()=>this.cachedXferState),this.scheduledSync=new $V(J,async()=>{try{await this.request({id:this.allocId(),op:"sync"})}catch(W){console.error(`${P0} worker sync after local write failed`,W)}}),this.local=new S0(Z,$,Q,()=>{throw Error(`${P0} local writer has no transport (use worker for network)`)},Z0,!0,void 0,void 0,()=>{this.scheduledSync.schedule()}),this.ready=new Promise((W,I)=>{this.resolveReady=W,this.rejectReady=I}),this.worker.onmessage=(W)=>{this.onMessage(W.data)},this.worker.onerror=(W)=>{console.error(`${P0} worker error`,W),this.failReady(Error(`${P0} worker failed to load`))},this.worker.onmessageerror=()=>{this.failReady(Error(`${P0} worker message error`))}}failReady(V){let $=this.rejectReady;if(this.rejectReady=void 0,this.resolveReady=void 0,$)$(V)}async flushScheduledSync(){await this.scheduledSync.flush()}static async connect(V,$,Q){let Z=Q.clock??new R0,J=Q.syncDebounceMs??TV,W=new XV(Q.worker,V,$,Z,J),I=Q.readyTimeoutMs??15000,Y;try{let X=W.probeReady();await Promise.race([W.ready,X,new Promise((G,K)=>{Y=setTimeout(()=>{K(Error(`${P0} worker ready timeout after ${I}ms`))},I)})]),X.catch(()=>{})}catch(X){throw W.terminate(),X}finally{if(Y!==void 0)clearTimeout(Y)}return W}markReady(){let V=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V()}probeReady(){return new Promise((V,$)=>{let Q=this.allocId();this.pending.set(Q,{resolve:(Z)=>{if(Z==="pong"){this.markReady(),V();return}$(Error(`${P0} worker probe ping failed`))},reject:$}),this.worker.postMessage({id:Q,op:"ping"})})}async ping(){if(await this.ready,await this.request({id:this.allocId(),op:"ping"})!=="pong")throw Error(`${P0} worker ping failed`)}terminate(){this.scheduledSync.cancel(),this.worker.terminate();for(let[,V]of this.pending)V.reject(Error(`${P0} worker terminated`));this.pending.clear()}onMessage(V){if(!lQ(V))return;let $=V;switch($.kind){case"ready":{this.markReady();return}case"clientState":{this.cachedClientState=$.state,this.clientState.emit();return}case"xferState":{this.cachedXferState=$.state,this.xferState.emit();return}case"dirty":{this.state.notify($.types);return}case"wiped":{this.state.clear();return}case"reply":{let Q=this.pending.get($.id);if(!Q)return;if(this.pending.delete($.id),$.ok)Q.resolve($.result);else Q.reject(new iV($.status));return}default:return}}allocId(){let V=this.nextId;return this.nextId+=1,V}request(V,$){return new Promise((Q,Z)=>{if(this.pending.set(V.id,{resolve:Q,reject:Z}),$&&$.length>0)this.worker.postMessage(V,$);else this.worker.postMessage(V)})}async requestStatus(V,$){try{let Q=await this.request(V,$),Z=hQ(Q);if(Z!==void 0)return Z;return 0}catch(Q){if(Q instanceof iV)return Q.status;return 12}}serializeHost(V){return{handle:V.handle.href,label:V.label,idx:V.idx??0}}async setSeed(V){await this.ready,await this.local.setSeed(V);let $=V.slice();await this.request({id:this.allocId(),op:"setSeed",seed:$},[$.buffer])}async link(V,$=!0){await this.ready,await this.local.link(V,!1),await this.request({id:this.allocId(),op:"link",host:this.serializeHost(V),connect:$})}async unlink(V){await this.ready,await this.local.unlink(V),await this.request({id:this.allocId(),op:"unlink",label:V})}async hosts(){return await this.ready,this.local.hosts()}async connect(V=!0,$=!0){await this.ready,await this.request({id:this.allocId(),op:"connect",listen:V,sync:$})}async disconnect(){await this.ready,await this.request({id:this.allocId(),op:"disconnect"})}async insertRaw(V){return await this.ready,this.local.insertRaw(V)}async upsertRaw(V,$,Q){return await this.ready,this.local.upsertRaw(V,$,Q)}async insert(V){return await this.ready,this.local.insert(V)}async upsert(V,$){return await this.ready,this.local.upsert(V,$)}async delete(V){return await this.ready,this.local.delete(V)}async genEID(V){return await this.ready,this.local.genEID(V)}async sync(){return await this.ready,this.requestStatus({id:this.allocId(),op:"sync"})}async wipe(){await this.ready,await this.request({id:this.allocId(),op:"wipe"})}async import(V){await this.ready;let $=new Uint8Array(await V.arrayBuffer());return this.requestStatus({id:this.allocId(),op:"import",bytes:$},[$.buffer])}async export(V,$){await this.ready;try{let Q=await this.request({id:this.allocId(),op:"export"});if(!(Q instanceof Uint8Array))return 12;let Z=new Blob([Q.slice()]);return DV(Z,V),0}catch(Q){if(Q instanceof iV)return Q.status;return 12}}}class iV extends Error{status;constructor(V){super(`WorkerReplyError: ${_[V]}`);this.status=V;this.name="WorkerReplyError"}}var k0="[DIPLOMATIC]";async function vV(V){let $=V.clock??new R0;if(V.worker!==void 0&&ZJ(V)!==void 0)throw Error(`${k0} worker path requires IndexedDB on both sides; do not pass store (got a custom store)`);if(V.worker===void 0){console.info(`${k0} sync on main thread `+"(no worker — app did not request a worker)");let J=await cQ(V.store);return JJ($,V.state,J)}if(typeof Worker>"u")throw Error(`${k0} worker was provided but Worker API is unavailable`);let Q=await cQ(void 0);console.info(`${k0} attaching app-provided sync worker…`);let Z=await XV.connect(V.state,Q,{worker:V.worker,readyTimeoutMs:V.readyTimeoutMs,clock:$,syncDebounceMs:V.syncDebounceMs});return await Z.ping(),console.info(`${k0} sync worker active (network + EntDB writes off main; local mutates on main; dirty signals only)`),{client:Z,mode:"worker",dispose:()=>{console.info(`${k0} terminating sync worker`),Z.terminate()}}}function ZJ(V){if("store"in V)return V.store;return}async function JJ(V,$,Q){let Z=new S0(V,$,Q,OV,Z0);return{client:Z,mode:"main",dispose:()=>{Z.disconnect()}}}async function cQ(V){if(V!==void 0)return V;if(typeof indexedDB>"u")throw Error(`${k0} IndexedDB is unavailable; pass store explicitly (e.g. new MemoryStore(crypto))`);return gV(Z0)}function WJ(V){let[$,Q]=i$();return uV(()=>{async function Z(){let W=await V.clientState.get();Q(W)}let J=V.clientState.listen(Z);return Z(),()=>{J()}},[V]),$}function IJ(V){let[$,Q]=i$();return uV(()=>{async function Z(){let W=await V.xferState.get();Q(W)}let J=V.xferState.listen(Z);return Z(),()=>{J()}},[V]),$}function YJ(V){uV(()=>{async function $(){try{await V.connect(),await V.sync()}catch(W){console.error("reconnectAndSync failed",W)}}function Q(){$()}function Z(){if(typeof document<"u"&&document.visibilityState==="visible")$()}function J(){$()}if(globalThis.addEventListener("online",Q),typeof document<"u")document.addEventListener("visibilitychange",Z);return globalThis.addEventListener("focus",J),globalThis.addEventListener("pageshow",J),()=>{if(globalThis.removeEventListener("online",Q),typeof document<"u")document.removeEventListener("visibilitychange",Z);globalThis.removeEventListener("focus",J),globalThis.removeEventListener("pageshow",J)}},[V])}function XJ(V={}){let $=V.clock??new R0,{seed:Q,host:Z,readyTimeoutMs:J}=V,W=V.worker,I="store"in V?V.store:void 0,[Y,X]=i$({stateMgr:D$});return uV(()=>{let G=!1,K;return(async()=>{let w=await S$();if(G)return;let N=A$(w),z=W!==void 0?await vV({state:N,clock:$,worker:W,readyTimeoutMs:J}):await vV({state:N,clock:$,store:I,readyTimeoutMs:J});if(G){z.dispose();return}K=z.dispose;let{client:U,mode:R}=z;if(Q)await U.setSeed(Q);if(Z)await U.link(Z);if(G){K();return}X({client:U,entDB:w,stateMgr:N,mode:R,error:void 0})})().catch((w)=>{let N=w instanceof Error?w:Error(String(w));if(console.error("[DIPLOMATIC] useClient init failed",N),!G)X((z)=>({...z,client:void 0,error:N}))}),()=>{G=!0,K?.()}},[$,Q,Z,W,I,J]),Y}import{use as GJ,useEffect as dQ,useRef as KJ,useState as MJ}from"react";function oQ(V,$,Q){let[Z,J]=MJ();return dQ(()=>{async function W(){let I=await Q();J(I)}return W(),V.on($,W),()=>{V.off($,W)}},[V,$,Q]),Z}function wJ(V,$,Q){let Z=KJ(Q());return dQ(()=>{async function J(){Z.current=Q()}return V.on($,J),()=>{V.off($,J)}},[V,$,Q]),GJ(Z.current)}function aQ(V,$){return`${V}:${$}`}class v${queue=new Map;async enq(V){for(let $ of V){let Q=aQ($.host,$.seq);this.queue.set(Q,$)}}async deq(V,$){for(let Q of $){let Z=aQ(V,Q);this.queue.delete(Z)}}async list(){let V=[];for(let $ of this.queue.values())V.push($);return V}async count(){return this.queue.size}async wipe(){this.queue.clear()}}class u${hosts=new Map;async add(V){let $={...V,lastSeq:0};this.hosts.set(V.label,$)}async touch(V,$){let Q=this.hosts.get(V);if(!Q||$<=Q.lastSeq)return;this.hosts.set(V,{...Q,lastSeq:$})}async get(V){return this.hosts.get(V)}async set(V,$){let Q=this.hosts.get(V);if(!Q)return 13;return this.hosts.set(V,{...Q,...$}),0}async del(V){this.hosts.delete(V)}async list(){return this.hosts.values()}async wipe(){this.hosts.clear()}}class n${crypto;messages=new Map;constructor(V){this.crypto=V}async add(V){let $=[];for(let{key:Q,data:Z}of V)this.messages.set(x(Q),Z),$.push(0);return $}async del(V){for(let $ of V)this.messages.delete(x($))}async get(V){let $=this.messages.get(x(V));if($)return await m0(V,$,this.crypto);return}async has(V){return this.messages.has(x(V))}async list(V){let $=[];for(let[Q,Z]of this.messages){if(V!==void 0&&JV(Z.apld)!==V)continue;let J=Y0(Q);$.push(await m0(J,Z,this.crypto))}return $}async last(V){let $;for(let[Q,Z]of this.messages){if(X0(V,Z.eid)===!1)continue;let J=Y0(Q);if($===void 0)$={hash:J,data:Z};else if((Z.ctr??0)>($.data.ctr??0)||(Z.ctr??0)===($.data.ctr??0)&&(Z.off??0)>($.data.off??0))$={hash:J,data:Z}}if($)return await m0($.hash,$.data,this.crypto);return}async markApplied(V){for(let $ of V){let Q=this.messages.get(x($));if(!Q)continue;L0(Q,j0)}}async markFailed(V){for(let{key:$,err:Q}of V){let Z=this.messages.get(x($));if(!Z)continue;L0(Z,K0,Q)}}async wipe(){this.messages.clear()}}class y${enclave;async save(V){return this.enclave=new o0(V,Z0),this.enclave}async load(){return this.enclave}async wipe(){this.enclave=void 0}}class b${queue=new Map;async enq(V,$){let Q=this.queue.get(V)||new Set;this.queue.set(V,Q);for(let Z of $)Q.add(o(Z))}async deq(V,$){let Q=this.queue.get(V);if(Q)for(let Z of $)Q.delete(o(Z))}async list(V){let $=this.queue.get(V);if(!$)return[];let Q=[];for(let Z of $)Q.push(_0(Z));return Q}async count(){let V=0;for(let $ of this.queue.values())V+=$.size;return V}async wipe(){this.queue.clear()}}class sQ{seed=new y$;hosts=new u$;uploads=new b$;downloads=new v$;messages;constructor(V){this.messages=new n$(V)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}class tQ{singletonType;latest;latestOff=-1;emitter=new C0;constructor(V){this.singletonType=V}async apply(V){for(let $ of V){let Q=new B($.eid),[Z,J]=Q.readStruct(t);if(J!==0)continue;let W=new k;W.writeVarString(this.singletonType);let I=W.result();if(Z.id.length===I.length&&Z.id.every((Y,X)=>Y===I[X])){if(this.latest===void 0||$.off>this.latestOff)this.latestOff=$.off,this.latest=$.bod,this.emitter.emit(this.singletonType,null)}}return V.map(()=>0)}clear=async()=>{return this.latest=void 0,this.latestOff=-1,this.emitter.emit(this.singletonType,null),0};notify=(V)=>{for(let $ of V)if($===this.singletonType)this.emitter.emit(this.singletonType,null)};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}async function Cw(V,$){let Q=await gV(Z0),Z=new S0(new R0,V,Q,OV,Z0);return{client:Z,setSeed:async(W)=>{let I=_0(W);await Q.seed.save(I),await Q.hosts.add({handle:$,label:"host",idx:0}),await Z.connect()}}}export{YJ as useSyncOnResume,wJ as useStateWatcherSuspense,oQ as useStateWatcher,IJ as useClientXferState,WJ as useClientState,XJ as useClient,J$ as shouldEmitItemProgress,L0 as setApld,gV as openIDBStore,S$ as openEntIDB,vV as openDiplomaticClient,D$ as nullStateManager,eZ as nullEntDB,I$ as isTerminalApplyFailure,SZ as isPendingApply,LZ as isApldState,p0 as idleProgress,_0 as htob,OV as hostHTTPTransport,Cw as genWebClient,AZ as genSingletonEID,A$ as entStateManager,t as eidCodec,ZV as defaultPeekProgressEvery,Z0 as crypto,o as btoh,JV as apldFromStored,XV as WorkerClient,C0 as TypedEventEmitter,S0 as SyncClient,_ as Status,xV as StateManager,tQ as SingletonStateManager,sQ as MemoryStore,g$ as IDBStore,V$ as HTTPTransport,L$ as EntIDB,pQ as EntDBMemory,k as Encoder,B as Decoder,R0 as Clock,z0 as APLD_PENDING,K0 as APLD_ERROR,j0 as APLD_APPLIED};