@palettelab/cli 0.3.9 → 0.3.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/ports.js +27 -2
- package/package.json +1 -1
package/lib/ports.js
CHANGED
|
@@ -13,13 +13,38 @@ function canBindPort(port, host = "0.0.0.0") {
|
|
|
13
13
|
})
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
function canConnectPort(port, host, timeoutMs = 250) {
|
|
17
|
+
return new Promise((resolve) => {
|
|
18
|
+
const socket = net.createConnection({ port, host })
|
|
19
|
+
const done = (connected) => {
|
|
20
|
+
socket.removeAllListeners()
|
|
21
|
+
socket.destroy()
|
|
22
|
+
resolve(connected)
|
|
23
|
+
}
|
|
24
|
+
socket.setTimeout(timeoutMs)
|
|
25
|
+
socket.once("connect", () => done(true))
|
|
26
|
+
socket.once("timeout", () => done(false))
|
|
27
|
+
socket.once("error", () => done(false))
|
|
28
|
+
})
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function isPortAvailable(port, { bindHost = "0.0.0.0" } = {}) {
|
|
32
|
+
// Docker publishes host ports on localhost-facing addresses. A process bound
|
|
33
|
+
// only to 127.0.0.1 or ::1 can be missed by a single 0.0.0.0 bind probe on
|
|
34
|
+
// some host setups, so test the addresses users actually open in browsers.
|
|
35
|
+
for (const host of ["127.0.0.1", "::1", "localhost"]) {
|
|
36
|
+
if (await canConnectPort(port, host)) return false
|
|
37
|
+
}
|
|
38
|
+
return canBindPort(port, bindHost)
|
|
39
|
+
}
|
|
40
|
+
|
|
16
41
|
async function findFreePort(preferred, { host = "0.0.0.0", maxAttempts = 100 } = {}) {
|
|
17
42
|
const start = Number(preferred)
|
|
18
43
|
if (!Number.isInteger(start) || start <= 0 || start > 65535) {
|
|
19
44
|
throw new Error(`invalid port: ${preferred}`)
|
|
20
45
|
}
|
|
21
46
|
for (let port = start; port < start + maxAttempts && port <= 65535; port++) {
|
|
22
|
-
if (await
|
|
47
|
+
if (await isPortAvailable(port, { bindHost: host })) return port
|
|
23
48
|
}
|
|
24
49
|
throw new Error(`no free port found from ${start} to ${Math.min(start + maxAttempts - 1, 65535)}`)
|
|
25
50
|
}
|
|
@@ -39,4 +64,4 @@ async function resolveDevPorts({
|
|
|
39
64
|
}
|
|
40
65
|
}
|
|
41
66
|
|
|
42
|
-
module.exports = { canBindPort, findFreePort, resolveDevPorts }
|
|
67
|
+
module.exports = { canBindPort, canConnectPort, isPortAvailable, findFreePort, resolveDevPorts }
|