import Bonjour from"bonjour-service";import{ok,err}from"./_deps/shared/index.js";export var DiscoveryErrorCode;!function(e){e.NETWORK_ERROR="NETWORK_ERROR",e.TIMEOUT="TIMEOUT",e.NO_SERVICES="NO_SERVICES",e.INVALID_SERVICE="INVALID_SERVICE"}(DiscoveryErrorCode||(DiscoveryErrorCode={}));export class MdnsDiscoveryManager{bonjour;service=null;serviceType="privateme";protocol="tcp";port=58472;constructor(){this.bonjour=new Bonjour}advertise(e,o,r=this.port){this.service&&this.service.stop?.(),this.service=this.bonjour.publish({name:e,type:this.serviceType,protocol:this.protocol,port:r,txt:{did:o,endpoint:`http://localhost:${r}`,name:e}})}async scan(e,o=5e3){return new Promise(r=>{const t=new Map;let s=!1;const i=this.bonjour.find({type:this.serviceType,protocol:this.protocol});i.on("up",o=>{try{const r=o.txt;if(!r||!r.did||!r.name)return;if(r.did===e)return;const s=r.endpoint||`http://${o.host||"localhost"}:${o.port}`,i=(o.addresses||[]).filter(e=>e.includes(".")&&!e.includes(":")),n={name:r.name,did:r.did,endpoint:s,addresses:i,port:o.port||this.port};t.set(r.did,n)}catch{}});const n=setTimeout(()=>{s||(s=!0,i.stop(),0===t.size?r(err({code:DiscoveryErrorCode.NO_SERVICES,message:"No devices found on local network",hint:"Ensure both devices are on the same Wi-Fi network"})):r(ok(Array.from(t.values()))))},o);i.on("error",e=>{s||(s=!0,clearTimeout(n),i.stop(),r(err({code:DiscoveryErrorCode.NETWORK_ERROR,message:e.message,hint:"Check firewall settings and network connectivity"})))})})}stopAdvertising(){this.service&&(this.service.stop?.(),this.service=null)}destroy(){this.stopAdvertising(),this.bonjour.destroy()}}