port-reclaim 0.3.0 → 0.4.0

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/README.md CHANGED
@@ -34,13 +34,14 @@ Requires Node.js 18 or newer. Supports macOS, Linux, Windows, WSL, PowerShell, a
34
34
 
35
35
  ```sh
36
36
  port-reclaim <PORT> [PORT ...]
37
+ port-reclaim --match <REGEX>
37
38
  ```
38
39
 
39
- If the port is free, the command verifies it by briefly binding the port, then exits successfully. If the port is in use but no owning process is visible to the current user, the command reports that instead of claiming success. If the process working directory matches the current project, the process is terminated automatically. Processes from another directory, system services, and processes whose working directory cannot be read require explicit confirmation. Confirmation prompts show the process name, working directory, and uptime.
40
+ If the port is free, the command verifies it by briefly binding the port, then exits successfully. If the port is in use but no owning process is visible to the current user, the command reports that instead of claiming success. If the process working directory matches the current project, the process is terminated automatically — except for known data services (`postgres`, `postmaster`, `mysqld`, `mariadbd`, `mongod`, `redis-server`, `memcached`, `etcd`), which always ask first even when they share your directory. Processes from another directory, system services, and processes whose working directory cannot be read require explicit confirmation. Confirmation prompts show the process name, working directory, and uptime.
40
41
 
41
42
  The command uses a graceful termination signal first on Unix-like systems and falls back to a forceful signal if the process remains alive. Windows uses `taskkill /F`.
42
43
 
43
- If confirmation is required in a non-interactive environment, the command declines safely and exits with status `1` (rerun with `--yes` to override).
44
+ If confirmation is required in a non-interactive environment, the command declines safely and exits with status `1` (rerun with `--yes` to override). `--yes` skips prompts, including the protected-service prompt, but it cannot override a refusal — list a service's port in `.reclaimignore` to make it un-killable by accident.
44
45
 
45
46
  Ports held by Docker processes (for example `docker-proxy` or Docker Desktop) are never killed. The tool explains that the port looks like Docker and suggests stopping the container instead. The same refusal applies to operating-system PIDs (0–4, such as `System`/HTTP.sys on Windows or `systemd` on Linux), which are never signalled.
46
47
 
@@ -52,9 +53,26 @@ Both TCP and UDP listeners are discovered. Discovery costs one `netstat`/`lsof`
52
53
  | --- | --- |
53
54
  | `-l`, `--list` | Report what is using each port without killing anything. |
54
55
  | `-y`, `--yes` | Terminate processes from other directories without prompting. |
56
+ | `-m`, `--match REGEX` | Reclaim every port held by a process whose name matches REGEX, instead of naming ports. |
57
+ | `--no-color` | Disable coloured output. |
55
58
  | `-h`, `--help` | Show the help message. |
56
59
  | `-v`, `--version` | Show the installed version. |
57
60
 
61
+ ### Reclaiming by process name
62
+
63
+ When you do not know which ports are involved, select by command name instead. `--match` scans every listening socket, keeps the processes whose name matches the regular expression (case-insensitive), and reclaims every port each one holds:
64
+
65
+ ```sh
66
+ port-reclaim --match 'next-server|vite' --list
67
+ port-reclaim --match '^node$' --yes
68
+ ```
69
+
70
+ The same safety rules apply: refusals still block Docker and operating-system PIDs, data services still prompt, and a process holding any protected port is skipped entirely. `--match` cannot be combined with port arguments, and an invalid expression exits with status `2`.
71
+
72
+ ### Colour
73
+
74
+ Successes are green, refusals and errors red, prompts yellow, and process details dim. Colour switches itself off when output is redirected, and can be forced off with `--no-color` or the `NO_COLOR` environment variable.
75
+
58
76
  ## Configuration
59
77
 
60
78
  Ports can be declared once so scripts can run plain `port-reclaim` with no arguments. Add a `port-reclaim` key to `package.json`:
@@ -129,11 +147,11 @@ if (found.length === 0 && (await runner.probe(3000)) === "occupied") {
129
147
  }
130
148
  ```
131
149
 
132
- `discover()` reports what is on a port, `terminate()` ends one PID, and `probe()` answers whether the port is bindable at all — `"free"`, `"occupied"`, or `"unknown"` when the OS refuses to say. A `refusal` reason on a discovered process means `port-reclaim` will not kill it, whatever the caller asks; `terminate()` is still available if you decide otherwise.
150
+ `discover()` reports what is on a port, `terminate()` ends one PID, `probe()` answers whether the port is bindable at all — `"free"`, `"occupied"`, or `"unknown"` when the OS refuses to say — and `discoverListening(regex)` works the other way, returning every listening process whose name matches along with all the ports it holds. A `refusal` reason on a discovered process means `port-reclaim` will not kill it, whatever the caller asks; `terminate()` is still available if you decide otherwise. `alwaysConfirm` marks a process the CLI will not auto-kill just because it shares your directory.
133
151
 
134
152
  ## Security Notes
135
153
 
136
- `port-reclaim` only acts on processes listening on the port you provide. It does not scan remote hosts, and it refuses to kill Docker processes and operating-system PIDs (0–4) — stop those containers and services yourself. Ports protected by `.reclaimignore` or the `ignore` config are always skipped. Review the process name and working directory before confirming a process from another project. UDP matches are heuristic: a UDP socket on a port can belong to a client as well as a server. To confirm a port is free, the tool binds it momentarily and releases it, so a connection arriving in that instant can be reported as in use.
154
+ `port-reclaim` only acts on processes listening on the port you provide. It does not scan remote hosts, and it refuses to kill Docker processes and operating-system PIDs (0–4) — stop those containers and services yourself. Known data services are never auto-killed even when their working directory matches yours, but `--yes` does override that prompt, so protect the ports that matter with `.reclaimignore`. Ports protected by `.reclaimignore` or the `ignore` config are always skipped. Review the process name and working directory before confirming a process from another project. UDP matches are heuristic: a UDP socket on a port can belong to a client as well as a server. To confirm a port is free, the tool binds it momentarily and releases it, so a connection arriving in that instant can be reported as in use.
137
155
 
138
156
  ## Development
139
157
 
@@ -4,5 +4,7 @@ export interface CliOptions {
4
4
  version: boolean;
5
5
  yes: boolean;
6
6
  list: boolean;
7
+ noColor: boolean;
8
+ match?: string;
7
9
  }
8
10
  export declare function parseArgs(argv: string[]): CliOptions | undefined;
package/dist/src/args.js CHANGED
@@ -2,6 +2,8 @@ const HELP_FLAGS = new Set(["--help", "-h"]);
2
2
  const VERSION_FLAGS = new Set(["--version", "-v"]);
3
3
  const YES_FLAGS = new Set(["--yes", "-y", "--force", "-f"]);
4
4
  const LIST_FLAGS = new Set(["--list", "-l"]);
5
+ const NO_COLOR_FLAGS = new Set(["--no-color"]);
6
+ const MATCH_FLAGS = new Set(["--match", "-m"]);
5
7
  function parsePort(value) {
6
8
  if (!/^\d+$/.test(value))
7
9
  return undefined;
@@ -9,9 +11,23 @@ function parsePort(value) {
9
11
  return port >= 1 && port <= 65535 ? port : undefined;
10
12
  }
11
13
  export function parseArgs(argv) {
12
- const options = { ports: [], help: false, version: false, yes: false, list: false };
13
- for (const arg of argv) {
14
- if (HELP_FLAGS.has(arg)) {
14
+ const options = { ports: [], help: false, version: false, yes: false, list: false, noColor: false };
15
+ for (let index = 0; index < argv.length; index += 1) {
16
+ const arg = argv[index];
17
+ if (MATCH_FLAGS.has(arg)) {
18
+ const value = argv[index + 1];
19
+ if (value === undefined || value.startsWith("-") || options.match !== undefined)
20
+ return undefined;
21
+ options.match = value;
22
+ index += 1;
23
+ }
24
+ else if (arg.startsWith("--match=")) {
25
+ const value = arg.slice("--match=".length);
26
+ if (!value || options.match !== undefined)
27
+ return undefined;
28
+ options.match = value;
29
+ }
30
+ else if (HELP_FLAGS.has(arg)) {
15
31
  options.help = true;
16
32
  }
17
33
  else if (VERSION_FLAGS.has(arg)) {
@@ -23,6 +39,9 @@ export function parseArgs(argv) {
23
39
  else if (LIST_FLAGS.has(arg)) {
24
40
  options.list = true;
25
41
  }
42
+ else if (NO_COLOR_FLAGS.has(arg)) {
43
+ options.noColor = true;
44
+ }
26
45
  else {
27
46
  const port = parsePort(arg);
28
47
  if (port === undefined)
package/dist/src/cli.js CHANGED
@@ -7,15 +7,18 @@ import { pathToFileURL } from "node:url";
7
7
  import { createProcessRunner } from "./process.js";
8
8
  import { parseArgs } from "./args.js";
9
9
  import { loadConfig } from "./config.js";
10
- const USAGE = `Usage: port-reclaim [options] <PORT ...>
10
+ import { paint, setColourMode } from "./style.js";
11
+ const USAGE = `Usage: port-reclaim [options] [PORT ...]
11
12
 
12
13
  Safely reclaim local ports held by stale development processes.
13
14
 
14
15
  Options:
15
- -l, --list Report what is using each port without killing anything.
16
- -y, --yes Terminate processes from other directories without prompting.
17
- -h, --help Show this help message.
18
- -v, --version Show the installed version.
16
+ -l, --list Report what is using each port without killing anything.
17
+ -y, --yes Terminate processes without prompting (never overrides a refusal).
18
+ -m, --match REGEX Reclaim every port held by a process whose name matches REGEX.
19
+ --no-color Disable coloured output.
20
+ -h, --help Show this help message.
21
+ -v, --version Show the installed version.
19
22
 
20
23
  Ports may also come from the "port-reclaim" key in package.json:
21
24
  "port-reclaim": { "ports": [3000, 5173], "ignore": [5432] }
@@ -43,6 +46,13 @@ function formatAge(ageMs) {
43
46
  return `${minutes}m ${totalSeconds % 60}s`;
44
47
  return `${totalSeconds}s`;
45
48
  }
49
+ function heading(ports) {
50
+ return ports.length > 1 ? `Ports ${ports.join(", ")}` : `Port ${ports[0]}`;
51
+ }
52
+ function lowercaseHeading(ports) {
53
+ const text = heading(ports);
54
+ return text.charAt(0).toLowerCase() + text.slice(1);
55
+ }
46
56
  function describe(portProcess) {
47
57
  const details = [`PID ${portProcess.pid}`];
48
58
  if (portProcess.cwd)
@@ -51,18 +61,37 @@ function describe(portProcess) {
51
61
  details.push(`up ${formatAge(portProcess.ageMs)}`);
52
62
  if (portProcess.protocol === "udp")
53
63
  details.push("udp");
54
- return `'${portProcess.name}' (${details.join(", ")})`;
64
+ return `${paint("bold", `'${portProcess.name}'`)} (${paint("dim", details.join(", "))})`;
55
65
  }
56
- async function confirm(portProcess, port) {
66
+ async function confirm(portProcess, ports) {
57
67
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
58
- console.error(`Port ${port} is used by ${describe(portProcess)}. Use an interactive terminal to confirm termination, or rerun with --yes.`);
68
+ console.error(`${paint("red", `${heading(ports)} is used by ${describe(portProcess)}.`)} ${paint("yellow", "Use an interactive terminal to confirm termination, or rerun with --yes.")}`);
59
69
  return false;
60
70
  }
61
71
  const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
62
- const answer = await prompt.question(`Port ${port} is used by ${describe(portProcess)}. Kill it? (y/N) `);
72
+ const answer = await prompt.question(paint("yellow", `${heading(ports)} is used by ${describe(portProcess)}. Kill it? (y/N) `));
63
73
  prompt.close();
64
74
  return /^y(es)?$/i.test(answer.trim());
65
75
  }
76
+ async function resolveProcess(portProcess, runner, options, ports) {
77
+ if (portProcess.refusal) {
78
+ console.error(paint("red", `${heading(ports)} is used by ${describe(portProcess)}. Refusing to kill it — ${portProcess.refusal}`));
79
+ return false;
80
+ }
81
+ const sameProject = sameDirectory(portProcess.cwd, process.cwd()) && !portProcess.alwaysConfirm;
82
+ if (!(sameProject || options.yes || await confirm(portProcess, ports)))
83
+ return false;
84
+ await runner.terminate(portProcess.pid);
85
+ console.log(paint("green", `Released ${lowercaseHeading(ports)} from ${portProcess.name} (PID ${portProcess.pid}).`));
86
+ return true;
87
+ }
88
+ function reportProcess(portProcess, port) {
89
+ const origin = sameDirectory(portProcess.cwd, process.cwd())
90
+ ? "matches the current directory"
91
+ : portProcess.cwd ? `'${portProcess.cwd}'` : "an unreadable working directory";
92
+ const refusal = portProcess.refusal ? ` ${paint("red", "[refused]")}` : "";
93
+ console.log(`Port ${port} is used by ${describe(portProcess)}${refusal} — ${origin}.`);
94
+ }
66
95
  async function version() {
67
96
  try {
68
97
  const pkg = JSON.parse(await readFile(new URL("../../package.json", import.meta.url), "utf8"));
@@ -72,44 +101,65 @@ async function version() {
72
101
  return "unknown";
73
102
  }
74
103
  }
75
- async function reclaimPort(port, runner, options) {
76
- const portProcesses = await runner.discover(port);
104
+ async function reclaimPort(port, runner, options, known) {
105
+ const portProcesses = known ?? await runner.discover(port);
77
106
  if (portProcesses.length === 0) {
78
107
  const state = await runner.probe(port);
79
108
  if (state === "occupied") {
80
- console.error(`Port ${port} is in use by a process port-reclaim cannot see — it may belong to another user or an elevated process, or be a socket still closing. Rerun with sudo or from an elevated PowerShell session, or inspect it with 'netstat -ano | findstr :${port}'.`);
109
+ console.error(paint("red", `Port ${port} is in use by a process port-reclaim cannot see — it may belong to another user, an elevated process, or a socket still closing.`));
110
+ console.error(`Rerun with sudo or from an elevated PowerShell session, or inspect it with 'netstat -ano | findstr :${port}'.`);
81
111
  return false;
82
112
  }
83
113
  if (options.list) {
84
- console.log(state === "free" ? `Port ${port} is free.` : `Port ${port} appears free but could not be verified.`);
114
+ console.log(state === "free" ? paint("green", `Port ${port} is free.`) : paint("yellow", `Port ${port} appears free but could not be verified.`));
85
115
  }
86
116
  return true;
87
117
  }
88
118
  let free = true;
89
- const currentDirectory = process.cwd();
90
119
  for (const portProcess of portProcesses) {
91
120
  if (options.list) {
92
- const origin = sameDirectory(portProcess.cwd, currentDirectory)
93
- ? "matches the current directory"
94
- : portProcess.cwd ? `'${portProcess.cwd}'` : "an unreadable working directory";
95
- const refusal = portProcess.refusal ? " [refused]" : "";
96
- console.log(`Port ${port} is used by ${describe(portProcess)}${refusal} — ${origin}.`);
121
+ reportProcess(portProcess, port);
97
122
  continue;
98
123
  }
99
- if (portProcess.refusal) {
100
- console.error(`Port ${port} is used by ${describe(portProcess)}. Refusing to kill it — ${portProcess.refusal}`);
124
+ if (!(await resolveProcess(portProcess, runner, options, [port])))
101
125
  free = false;
126
+ }
127
+ return free;
128
+ }
129
+ function isValidPattern(pattern) {
130
+ try {
131
+ new RegExp(pattern);
132
+ return true;
133
+ }
134
+ catch {
135
+ return false;
136
+ }
137
+ }
138
+ async function reclaimMatching(runner, options, pattern, ignored) {
139
+ const found = await runner.discoverListening(new RegExp(pattern, "i"));
140
+ const matches = found.filter((portProcess) => (portProcess.ports?.length ?? 0) > 0);
141
+ if (matches.length === 0) {
142
+ console.log(paint("dim", `No listening process matches '${pattern}'.`));
143
+ return 0;
144
+ }
145
+ const sorted = matches.sort((left, right) => (left.ports?.[0] ?? 0) - (right.ports?.[0] ?? 0));
146
+ let exitCode = 0;
147
+ for (const portProcess of sorted) {
148
+ const ports = portProcess.ports ?? [];
149
+ const protectedPort = ports.find((port) => ignored.has(port));
150
+ if (protectedPort !== undefined) {
151
+ console.log(paint("yellow", `Skipping ${portProcess.name} (PID ${portProcess.pid}) — port ${protectedPort} is protected by .reclaimignore or config.`));
102
152
  continue;
103
153
  }
104
- const shouldTerminate = sameDirectory(portProcess.cwd, currentDirectory) || options.yes || await confirm(portProcess, port);
105
- if (!shouldTerminate) {
106
- free = false;
154
+ if (options.list) {
155
+ for (const port of ports)
156
+ reportProcess(portProcess, port);
107
157
  continue;
108
158
  }
109
- await runner.terminate(portProcess.pid);
110
- console.log(`Released port ${port} from ${portProcess.name} (PID ${portProcess.pid}).`);
159
+ if (!(await resolveProcess(portProcess, runner, options, ports)))
160
+ exitCode = 1;
111
161
  }
112
- return free;
162
+ return exitCode;
113
163
  }
114
164
  export async function main(argv = process.argv.slice(2), runner = createProcessRunner()) {
115
165
  const options = parseArgs(argv);
@@ -117,6 +167,7 @@ export async function main(argv = process.argv.slice(2), runner = createProcessR
117
167
  printUsage();
118
168
  return 2;
119
169
  }
170
+ setColourMode(options.noColor ? "never" : "auto");
120
171
  if (options.help) {
121
172
  console.log(USAGE);
122
173
  return 0;
@@ -127,6 +178,18 @@ export async function main(argv = process.argv.slice(2), runner = createProcessR
127
178
  }
128
179
  const config = await loadConfig(process.cwd());
129
180
  const ignored = new Set(config.ignore);
181
+ if (options.match !== undefined) {
182
+ if (!isValidPattern(options.match)) {
183
+ console.error(paint("red", `port-reclaim: '${options.match}' is not a valid regular expression.`));
184
+ return 2;
185
+ }
186
+ if (options.ports.length > 0) {
187
+ console.error(paint("red", "port-reclaim: pass either ports or --match, not both."));
188
+ printUsage();
189
+ return 2;
190
+ }
191
+ return reclaimMatching(runner, options, options.match, ignored);
192
+ }
130
193
  const ports = options.ports.length > 0 ? options.ports : config.ports;
131
194
  if (ports.length === 0) {
132
195
  printUsage();
@@ -135,18 +198,17 @@ export async function main(argv = process.argv.slice(2), runner = createProcessR
135
198
  let exitCode = 0;
136
199
  for (const port of ports) {
137
200
  if (ignored.has(port)) {
138
- console.log(`Port ${port} is protected by .reclaimignore or config — skipped.`);
201
+ console.log(paint("yellow", `Port ${port} is protected by .reclaimignore or config — skipped.`));
139
202
  continue;
140
203
  }
141
- const free = await reclaimPort(port, runner, options);
142
- if (!free)
204
+ if (!(await reclaimPort(port, runner, options)))
143
205
  exitCode = 1;
144
206
  }
145
207
  return exitCode;
146
208
  }
147
209
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
148
210
  main().then((code) => process.exit(code)).catch((error) => {
149
- console.error(`port-reclaim: ${error.message}`);
211
+ console.error(paint("red", `port-reclaim: ${error.message}`));
150
212
  process.exit(1);
151
213
  });
152
214
  }
@@ -1,5 +1,7 @@
1
- export { createProcessRunner, parseEtime, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, refusalReason, } from "./process.js";
2
- export type { NetstatPid, PortProcess, PortState, ProcessRow, ProcessRunner, Protocol, } from "./process.js";
1
+ export { createProcessRunner, parseEtime, parseNetstatListeners, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, parseUnixLsofListeners, isProtectedService, refusalReason, } from "./process.js";
2
+ export type { ListenerRow, NetstatPid, PortProcess, PortState, ProcessRow, ProcessRunner, Protocol, } from "./process.js";
3
+ export { colourEnabled, paint, setColourMode } from "./style.js";
4
+ export type { Colour, ColourMode } from "./style.js";
3
5
  export { loadConfig, parsePackageConfig, parseReclaimignore } from "./config.js";
4
6
  export type { ReclaimConfig } from "./config.js";
5
7
  export { parseArgs } from "./args.js";
package/dist/src/index.js CHANGED
@@ -1,3 +1,4 @@
1
- export { createProcessRunner, parseEtime, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, refusalReason, } from "./process.js";
1
+ export { createProcessRunner, parseEtime, parseNetstatListeners, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, parseUnixLsofListeners, isProtectedService, refusalReason, } from "./process.js";
2
+ export { colourEnabled, paint, setColourMode } from "./style.js";
2
3
  export { loadConfig, parsePackageConfig, parseReclaimignore } from "./config.js";
3
4
  export { parseArgs } from "./args.js";
@@ -6,16 +6,27 @@ export interface PortProcess {
6
6
  cwd?: string;
7
7
  protocol?: Protocol;
8
8
  ageMs?: number;
9
+ ports?: number[];
9
10
  refusal?: string;
11
+ alwaysConfirm?: boolean;
10
12
  }
11
13
  export interface ProcessRunner {
12
14
  discover(port: number): Promise<PortProcess[]>;
15
+ discoverListening(match: RegExp): Promise<PortProcess[]>;
13
16
  terminate(pid: number): Promise<void>;
14
17
  probe(port: number): Promise<PortState>;
15
18
  }
19
+ export interface ListenerRow {
20
+ pid: number;
21
+ port: number;
22
+ protocol: Protocol;
23
+ }
24
+ export declare function isProtectedService(name: string): boolean;
16
25
  export declare function refusalReason(pid: number, name: string): string | undefined;
17
26
  export declare function parseUnixLsof(output: string): number[];
18
27
  export declare function parseEtime(value: string): number | undefined;
28
+ export declare function parseNetstatListeners(output: string): ListenerRow[];
29
+ export declare function parseUnixLsofListeners(output: string, protocol: Protocol): ListenerRow[];
19
30
  export interface NetstatPid {
20
31
  pid: number;
21
32
  protocol: Protocol;
@@ -7,6 +7,12 @@ import pidCwd from "pid-cwd";
7
7
  const execFileAsync = promisify(execFile);
8
8
  const DOCKER_PROCESS = /docker|vpnkit/i;
9
9
  const SYSTEM_PID_CEILING = 4;
10
+ // Data services can legitimately run with their working directory inside a project, which is
11
+ // the exact condition the same-directory auto-kill shortcut trusts. They never auto-kill.
12
+ const PROTECTED_SERVICES = new Set(["postgres", "postmaster", "mysqld", "mariadbd", "mongod", "redis-server", "memcached", "etcd"]);
13
+ export function isProtectedService(name) {
14
+ return PROTECTED_SERVICES.has(name.trim().toLowerCase());
15
+ }
10
16
  export function refusalReason(pid, name) {
11
17
  if (DOCKER_PROCESS.test(name)) {
12
18
  return "it appears to be a Docker process — stop the container instead (for example 'docker stop <container>').";
@@ -41,6 +47,50 @@ export function parseEtime(value) {
41
47
  }
42
48
  return (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000;
43
49
  }
50
+ export function parseNetstatListeners(output) {
51
+ const rows = [];
52
+ const seen = new Set();
53
+ for (const line of output.split(/\r?\n/)) {
54
+ const columns = line.trim().split(/\s+/);
55
+ const protocol = columns[0]?.toUpperCase();
56
+ if (protocol !== "TCP" && protocol !== "UDP")
57
+ continue;
58
+ if (protocol === "TCP" && columns[3]?.toUpperCase() !== "LISTENING")
59
+ continue;
60
+ const port = Number(columns[1]?.split(":").at(-1));
61
+ const pid = Number(columns.at(-1));
62
+ if (!Number.isInteger(port) || port <= 0 || !Number.isInteger(pid) || pid <= 0)
63
+ continue;
64
+ const key = `${pid}:${port}:${protocol}`;
65
+ if (seen.has(key))
66
+ continue;
67
+ seen.add(key);
68
+ rows.push({ pid, port, protocol: protocol.toLowerCase() });
69
+ }
70
+ return rows;
71
+ }
72
+ export function parseUnixLsofListeners(output, protocol) {
73
+ const rows = [];
74
+ const seen = new Set();
75
+ let pid = 0;
76
+ for (const line of output.split(/\r?\n/)) {
77
+ if (line.startsWith("p")) {
78
+ pid = Number(line.slice(1));
79
+ continue;
80
+ }
81
+ if (!line.startsWith("n") || !Number.isInteger(pid) || pid <= 0)
82
+ continue;
83
+ const port = Number(line.slice(1).split(":").at(-1));
84
+ if (!Number.isInteger(port) || port <= 0)
85
+ continue;
86
+ const key = `${pid}:${port}`;
87
+ if (seen.has(key))
88
+ continue;
89
+ seen.add(key);
90
+ rows.push({ pid, port, protocol });
91
+ }
92
+ return rows;
93
+ }
44
94
  export function parseNetstatPids(output, port) {
45
95
  const results = [];
46
96
  const seen = new Set();
@@ -126,6 +176,17 @@ function byPid(rows) {
126
176
  function describe(pid, protocol, info) {
127
177
  return { pid, protocol, name: info?.name ?? "unknown", ageMs: info?.ageMs };
128
178
  }
179
+ function powershell(script) {
180
+ return run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
181
+ }
182
+ async function processNames(pids) {
183
+ if (pids.length === 0)
184
+ return new Map();
185
+ if (process.platform === "win32") {
186
+ return byPid(parsePipeTable(await powershell(windowsNamesScript(pids))));
187
+ }
188
+ return byPid(parsePsTable(await run("ps", ["-p", pids.join(","), "-o", "pid=,comm=,etime="])));
189
+ }
129
190
  async function discoverUnix(port) {
130
191
  const protocols = new Map();
131
192
  for (const pid of parseUnixLsof(await run("lsof", ["-nP", "-iUDP:" + port, "-Fp"])))
@@ -134,8 +195,7 @@ async function discoverUnix(port) {
134
195
  protocols.set(pid, "tcp");
135
196
  if (protocols.size === 0)
136
197
  return [];
137
- const output = await run("ps", ["-p", [...protocols.keys()].join(","), "-o", "pid=,comm=,etime="]);
138
- const infos = byPid(parsePsTable(output));
198
+ const infos = await processNames([...protocols.keys()]);
139
199
  return [...protocols].map(([pid, protocol]) => describe(pid, protocol, infos.get(pid)));
140
200
  }
141
201
  function windowsNameLoop(protocol) {
@@ -151,9 +211,44 @@ async function discoverWindows(port) {
151
211
  const entries = parseNetstatPids(await run("netstat.exe", ["-ano"]), port);
152
212
  if (entries.length === 0)
153
213
  return [];
154
- const infos = byPid(parsePipeTable(await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", windowsNamesScript(entries.map((entry) => entry.pid))])));
214
+ const infos = await processNames(entries.map((entry) => entry.pid));
155
215
  return entries.map((entry) => describe(entry.pid, entry.protocol, infos.get(entry.pid)));
156
216
  }
217
+ async function listUnixSockets() {
218
+ const tcp = await run("lsof", ["-nP", "-iTCP", "-sTCP:LISTEN", "-Fpn"]);
219
+ const udp = await run("lsof", ["-nP", "-iUDP", "-Fpn"]);
220
+ return [...parseUnixLsofListeners(tcp, "tcp"), ...parseUnixLsofListeners(udp, "udp")];
221
+ }
222
+ async function discoverListening(match) {
223
+ const rows = process.platform === "win32"
224
+ ? parseNetstatListeners(await run("netstat.exe", ["-ano"]))
225
+ : await listUnixSockets();
226
+ const sockets = new Map();
227
+ for (const row of rows) {
228
+ const entry = sockets.get(row.pid);
229
+ if (!entry) {
230
+ sockets.set(row.pid, { ports: [row.port], protocol: row.protocol });
231
+ }
232
+ else {
233
+ if (!entry.ports.includes(row.port))
234
+ entry.ports.push(row.port);
235
+ if (row.protocol === "tcp")
236
+ entry.protocol = "tcp";
237
+ }
238
+ }
239
+ const infos = await processNames([...sockets.keys()]);
240
+ const candidates = [...infos].filter(([, info]) => match.test(info.name));
241
+ return Promise.all(candidates.map(async ([pid, info]) => ({
242
+ pid,
243
+ name: info.name,
244
+ protocol: sockets.get(pid)?.protocol,
245
+ ageMs: info.ageMs,
246
+ ports: sockets.get(pid)?.ports.sort((left, right) => left - right),
247
+ cwd: (await pidCwd(pid)) ?? undefined,
248
+ refusal: refusalReason(pid, info.name),
249
+ alwaysConfirm: isProtectedService(info.name),
250
+ })));
251
+ }
157
252
  function probePort(port, protocol) {
158
253
  return new Promise((resolve) => {
159
254
  if (protocol === "tcp") {
@@ -186,8 +281,10 @@ export function createProcessRunner() {
186
281
  ...entry,
187
282
  cwd: (await pidCwd(entry.pid)) ?? undefined,
188
283
  refusal: refusalReason(entry.pid, entry.name),
284
+ alwaysConfirm: isProtectedService(entry.name),
189
285
  })));
190
286
  },
287
+ discoverListening,
191
288
  async terminate(pid) {
192
289
  if (process.platform === "win32") {
193
290
  // Without /F, taskkill cannot end console processes such as node dev servers.
@@ -0,0 +1,5 @@
1
+ export type Colour = "bold" | "dim" | "red" | "green" | "yellow";
2
+ export type ColourMode = "auto" | "always" | "never";
3
+ export declare function setColourMode(next: ColourMode): void;
4
+ export declare function colourEnabled(): boolean;
5
+ export declare function paint(colour: Colour, text: string): string;
@@ -0,0 +1,26 @@
1
+ import process from "node:process";
2
+ const CODES = {
3
+ bold: "\u001b[1m",
4
+ dim: "\u001b[2m",
5
+ red: "\u001b[31m",
6
+ green: "\u001b[32m",
7
+ yellow: "\u001b[33m",
8
+ };
9
+ const RESET = "\u001b[0m";
10
+ let mode = "auto";
11
+ export function setColourMode(next) {
12
+ mode = next;
13
+ }
14
+ export function colourEnabled() {
15
+ if (mode === "never")
16
+ return false;
17
+ if (mode === "always")
18
+ return true;
19
+ if (process.env.NO_COLOR)
20
+ return false;
21
+ return Boolean(process.stdout.isTTY);
22
+ }
23
+ // Wraps a whole segment rather than interpolating inside one, so message text stays greppable.
24
+ export function paint(colour, text) {
25
+ return colourEnabled() ? `${CODES[colour]}${text}${RESET}` : text;
26
+ }
@@ -1,20 +1,21 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import { parseArgs } from "../src/args.js";
4
+ const EMPTY = { ports: [], help: false, version: false, yes: false, list: false, noColor: false };
4
5
  test("parses multiple ports and deduplicates", () => {
5
- assert.deepEqual(parseArgs(["3000", "5173", "3000"]), {
6
- ports: [3000, 5173],
7
- help: false,
8
- version: false,
9
- yes: false,
10
- list: false,
11
- });
6
+ assert.deepEqual(parseArgs(["3000", "5173", "3000"]), { ...EMPTY, ports: [3000, 5173] });
12
7
  });
13
8
  test("parses flags", () => {
14
- assert.deepEqual(parseArgs(["-l", "--yes"]), { ports: [], help: false, version: false, yes: true, list: true });
15
- assert.deepEqual(parseArgs(["--list", "-y", "-f"]), { ports: [], help: false, version: false, yes: true, list: true });
16
- assert.deepEqual(parseArgs(["--help"]), { ports: [], help: true, version: false, yes: false, list: false });
17
- assert.deepEqual(parseArgs(["-v"]), { ports: [], help: false, version: true, yes: false, list: false });
9
+ assert.deepEqual(parseArgs(["-l", "--yes"]), { ...EMPTY, yes: true, list: true });
10
+ assert.deepEqual(parseArgs(["--list", "-y", "-f"]), { ...EMPTY, yes: true, list: true });
11
+ assert.deepEqual(parseArgs(["--help"]), { ...EMPTY, help: true });
12
+ assert.deepEqual(parseArgs(["-v"]), { ...EMPTY, version: true });
13
+ assert.deepEqual(parseArgs(["--no-color", "3000"]), { ...EMPTY, noColor: true, ports: [3000] });
14
+ });
15
+ test("parses --match with a pattern", () => {
16
+ assert.deepEqual(parseArgs(["--match", "next-server"]), { ...EMPTY, match: "next-server" });
17
+ assert.deepEqual(parseArgs(["-m", "^node$"]), { ...EMPTY, match: "^node$" });
18
+ assert.deepEqual(parseArgs(["--match=vue-cli"]), { ...EMPTY, match: "vue-cli" });
18
19
  });
19
20
  test("rejects invalid input", () => {
20
21
  assert.equal(parseArgs(["abc"]), undefined);
@@ -22,4 +23,8 @@ test("rejects invalid input", () => {
22
23
  assert.equal(parseArgs(["65536"]), undefined);
23
24
  assert.equal(parseArgs(["3000", "--nope"]), undefined);
24
25
  assert.equal(parseArgs(["-1"]), undefined);
26
+ assert.equal(parseArgs(["--match"]), undefined);
27
+ assert.equal(parseArgs(["--match", "--yes"]), undefined);
28
+ assert.equal(parseArgs(["--match", "a", "--match", "b"]), undefined);
29
+ assert.equal(parseArgs(["--match="]), undefined);
25
30
  });
@@ -5,9 +5,9 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
5
5
  import { tmpdir } from "node:os";
6
6
  import path from "node:path";
7
7
  import { main } from "../src/cli.js";
8
- import { refusalReason } from "../src/process.js";
9
- function fakeRunner(byPort, probeState = "free") {
10
- const calls = { discovered: [], terminated: [], probed: [] };
8
+ import { refusalReason, isProtectedService } from "../src/process.js";
9
+ function fakeRunner(byPort, probeState = "free", listening = []) {
10
+ const calls = { discovered: [], terminated: [], probed: [], patterns: [] };
11
11
  return {
12
12
  calls,
13
13
  runner: {
@@ -15,6 +15,10 @@ function fakeRunner(byPort, probeState = "free") {
15
15
  calls.discovered.push(port);
16
16
  return byPort[port] ?? [];
17
17
  },
18
+ async discoverListening(match) {
19
+ calls.patterns.push(match.source);
20
+ return listening;
21
+ },
18
22
  async terminate(pid) {
19
23
  calls.terminated.push(pid);
20
24
  },
@@ -88,6 +92,31 @@ test("terminates processes from the current directory without prompting", async
88
92
  output.restore();
89
93
  }
90
94
  });
95
+ test("prompts before killing a database even when it shares the project directory", async () => {
96
+ const postgres = { pid: 4242, name: "postgres", cwd: process.cwd(), alwaysConfirm: isProtectedService("postgres") };
97
+ const { runner, calls } = fakeRunner({ 5432: [postgres] });
98
+ const output = capture();
99
+ try {
100
+ assert.equal(await main(["5432"], runner), 1);
101
+ assert.deepEqual(calls.terminated, []);
102
+ assert.match(output.error.join("\n"), /interactive terminal/);
103
+ }
104
+ finally {
105
+ output.restore();
106
+ }
107
+ });
108
+ test("--yes still overrides the protected-service prompt", async () => {
109
+ const postgres = { pid: 4242, name: "postgres", cwd: process.cwd(), alwaysConfirm: isProtectedService("postgres") };
110
+ const { runner, calls } = fakeRunner({ 5432: [postgres] });
111
+ const output = capture();
112
+ try {
113
+ assert.equal(await main(["5432", "--yes"], runner), 0);
114
+ assert.deepEqual(calls.terminated, [4242]);
115
+ }
116
+ finally {
117
+ output.restore();
118
+ }
119
+ });
91
120
  test("declines foreign processes when not interactive", async () => {
92
121
  const { runner, calls } = fakeRunner({ 3000: [{ pid: 7, name: "node", cwd: "/somewhere/else" }] });
93
122
  const output = capture();
@@ -183,3 +212,110 @@ test("invalid input exits 2", async () => {
183
212
  output.restore();
184
213
  }
185
214
  });
215
+ function staleServer() {
216
+ return [{ pid: 77, name: "next-server", cwd: "/elsewhere", ports: [3000, 5173] }];
217
+ }
218
+ test("--match reclaims every port a matching process holds and kills it once", async () => {
219
+ const { runner, calls } = fakeRunner({}, "free", staleServer());
220
+ const output = capture();
221
+ try {
222
+ assert.equal(await main(["--match", "next-server", "--yes"], runner), 0);
223
+ assert.deepEqual(calls.patterns, ["next-server"]);
224
+ assert.deepEqual(calls.discovered, []);
225
+ assert.deepEqual(calls.terminated, [77]);
226
+ assert.match(output.log.join("\n"), /Released ports 3000, 5173 from next-server \(PID 77\)/);
227
+ }
228
+ finally {
229
+ output.restore();
230
+ }
231
+ });
232
+ test("--match honours refusals for protected processes", async () => {
233
+ const docker = { pid: 9, name: "docker-proxy", ports: [8080], refusal: refusalReason(9, "docker-proxy") };
234
+ const { runner, calls } = fakeRunner({}, "free", [docker]);
235
+ const output = capture();
236
+ try {
237
+ assert.equal(await main(["--match", "docker", "--yes"], runner), 1);
238
+ assert.deepEqual(calls.terminated, []);
239
+ assert.match(output.error.join("\n"), /Docker/);
240
+ }
241
+ finally {
242
+ output.restore();
243
+ }
244
+ });
245
+ test("--match skips a process holding a protected port", async () => {
246
+ const dir = await mkdtemp(path.join(tmpdir(), "port-reclaim-"));
247
+ const originalCwd = process.cwd();
248
+ const postgres = { pid: 4242, name: "postgres", cwd: "/var/lib/postgresql", ports: [5432], alwaysConfirm: isProtectedService("postgres") };
249
+ const { runner, calls } = fakeRunner({}, "free", [postgres]);
250
+ const output = capture();
251
+ try {
252
+ await writeFile(path.join(dir, ".reclaimignore"), "5432\n");
253
+ process.chdir(dir);
254
+ assert.equal(await main(["--match", "postgres", "--yes"], runner), 0);
255
+ assert.deepEqual(calls.terminated, []);
256
+ assert.match(output.log.join("\n"), /protected/);
257
+ }
258
+ finally {
259
+ process.chdir(originalCwd);
260
+ await rm(dir, { recursive: true, force: true });
261
+ output.restore();
262
+ }
263
+ });
264
+ test("--match reports when nothing listens under that name", async () => {
265
+ const { runner, calls } = fakeRunner({}, "free", []);
266
+ const output = capture();
267
+ try {
268
+ assert.equal(await main(["--match", "nothing-here", "--yes"], runner), 0);
269
+ assert.deepEqual(calls.terminated, []);
270
+ assert.match(output.log.join("\n"), /No listening process matches/);
271
+ }
272
+ finally {
273
+ output.restore();
274
+ }
275
+ });
276
+ test("an invalid --match pattern exits 2", async () => {
277
+ const { runner } = fakeRunner({});
278
+ const output = capture();
279
+ try {
280
+ assert.equal(await main(["--match", "("], runner), 2);
281
+ assert.match(output.error.join("\n"), /not a valid regular expression/);
282
+ }
283
+ finally {
284
+ output.restore();
285
+ }
286
+ });
287
+ test("--match cannot be combined with ports", async () => {
288
+ const { runner } = fakeRunner({});
289
+ const output = capture();
290
+ try {
291
+ assert.equal(await main(["3000", "--match", "node"], runner), 2);
292
+ assert.match(output.error.join("\n"), /either ports or --match/);
293
+ }
294
+ finally {
295
+ output.restore();
296
+ }
297
+ });
298
+ test("colour codes reach a terminal and --no-color suppresses them", async () => {
299
+ const originalTty = process.stdout.isTTY;
300
+ const originalNoColor = process.env.NO_COLOR;
301
+ delete process.env.NO_COLOR;
302
+ Object.defineProperty(process.stdout, "isTTY", { value: true, configurable: true });
303
+ const byPort = { 3000: [{ pid: 42, name: "node", cwd: process.cwd() }] };
304
+ try {
305
+ const coloured = capture();
306
+ await main(["3000"], fakeRunner(byPort).runner);
307
+ coloured.restore();
308
+ const plain = capture();
309
+ await main(["3000", "--no-color"], fakeRunner(byPort).runner);
310
+ plain.restore();
311
+ assert.match(coloured.log.join("\n"), /\u001b\[32m/);
312
+ assert.doesNotMatch(plain.log.join("\n"), /\u001b\[/);
313
+ }
314
+ finally {
315
+ Object.defineProperty(process.stdout, "isTTY", { value: originalTty, configurable: true });
316
+ if (originalNoColor === undefined)
317
+ delete process.env.NO_COLOR;
318
+ else
319
+ process.env.NO_COLOR = originalNoColor;
320
+ }
321
+ });
@@ -1,6 +1,6 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { parseEtime, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, refusalReason, } from "../src/process.js";
3
+ import { parseEtime, parseNetstatListeners, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, parseUnixLsofListeners, isProtectedService, refusalReason, } from "../src/process.js";
4
4
  test("parses lsof PID records", () => {
5
5
  assert.deepEqual(parseUnixLsof("p1234\ncnode\np5678\np1234\n"), [1234, 5678]);
6
6
  });
@@ -36,6 +36,45 @@ test("drops PID 0, keeps PID 4 for the refusal layer, and deduplicates rows", ()
36
36
  { pid: 77, name: "node", ageMs: 30, protocol: undefined },
37
37
  ]);
38
38
  });
39
+ test("parses every listener from a full netstat table", () => {
40
+ const output = [
41
+ " Proto Local Address Foreign Address State PID",
42
+ " TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 4",
43
+ " TCP 127.0.0.1:3000 127.0.0.1:51234 ESTABLISHED 9999",
44
+ " TCP [::]:5173 [::]:0 LISTENING 2222",
45
+ " TCP 0.0.0.0:5173 0.0.0.0:0 LISTENING 2222",
46
+ " UDP 0.0.0.0:5353 *:* 3333",
47
+ " UDP [::]:54321 *:* 0",
48
+ ].join("\r\n");
49
+ assert.deepEqual(parseNetstatListeners(output), [
50
+ { pid: 4, port: 135, protocol: "tcp" },
51
+ { pid: 2222, port: 5173, protocol: "tcp" },
52
+ { pid: 3333, port: 5353, protocol: "udp" },
53
+ ]);
54
+ });
55
+ test("parses grouped lsof field output into listeners", () => {
56
+ const output = [
57
+ "p4242",
58
+ "n127.0.0.1:5432",
59
+ "n[::1]:5432",
60
+ "p77",
61
+ "n*:3000",
62
+ "n/tcp",
63
+ "n/var/run/docker.sock",
64
+ ].join("\n");
65
+ assert.deepEqual(parseUnixLsofListeners(output, "tcp"), [
66
+ { pid: 4242, port: 5432, protocol: "tcp" },
67
+ { pid: 77, port: 3000, protocol: "tcp" },
68
+ ]);
69
+ });
70
+ test("recognises data services that must never auto-kill", () => {
71
+ assert.equal(isProtectedService("postgres"), true);
72
+ assert.equal(isProtectedService("Redis-Server"), true);
73
+ assert.equal(isProtectedService(" mysqld "), true);
74
+ assert.equal(isProtectedService("node"), false);
75
+ assert.equal(isProtectedService("redis-cli"), false);
76
+ assert.equal(isProtectedService("mongo"), false);
77
+ });
39
78
  test("refuses Docker-named processes and operating-system PIDs", () => {
40
79
  assert.match(refusalReason(9, "docker-proxy") ?? "", /Docker/);
41
80
  assert.match(refusalReason(9, "vpnkit") ?? "", /Docker/);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,30 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import process from "node:process";
4
+ import { colourEnabled, paint, setColourMode } from "../src/style.js";
5
+ test("paint wraps text only when colour is enabled", () => {
6
+ setColourMode("always");
7
+ assert.equal(paint("green", "ok"), "\u001b[32mok\u001b[0m");
8
+ assert.equal(paint("dim", "PID 7"), "\u001b[2mPID 7\u001b[0m");
9
+ setColourMode("never");
10
+ assert.equal(paint("green", "ok"), "ok");
11
+ });
12
+ test("auto mode defers to NO_COLOR and never mode always strips", () => {
13
+ const original = process.env.NO_COLOR;
14
+ try {
15
+ process.env.NO_COLOR = "1";
16
+ setColourMode("auto");
17
+ assert.equal(colourEnabled(), false);
18
+ setColourMode("never");
19
+ assert.equal(colourEnabled(), false);
20
+ setColourMode("always");
21
+ assert.equal(colourEnabled(), true);
22
+ }
23
+ finally {
24
+ if (original === undefined)
25
+ delete process.env.NO_COLOR;
26
+ else
27
+ process.env.NO_COLOR = original;
28
+ setColourMode("auto");
29
+ }
30
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "port-reclaim",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Free up a port already in use: find and kill the process holding it (EADDRINUSE). Cross-platform, zero-config, Docker-safe.",
5
5
  "author": "princegoel0",
6
6
  "license": "MIT",
@@ -31,7 +31,7 @@
31
31
  },
32
32
  "scripts": {
33
33
  "build": "tsc",
34
- "test": "npm run build && node --test dist/tests/process.test.js dist/tests/args.test.js dist/tests/config.test.js dist/tests/cli.test.js",
34
+ "test": "npm run build && node --test dist/tests/process.test.js dist/tests/args.test.js dist/tests/config.test.js dist/tests/style.test.js dist/tests/cli.test.js",
35
35
  "prepublishOnly": "npm test"
36
36
  },
37
37
  "keywords": [