@collight/dns-sd
Version:
A DNS Service Discovery implementation in modern TypeScript
3 lines (2 loc) • 1.53 kB
JavaScript
import{EventEmitter as f}from"events";import a from"fast-deep-equal";import h from"multicast-dns";import{nameEquals as m}from"./dns-utils.js";class T extends f{constructor(n){super(),this.typeToRecords=new Map,this.mdns=h(n),this.mdns.setMaxListeners(0),this.mdns.on("query",o=>this.respond(o))}register(n){function o(e,s){return e.type===s.type&&e.name===s.name&&a(e.data,s.data)}for(const e of n){const s=e.type,t=this.typeToRecords.get(s)??[];t.every(r=>!o(r,e))&&t.push(e),this.typeToRecords.set(s,t)}}unregister(n){for(const o of n){const e=o.type,t=(this.typeToRecords.get(e)??[]).filter(r=>r.name!==o.name);t.length>0?this.typeToRecords.set(e,t):this.typeToRecords.delete(e)}}getRecordsOf(n,o){const e=[];for(const s of this.typeToRecords.get(n)??[]){const t=o.includes(".")?s.name:s.name.split(".")[0];t!==void 0&&m(t,o)&&e.push(s)}return e}respond(n){for(const o of n.questions){const e=o.type,s=o.name;let t;if(e==="ANY"?t=Array.from(this.typeToRecords.keys()).flatMap(i=>this.getRecordsOf(i,s)):t=this.getRecordsOf(e,s),t.length===0)continue;const r=[];if(e!=="ANY"){for(const c of t)c.type==="PTR"&&(r.push(...this.getRecordsOf("SRV",c.data)),r.push(...this.getRecordsOf("TXT",c.data)));const i=new Set;for(const c of r)if(c.type==="SRV"){const p=c.data.target;i.add(p)}for(const c of i)r.push(...this.getRecordsOf("A",c)),r.push(...this.getRecordsOf("AAAA",c))}const d={answers:t,additionals:r};this.mdns.respond(d,(...i)=>{this.emit("responded",d,...i)})}}}export{T as MDNSServer};
//# sourceMappingURL=MDNSServer.js.map