"use strict"; // Preloaded with node --require into an example that a test runs. An example connects to the broker of Alex2MQTT, // the test has one on 127.0.0.1: every TCP connection of the process goes to LOOPBACK_PORT on 127.0.0.1, whatever // host and port it names. Nothing of an example under test leaves the machine. const net = require("node:net"); const port = Number(process.env.LOOPBACK_PORT); if (!Number.isInteger(port) || port <= 0) throw new Error("LOOPBACK_PORT is not set: the port of the broker of the test"); const connect = net.Socket.prototype.connect; net.Socket.prototype.connect = function toLoopback(...args) { // connect(options, listener), connect(port, host, listener), or the two in an array as net.createConnection() passes them const given = Array.isArray(args[0]) ? args[0] : args; const listener = given.find((arg) => typeof arg === "function"); return connect.call(this, { host: "127.0.0.1", port }, ...(listener ? [listener] : [])); };