sterfive-bonjour-service
Version:
A Bonjour/Zeroconf implementation in TypeScript
133 lines • 3.58 kB
JavaScript
;
/**
* Bonjour Service - Service Definition
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Service = void 0;
const os_1 = require("os");
const events_1 = require("events");
const service_types_1 = require("./service-types");
const dns_txt_1 = __importDefault(require("./dns-txt"));
const TLD = '.local';
/**
* Provide PTR record
* @param service
* @returns
*/
function RecordPTR(service) {
return {
name: `${service.type}${TLD}`,
type: 'PTR',
ttl: 28800,
data: service.fqdn
};
}
/**
* Provide SRV record
* @param service
* @returns
*/
function RecordSRV(service) {
return {
name: service.fqdn,
type: 'SRV',
ttl: 120,
data: {
port: service.port,
target: service.host
}
};
}
/**
* Provide TXT record
* @param service
* @returns
*/
function RecordTXT(service) {
const txtService = new dns_txt_1.default();
return {
name: service.fqdn,
type: 'TXT',
ttl: 4500,
data: txtService.encode(service.txt)
};
}
/**
* Provide A record
* @param service
* @param ip
* @returns
*/
function RecordA(service, ip) {
return {
name: service.host,
type: 'A',
ttl: 120,
data: ip
};
}
/**
* Provide AAAA record
* @param service
* @param ip
* @returns
*/
function RecordAAAA(service, ip) {
return {
name: service.host,
type: 'AAAA',
ttl: 120,
data: ip
};
}
class Service extends events_1.EventEmitter {
constructor(config) {
super();
this.probe = true;
this.published = false;
this.activated = false;
this.destroyed = false;
if (!config.name)
throw new Error('Required name not given');
if (!config.type)
throw new Error('Required type not given');
if (!config.port)
throw new Error('Required port not given');
this.name = config.name;
this.protocol = config.protocol || 'tcp';
this.type = (0, service_types_1.toString)({ name: config.type, protocol: this.protocol });
this.port = config.port;
this.host = config.host || (0, os_1.hostname)();
this.fqdn = `${this.name}.${this.type}${TLD}`;
this.txt = config.txt;
this.subtypes = config.subtypes;
}
records() {
const records = [RecordPTR(this), RecordSRV(this), RecordTXT(this)];
// Create record per interface address
const ifaces = Object.values((0, os_1.networkInterfaces)());
for (let iface of ifaces) {
let addrs = iface;
for (let addr of addrs) {
if (addr.internal || addr.mac === '00:00:00:00:00:00')
continue;
switch (addr.family) {
case 'IPv4':
records.push(RecordA(this, addr.address));
break;
case 'IPv6':
records.push(RecordAAAA(this, addr.address));
break;
}
}
}
// Return all records
return records;
}
}
exports.Service = Service;
exports.default = Service;
//# sourceMappingURL=service.js.map