UNPKG

@collight/dns-sd

Version:

A DNS Service Discovery implementation in modern TypeScript

3 lines (2 loc) 2.77 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("events"),h=require("../utils/debug.cjs"),a=require("../utils/dns-utils.cjs");require("fast-deep-equal");require("multicast-dns");const d=require("../utils/ServiceType.cjs"),c=require("./DiscoveredService.cjs"),r=class r extends m.EventEmitter{constructor(e,t){super(),this.services=[],this.mdns=e,this.filter=t?.filter}get queryNames(){if(!this.filter)return[r.WILDCARD];const{protocol:e,type:t,name:i,subtypes:s}=this.filter;return(s&&s.length>0?s.map(o=>new d.ServiceType(t,e,o).toString()):[new d.ServiceType(t,e).toString()]).map(o=>typeof i=="string"?`${i}.${o}${r.TLD}`:`${o}${r.TLD}`)}start(){this.onresponse||(this.onresponse=(e,t)=>{h.debug("mdns on response packet:",e);for(const s of[...e.answers,...e.additionals])s.type==="PTR"&&s.ttl===0&&this.removeService(s.data);const i=c.DiscoveredService.fromResponse(e,t);if(i.length===0){if(!this.filter)for(const s of e.answers)s.type!=="PTR"||s.name!==r.WILDCARD||(h.debug("mdns wildcard query with:",s.data),this.mdns.query(s.data,"PTR"));return}for(const s of i)this.services.some(n=>a.nameEquals(n.fqdn,s.fqdn))?this.updateService(s):this.addService(s)},this.mdns.on("response",this.onresponse),this.update())}stop(){if(this.onresponse){this.mdns.removeListener("response",this.onresponse),this.onresponse=void 0;for(const e of this.services)clearTimeout(e.ttlTimer);this.services=[]}}update(){h.debug("mdns query with:",this.queryNames);for(const e of this.queryNames)this.mdns.query(e,"PTR")}match(e){if(!this.filter)return!0;const{protocol:t,type:i,subtypes:s,name:n,txt:o}=this.filter;if(t!==e.protocol||i!==e.type||(s?.some(f=>!e.subtypes.includes(f))??!1)||n!==void 0&&(typeof n=="string"&&!a.nameEquals(n,e.name)||n instanceof RegExp&&!n.test(e.name)))return!1;if(o){for(const[f,u]of Object.entries(o))if(e.txt?.[f]===void 0||typeof u=="string"&&u!==e.txt[f]||u instanceof RegExp&&!u.test(e.txt[f]))return!1}return!0}setupTTLTimer(e){e.ttl!==void 0&&(e.ttlTimer=setTimeout(()=>{e.expired&&this.removeService(e.fqdn)},e.ttl*1e3))}addService(e){this.match(e)&&(this.services.push(e),this.setupTTLTimer(e),this.emit("up",e))}updateService(e){if(!this.match(e)){this.removeService(e.fqdn);return}for(let t=0;t<this.services.length;++t){const i=this.services[t];if(a.nameEquals(i.fqdn,e.fqdn)){clearTimeout(i.ttlTimer),this.services[t]=e,this.setupTTLTimer(e),this.emit("update",e,i);break}}}removeService(e){for(let t=0;t<this.services.length;++t){const i=this.services[t];if(i&&a.nameEquals(i.fqdn,e)){this.services.splice(t,1),clearTimeout(i.ttlTimer),this.emit("down",i);return}}}};r.TLD=".local",r.WILDCARD="_services._dns-sd._udp"+r.TLD;let l=r;exports.Browser=l; //# sourceMappingURL=Browser.cjs.map