| 
 | 1 | +"use strict";  | 
 | 2 | + | 
 | 3 | +/*  | 
 | 4 | + * Based on the packages get-port https://www.npmjs.com/package/get-port  | 
 | 5 | + * and portfinder https://www.npmjs.com/package/portfinder  | 
 | 6 | + * The code structure is similar to get-port, but it searches  | 
 | 7 | + * ports deterministically like portfinder  | 
 | 8 | + */  | 
 | 9 | +const net = require("net");  | 
 | 10 | +const os = require("os");  | 
 | 11 | + | 
 | 12 | +const minPort = 1024;  | 
 | 13 | +const maxPort = 65_535;  | 
 | 14 | + | 
 | 15 | +/**  | 
 | 16 | + * @return {Set<string|undefined>}  | 
 | 17 | + */  | 
 | 18 | +const getLocalHosts = () => {  | 
 | 19 | +  const interfaces = os.networkInterfaces();  | 
 | 20 | + | 
 | 21 | +  // Add undefined value for createServer function to use default host,  | 
 | 22 | +  // and default IPv4 host in case createServer defaults to IPv6.  | 
 | 23 | +  // eslint-disable-next-line no-undefined  | 
 | 24 | +  const results = new Set([undefined, "0.0.0.0"]);  | 
 | 25 | + | 
 | 26 | +  for (const _interface of Object.values(interfaces)) {  | 
 | 27 | +    if (_interface) {  | 
 | 28 | +      for (const config of _interface) {  | 
 | 29 | +        results.add(config.address);  | 
 | 30 | +      }  | 
 | 31 | +    }  | 
 | 32 | +  }  | 
 | 33 | + | 
 | 34 | +  return results;  | 
 | 35 | +};  | 
 | 36 | + | 
 | 37 | +/**  | 
 | 38 | + * @param {number} basePort  | 
 | 39 | + * @param {string | undefined} host  | 
 | 40 | + * @return {Promise<number>}  | 
 | 41 | + */  | 
 | 42 | +const checkAvailablePort = (basePort, host) =>  | 
 | 43 | +  new Promise((resolve, reject) => {  | 
 | 44 | +    const server = net.createServer();  | 
 | 45 | +    server.unref();  | 
 | 46 | +    server.on("error", reject);  | 
 | 47 | + | 
 | 48 | +    server.listen(basePort, host, () => {  | 
 | 49 | +      // Next line should return AdressInfo because we're calling it after listen() and before close()  | 
 | 50 | +      const { port } = /** @type {import("net").AddressInfo} */ (  | 
 | 51 | +        server.address()  | 
 | 52 | +      );  | 
 | 53 | +      server.close(() => {  | 
 | 54 | +        resolve(port);  | 
 | 55 | +      });  | 
 | 56 | +    });  | 
 | 57 | +  });  | 
 | 58 | + | 
 | 59 | +/**  | 
 | 60 | + * @param {number} port  | 
 | 61 | + * @param {Set<string|undefined>} hosts  | 
 | 62 | + * @return {Promise<number>}  | 
 | 63 | + */  | 
 | 64 | +const getAvailablePort = async (port, hosts) => {  | 
 | 65 | +  /**  | 
 | 66 | +   * Errors that mean that host is not available.  | 
 | 67 | +   * @type {Set<string | undefined>}  | 
 | 68 | +   */  | 
 | 69 | +  const nonExistentInterfaceErrors = new Set(["EADDRNOTAVAIL", "EINVAL"]);  | 
 | 70 | +  /* Check if the post is available on every local host name */  | 
 | 71 | +  for (const host of hosts) {  | 
 | 72 | +    try {  | 
 | 73 | +      await checkAvailablePort(port, host); // eslint-disable-line no-await-in-loop  | 
 | 74 | +    } catch (error) {  | 
 | 75 | +      /* We throw an error only if the interface exists */  | 
 | 76 | +      if (  | 
 | 77 | +        !nonExistentInterfaceErrors.has(  | 
 | 78 | +          /** @type {NodeJS.ErrnoException} */ (error).code  | 
 | 79 | +        )  | 
 | 80 | +      ) {  | 
 | 81 | +        throw error;  | 
 | 82 | +      }  | 
 | 83 | +    }  | 
 | 84 | +  }  | 
 | 85 | + | 
 | 86 | +  return port;  | 
 | 87 | +};  | 
 | 88 | + | 
 | 89 | +/**  | 
 | 90 | + * @param {number} basePort  | 
 | 91 | + * @return {Promise<number>}  | 
 | 92 | + */  | 
 | 93 | +async function getPorts(basePort) {  | 
 | 94 | +  if (basePort < minPort || basePort > maxPort) {  | 
 | 95 | +    throw new Error(`Port number must lie between ${minPort} and ${maxPort}`);  | 
 | 96 | +  }  | 
 | 97 | + | 
 | 98 | +  let port = basePort;  | 
 | 99 | +  const hosts = getLocalHosts();  | 
 | 100 | +  /** @type {Set<string | undefined>} */  | 
 | 101 | +  const portUnavailableErrors = new Set(["EADDRINUSE", "EACCES"]);  | 
 | 102 | +  while (port <= maxPort) {  | 
 | 103 | +    try {  | 
 | 104 | +      const availablePort = await getAvailablePort(port, hosts); // eslint-disable-line no-await-in-loop  | 
 | 105 | +      return availablePort;  | 
 | 106 | +    } catch (error) {  | 
 | 107 | +      /* Try next port if port is busy; throw for any other error */  | 
 | 108 | +      if (  | 
 | 109 | +        !portUnavailableErrors.has(  | 
 | 110 | +          /** @type {NodeJS.ErrnoException} */ (error).code  | 
 | 111 | +        )  | 
 | 112 | +      ) {  | 
 | 113 | +        throw error;  | 
 | 114 | +      }  | 
 | 115 | +      port += 1;  | 
 | 116 | +    }  | 
 | 117 | +  }  | 
 | 118 | + | 
 | 119 | +  throw new Error("No available ports found");  | 
 | 120 | +}  | 
 | 121 | + | 
 | 122 | +module.exports = getPorts;  | 
0 commit comments