import{_ as d,N as u,q as h,s as l,t as r}from"./bootstrap-DlNJH-GE.js";function w(a){return a.slice().sort((t,e)=>e.createdMs-t.createdMs)[0]}class f{constructor(t,e="wkmsreact-node"){this.cfg=t,this.name=e}nc;enc=new TextEncoder;dec=new TextDecoder;async connect(){let t;try{t=await d(()=>import("./nats-Dzari4lm.js"),[])}catch(n){throw new u("RelayClient","install nats.ws (npm i nats.ws)",n)}const e=h(this.cfg);if(e.length===0)throw new u("RelayClient","no enabled relays in RelayConfig");const i=e[0];return this.nc=await t.connect({servers:e.map(n=>n.wssUrl),user:i.user,pass:i.pass,name:this.name,timeout:15e3,maxReconnectAttempts:-1,noRandomize:!0}),{server:this.nc.getServer(),domain:this.connectedDomain()}}isReady(){return!!this.nc&&!this.nc.isClosed()}connectedDomain(){const t=this.nc?.getServer()??"";return l(this.cfg,t)?.jsDomain??r(this.cfg)[0]??""}js(){if(!this.nc)throw new Error("RelayClient used before connect()");return this.nc.jetstream()}async kvBucket(t,e){try{return await this.js().views.kv(`${t}_${e}`,{bindOnly:!0})}catch{return null}}async kvPut(t,e,i){const n=this.connectedDomain(),o=await this.kvBucket(t,n);if(!o)throw new Error(`RelayClient.kvPut: origin bucket ${t}_${n} not found on the connected relay`);const s=await o.put(e,this.enc.encode(JSON.stringify(i)));return{domain:n,revision:s}}async kvGet(t,e){const i=[];for(const n of r(this.cfg)){const o=await this.kvBucket(t,n);if(o)try{const s=await o.get(e);s&&s.operation!=="DEL"&&s.operation!=="PURGE"&&s.value?.length&&i.push({key:e,value:JSON.parse(this.dec.decode(s.value)),domain:n,createdMs:s.created instanceof Date?s.created.getTime():Number(s.created??0),revision:s.revision})}catch{}}return w(i)}async kvDelete(t,e){const i=this.connectedDomain(),n=await this.kvBucket(t,i);n&&await n.delete(e).catch(()=>{})}async kvKeys(t,e){const i=new Set;for(const n of r(this.cfg)){const o=await this.kvBucket(t,n);if(o)try{const s=await o.keys(e);for await(const c of s)i.add(c)}catch{}}return[...i].sort()}async objectPut(t,e,i,n){const o=this.connectedDomain();let s;try{s=await this.js().views.os(`${t}_${o}`,{bindOnly:!0})}catch(c){throw new Error(`RelayClient.objectPut: origin object bucket ${t}_${o} not found: ${String(c)}`)}return await s.putBlob({name:e,description:n},i),{domain:o}}async objectGet(t,e){for(const i of r(this.cfg))try{const n=await this.js().views.os(`${t}_${i}`,{bindOnly:!0});if(!await n.info(e))continue;const s=await n.getBlob(e);if(s)return{data:s,domain:i}}catch{}}async close(){try{await this.nc?.close()}catch{}this.nc=void 0}}export{f as RelayClient,w as pickLatestEntry};
//# sourceMappingURL=relay_client-BG1TqAsV.js.map
