UNPKG

@collight/dns-sd

Version:

A DNS Service Discovery implementation in modern TypeScript

3 lines (2 loc) 1.61 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("events"),f=require("fast-deep-equal"),u=require("multicast-dns"),h=require("./dns-utils.cjs");class y extends p.EventEmitter{constructor(n){super(),this.typeToRecords=new Map,this.mdns=u(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&&f(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&&h.nameEquals(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 a=c.data.target;i.add(a)}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)})}}}exports.MDNSServer=y; //# sourceMappingURL=MDNSServer.cjs.map