"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.sendInParallel = sendInParallel;
exports.sendMessage = sendMessage;
var _dgram = _interopRequireDefault(require("dgram"));
var _net = _interopRequireDefault(require("net"));
var _nodeUrl = _interopRequireDefault(require("node:url"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
async function sendInParallel(addresses, port, request, signal) {
  signal.throwIfAborted();
  return await new Promise((resolve, reject) => {
    const sockets = [];
    let errorCount = 0;
    const onError = err => {
      errorCount++;
      if (errorCount === addresses.length) {
        signal.removeEventListener('abort', onAbort);
        clearSockets();
        reject(err);
      }
    };
    const onMessage = message => {
      signal.removeEventListener('abort', onAbort);
      clearSockets();
      resolve(message);
    };
    const onAbort = () => {
      clearSockets();
      reject(signal.reason);
    };
    const clearSockets = () => {
      for (const socket of sockets) {
        socket.removeListener('error', onError);
        socket.removeListener('message', onMessage);
        socket.close();
      }
    };
    signal.addEventListener('abort', onAbort, {
      once: true
    });
    for (let j = 0; j < addresses.length; j++) {
      const udpType = addresses[j].family === 6 ? 'udp6' : 'udp4';
      const socket = _dgram.default.createSocket(udpType);
      sockets.push(socket);
      socket.on('error', onError);
      socket.on('message', onMessage);
      socket.send(request, 0, request.length, port, addresses[j].address);
    }
  });
}
async function sendMessage(host, port, lookup, signal, request) {
  signal.throwIfAborted();
  let addresses;
  if (_net.default.isIP(host)) {
    addresses = [{
      address: host,
      family: _net.default.isIPv6(host) ? 6 : 4
    }];
  } else {
    addresses = await new Promise((resolve, reject) => {
      const onAbort = () => {
        reject(signal.reason);
      };
      const domainInASCII = _nodeUrl.default.domainToASCII(host);
      lookup(domainInASCII === '' ? host : domainInASCII, {
        all: true
      }, (err, addresses) => {
        signal.removeEventListener('abort', onAbort);
        err ? reject(err) : resolve(addresses);
      });
    });
  }
  return await sendInParallel(addresses, port, request, signal);
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 7680 characters]