@kaynooo/cli-proc 0.7.0 → 0.7.2

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/dist/proc-cli.js CHANGED
@@ -2,13 +2,13 @@
2
2
  // @bun
3
3
 
4
4
  // src/proc-cli.ts
5
- import process16 from "process";
5
+ import process20 from "process";
6
6
  // ../kit/src/args.ts
7
- import process6 from "process";
7
+ import process9 from "process";
8
8
  import { parseArgs } from "util";
9
9
 
10
10
  // ../kit/src/format.ts
11
- import process4 from "process";
11
+ import process7 from "process";
12
12
 
13
13
  // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-n6z2kk96.js
14
14
  var r = new Map;
@@ -23,6 +23,7 @@ function y(e, t) {
23
23
  n = new Intl.NumberFormat(e, t), i.set(o, n);
24
24
  return n;
25
25
  }
26
+
26
27
  // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
27
28
  var N = new Map;
28
29
  var Nt = /\s+\S*$/;
@@ -40,6 +41,7 @@ function ko(t, e, r = "...") {
40
41
  }
41
42
  var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
42
43
  var z = new Map;
44
+
43
45
  // ../kit/src/mode.ts
44
46
  import process2 from "process";
45
47
  var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
@@ -62,7 +64,7 @@ function isInteractive(streams = process2) {
62
64
  }
63
65
 
64
66
  // ../kit/src/style.ts
65
- import process3 from "process";
67
+ import process6 from "process";
66
68
 
67
69
  // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
68
70
  var G2 = /^[a-f0-9]+$/i;
@@ -88,7 +90,7 @@ function C(r, e = globalThis.process?.env ?? {}) {
88
90
  return false;
89
91
  return r?.isTTY === true;
90
92
  }
91
- function f2(r, e = []) {
93
+ function f(r, e = []) {
92
94
  let l = "", n = "";
93
95
  for (let t = 0, i = e.length;t < i; t++)
94
96
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
@@ -98,7 +100,7 @@ function f2(r, e = []) {
98
100
  if (Array.isArray(a)) {
99
101
  let s = g.get(i);
100
102
  if (s === undefined)
101
- s = f2(r, [...e, a]), g.set(i, s);
103
+ s = f(r, [...e, a]), g.set(i, s);
102
104
  return s;
103
105
  }
104
106
  if (typeof a === "function")
@@ -107,30 +109,251 @@ function f2(r, e = []) {
107
109
  if (u === undefined) {
108
110
  if (g.size >= 64)
109
111
  g.clear();
110
- u = f2(r, [...e, a(...s)]), g.set(y, u);
112
+ u = f(r, [...e, a(...s)]), g.set(y, u);
111
113
  }
112
114
  return u;
113
115
  };
114
116
  throw Error(`Unknown style: ${String(i)}`);
115
117
  } });
116
118
  }
117
- function Fe2(r = {}) {
118
- return f2(r);
119
+ function Fe(r = {}) {
120
+ return f(r);
121
+ }
122
+ var o = Fe();
123
+
124
+ // ../kit/src/theme.ts
125
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
126
+ import { homedir as homedir2 } from "os";
127
+ import { join as join3, resolve as resolve2 } from "path";
128
+ import process5 from "process";
129
+
130
+ // ../kit/src/config.ts
131
+ import { existsSync } from "fs";
132
+ import { dirname, join, resolve } from "path";
133
+ import process3 from "process";
134
+ function findUp(names, from = process3.cwd(), stop = () => false) {
135
+ const wanted = typeof names === "string" ? [names] : names;
136
+ for (let dir = resolve(from);; dir = dirname(dir)) {
137
+ const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
138
+ if (found !== undefined)
139
+ return found;
140
+ if (stop(dir) || dirname(dir) === dir)
141
+ return;
142
+ }
143
+ }
144
+
145
+ // ../kit/src/user-config.ts
146
+ import { homedir } from "os";
147
+ import { join as join2 } from "path";
148
+ import process4 from "process";
149
+ function configBase(where = {}) {
150
+ const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
151
+ return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
152
+ }
153
+ function userConfigPath(bin, where = {}) {
154
+ return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
119
155
  }
120
- var o2 = Fe2();
121
156
 
122
157
  // ../kit/src/theme.ts
123
158
  var ENDS = new Map;
159
+ var DEFAULT = {
160
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
161
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
162
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
163
+ bins: {},
164
+ gradient: ["#c084fc", "#67e8f9"]
165
+ };
166
+ var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
167
+ var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
168
+ var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
169
+ var PRESETS = {
170
+ default: {},
171
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
172
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
173
+ ascii: { glyphs: ASCII }
174
+ };
124
175
  var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
176
+ var HEX = /^#[0-9a-f]{6}$/i;
177
+ var CONTROL = /\p{Cc}/u;
125
178
  var MAX_FILE_BYTES = 64 * 1024;
179
+ var SPACES = /\s+/;
180
+ function isColorSpec(spec) {
181
+ if (typeof spec === "number")
182
+ return Number.isInteger(spec) && spec >= 0 && spec <= 255;
183
+ return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
184
+ }
185
+ var CUBE = [0, 95, 135, 175, 215, 255];
186
+ function cubeLevel(channel) {
187
+ return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
188
+ }
189
+ function nearest256(hex) {
190
+ const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
191
+ const levels = rgb.map(cubeLevel);
192
+ const cube = levels.map((level) => CUBE[level]);
193
+ const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
194
+ const greyValue = 8 + grey * 10;
195
+ const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
196
+ return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
197
+ }
198
+ function hasTrueColor(env) {
199
+ return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
200
+ }
201
+ function tinted(colors, spec, env = process5.env) {
202
+ if (typeof spec === "number")
203
+ return colors.ansi256(spec);
204
+ return spec.trim().split(SPACES).reduce((chain, token) => {
205
+ if (HEX.test(token))
206
+ return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
207
+ return chain[token] ?? chain;
208
+ }, colors);
209
+ }
210
+ function isRecord(value) {
211
+ return typeof value === "object" && value !== null && !Array.isArray(value);
212
+ }
213
+ function readThemeFile(path, warn) {
214
+ try {
215
+ const stat = statSync(path, { throwIfNoEntry: false });
216
+ if (stat === undefined)
217
+ return;
218
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
219
+ warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
220
+ return;
221
+ }
222
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
223
+ if (isRecord(parsed))
224
+ return parsed;
225
+ warn(`${path} is not a JSON object, theme ignored`);
226
+ } catch (error) {
227
+ warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
228
+ }
229
+ return;
230
+ }
231
+ function applyPreset(theme, name, warn, where) {
232
+ if (name === undefined)
233
+ return;
234
+ if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
235
+ warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
236
+ return;
237
+ }
238
+ const preset = PRESETS[name];
239
+ Object.assign(theme.colors, preset.colors);
240
+ Object.assign(theme.glyphs, preset.glyphs);
241
+ if (preset.accents !== undefined)
242
+ theme.accents = [...preset.accents];
243
+ if (Object.hasOwn(preset, "gradient"))
244
+ theme.gradient = preset.gradient;
245
+ return name;
246
+ }
247
+ function applyFile(theme, file, where, warn) {
248
+ if (isRecord(file.colors)) {
249
+ for (const [key, value] of Object.entries(file.colors)) {
250
+ if (!Object.hasOwn(DEFAULT.colors, key))
251
+ warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
252
+ else if (!isColorSpec(value))
253
+ warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
254
+ else
255
+ theme.colors[key] = value;
256
+ }
257
+ }
258
+ if (isRecord(file.glyphs)) {
259
+ for (const [key, value] of Object.entries(file.glyphs)) {
260
+ if (!Object.hasOwn(DEFAULT.glyphs, key))
261
+ warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
262
+ else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
263
+ warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
264
+ else
265
+ theme.glyphs[key] = value;
266
+ }
267
+ }
268
+ if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
269
+ theme.accents = [...file.accents];
270
+ else if (file.accents !== undefined)
271
+ warn(`${where}: accents must be a non-empty list of colours`);
272
+ if (file.gradient === null)
273
+ theme.gradient = undefined;
274
+ else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
275
+ theme.gradient = [file.gradient[0], file.gradient[1]];
276
+ else if (file.gradient !== undefined)
277
+ warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
278
+ if (isRecord(file.bins)) {
279
+ for (const [bin, value] of Object.entries(file.bins)) {
280
+ if (isColorSpec(value))
281
+ theme.bins[bin] = value;
282
+ else
283
+ warn(`${where}: bin ${bin} has no valid colour`);
284
+ }
285
+ }
286
+ }
287
+ function endsWalk(home) {
288
+ return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
289
+ }
126
290
  var warned = new Set;
291
+ function warnOnce(message) {
292
+ if (warned.has(message))
293
+ return;
294
+ warned.add(message);
295
+ console.error(`warning: theme ${message}`);
296
+ }
297
+ function isPath(chosen) {
298
+ return chosen.includes("/") || chosen.endsWith(".json");
299
+ }
300
+ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
301
+ const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
302
+ const sources = [];
303
+ const chosen = env.KIT_THEME ?? "";
304
+ const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
305
+ if (isPath(chosen))
306
+ wanted.push(resolve2(from, chosen));
307
+ const files = [];
308
+ for (const path of wanted) {
309
+ const file = path === undefined ? undefined : readThemeFile(path, warn);
310
+ if (path !== undefined && file !== undefined)
311
+ files.push({ path, file });
312
+ }
313
+ let preset = "default";
314
+ if (chosen !== "" && !isPath(chosen)) {
315
+ preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
316
+ } else {
317
+ const named = files.findLast(({ file }) => file.preset !== undefined);
318
+ if (named !== undefined)
319
+ preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
320
+ }
321
+ for (const { path, file } of files) {
322
+ applyFile(theme, file, path, warn);
323
+ sources.push(path);
324
+ }
325
+ return { theme, sources, preset };
326
+ }
327
+ var current;
328
+ var currentKey = "";
329
+ function activeTheme() {
330
+ const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
331
+ if (current === undefined || key !== currentKey) {
332
+ current = loadTheme();
333
+ currentKey = key;
334
+ }
335
+ return current;
336
+ }
127
337
 
128
338
  // ../kit/src/style.ts
129
- function takesControlCodes(stream, env = process3.env) {
339
+ var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
340
+ function takesControlCodes(stream, env = process6.env) {
130
341
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
131
342
  }
132
- function paint(stream, env = process3.env) {
133
- return Fe2({ stream: { isTTY: takesControlCodes(stream, env) }, env });
343
+ function paint(stream, env = process6.env) {
344
+ return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
345
+ }
346
+ function marked(mark, text, stream, detail, env = process6.env) {
347
+ const colors = paint(stream, env);
348
+ let head = MARK_WORDS[mark];
349
+ if (takesControlCodes(stream, env)) {
350
+ const { theme } = activeTheme();
351
+ head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
352
+ }
353
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
354
+ }
355
+ function problem(text, detail) {
356
+ console.error(marked("problem", text, process6.stderr, detail));
134
357
  }
135
358
  var STATUS_WORDS = {
136
359
  passed: ["passed", "success", "succeeded", "ok"],
@@ -141,7 +364,7 @@ var STATUS_WORDS = {
141
364
  };
142
365
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
143
366
  // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-knqbxp56.js
144
- function tt2(i, { units: r = "iec", dp: t = 1, locale: n } = {}) {
367
+ function tt(i, { units: r = "iec", dp: t = 1, locale: n } = {}) {
145
368
  let e = r === "si" ? 1000 : 1024;
146
369
  if (Math.abs(i) < e)
147
370
  return `${i} B`;
@@ -179,7 +402,7 @@ var ESCAPE = String.fromCharCode(27);
179
402
  function textWidth(text) {
180
403
  return Bun.stringWidth(text);
181
404
  }
182
- function table(rows, { cellWidth, header = false, align = [], fit, stream = process4.stdout, env = process4.env } = {}) {
405
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
183
406
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
184
407
  if (outputMode(stream, env) === "agent")
185
408
  return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
@@ -218,7 +441,7 @@ function narrow(rows, widths, limit) {
218
441
  }
219
442
  return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
220
443
  }
221
- function jsonText(value, replacer, { stream = process4.stdout, env = process4.env } = {}) {
444
+ function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
222
445
  return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
223
446
  }
224
447
  function printJson(value) {
@@ -226,27 +449,23 @@ function printJson(value) {
226
449
  }
227
450
 
228
451
  // ../kit/src/help.ts
229
- import process5 from "process";
452
+ import process8 from "process";
230
453
  var OPTIONAL = /\[[^\]]+\]/g;
231
454
  var USAGE_PREFIX = /^usage:\s*/i;
232
455
  var FULL_STOP = /\.$/;
233
- function usageLine(usage, colors = paint(process5.stdout)) {
456
+ function usageLine(usage, colors = paint(process8.stdout)) {
234
457
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
235
458
  }
236
- function helpText(usage, options, colors = paint(process5.stdout), { examples = [], replaces, exits = [] } = {}) {
237
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
459
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
460
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
238
461
  `);
239
462
  }
240
- function exitRows(exits, colors = paint(process5.stdout)) {
463
+ function exitRows(exits, colors = paint(process8.stdout)) {
241
464
  if (exits.length === 0)
242
465
  return [];
243
- const width = Math.max(...exits.map(([code]) => String(code).length));
244
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
245
- }
246
- function replacesRows(replaces, colors = paint(process5.stdout)) {
247
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
466
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
248
467
  }
249
- function wantsHelpJson(env = process5.env) {
468
+ function wantsHelpJson(env = process8.env) {
250
469
  return env.KIT_HELP === "json";
251
470
  }
252
471
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -265,12 +484,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
265
484
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
266
485
  };
267
486
  }
268
- function exampleRows(examples, colors = paint(process5.stdout)) {
487
+ function exampleRows(examples, colors = paint(process8.stdout)) {
269
488
  if (examples.length === 0 || outputMode() === "agent")
270
489
  return [];
271
490
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
272
491
  }
273
- function optionRows(options, colors = paint(process5.stdout)) {
492
+ function optionRows(options, colors = paint(process8.stdout)) {
274
493
  const rows = Object.entries(options).map(([name, option]) => {
275
494
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
276
495
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -371,7 +590,7 @@ var OUTPUT_OPTIONS = {
371
590
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
372
591
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
373
592
  };
374
- function applyOutput(color, plain, env = process6.env) {
593
+ function applyOutput(color, plain, env = process9.env) {
375
594
  const when = plain === true ? "never" : color ?? "auto";
376
595
  if (when === "auto")
377
596
  return;
@@ -540,9 +759,33 @@ function nearestOption(message, options, allowNegative) {
540
759
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
541
760
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
542
761
  }
762
+ // ../kit/src/argv.ts
763
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
764
+ import { resolve as resolve3 } from "path";
765
+ import process10 from "process";
766
+ function commandLine() {
767
+ try {
768
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
769
+ } catch {
770
+ return;
771
+ }
772
+ }
773
+ function realPath(word) {
774
+ try {
775
+ return realpathSync(resolve3(word));
776
+ } catch {
777
+ return;
778
+ }
779
+ }
780
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
781
+ const target = script === undefined ? undefined : realPath(script) ?? script;
782
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
783
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
784
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
785
+ }
543
786
  // ../kit/src/process.ts
544
787
  import { constants } from "os";
545
- import process7 from "process";
788
+ import process11 from "process";
546
789
  var KILL_GRACE_MS = 2000;
547
790
  function exitCodeOf(code, signal) {
548
791
  if (code !== null)
@@ -562,7 +805,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
562
805
  return;
563
806
  try {
564
807
  if (grouped)
565
- process7.kill(-proc.pid, killing);
808
+ process11.kill(-proc.pid, killing);
566
809
  else
567
810
  proc.kill(killing);
568
811
  } catch {}
@@ -636,15 +879,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
636
879
  var RESET_STYLE = `${ESC}[0m`;
637
880
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
638
881
  // ../kit/src/cli.ts
639
- import { readFileSync, realpathSync } from "fs";
640
- import { dirname as dirname2, join as join2 } from "path";
641
- import process9 from "process";
882
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
883
+ import { dirname as dirname3, join as join5 } from "path";
884
+ import process13 from "process";
642
885
 
643
886
  // ../kit/src/usage.ts
644
887
  import { appendFileSync, mkdirSync } from "fs";
645
- import { homedir } from "os";
646
- import { dirname, isAbsolute, join } from "path";
647
- import process8 from "process";
888
+ import { homedir as homedir3 } from "os";
889
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
890
+ import process12 from "process";
648
891
 
649
892
  // ../kit/src/logs.ts
650
893
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -658,14 +901,14 @@ var usageError;
658
901
  function noteUsageError(message) {
659
902
  usageError = message;
660
903
  }
661
- function stateHome(env = process8.env) {
904
+ function stateHome(env = process12.env) {
662
905
  const dir = env.XDG_STATE_HOME;
663
- return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
906
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
664
907
  }
665
- function usagePath(env = process8.env) {
666
- return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
908
+ function usagePath(env = process12.env) {
909
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
667
910
  }
668
- function usageRecorded(env = process8.env) {
911
+ function usageRecorded(env = process12.env) {
669
912
  const off = env.KAYNOOO_CLI_NO_USAGE;
670
913
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
671
914
  }
@@ -679,12 +922,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
679
922
  usageError = undefined;
680
923
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
681
924
  }
682
- function recordUsage(entry, env = process8.env) {
925
+ function recordUsage(entry, env = process12.env) {
683
926
  if (!usageRecorded(env))
684
927
  return;
685
928
  try {
686
929
  const path = usagePath(env);
687
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
930
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
688
931
  appendFileSync(path, `${JSON.stringify(entry)}
689
932
  `, { mode: 384 });
690
933
  } catch {}
@@ -756,7 +999,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
756
999
  header(colors, summary),
757
1000
  "",
758
1001
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
759
- ...replacesRows(replaces, colors),
760
1002
  "",
761
1003
  ...await commandRows(commands, colors),
762
1004
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -770,8 +1012,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
770
1012
  `);
771
1013
  }
772
1014
  function printError(prefix, message, hint, cause) {
773
- const colors = paint(process9.stderr);
774
- const styled = takesControlCodes(process9.stderr);
1015
+ const colors = paint(process13.stderr);
1016
+ const styled = takesControlCodes(process13.stderr);
775
1017
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
776
1018
  const under = (label, text, tint) => text === undefined ? "" : `
777
1019
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -814,11 +1056,11 @@ async function dispatch(level, typed, { version, redact }) {
814
1056
  }
815
1057
  }
816
1058
  if (name === undefined && level.path.length > 1) {
817
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
1059
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
818
1060
  return 2;
819
1061
  }
820
1062
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
821
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
1063
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
822
1064
  return 0;
823
1065
  }
824
1066
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -874,24 +1116,24 @@ function candidateLine(candidate) {
874
1116
  }
875
1117
  function positionalBeingTyped(before, { options, positionals }) {
876
1118
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
877
- let index = 0;
1119
+ const typed = [];
878
1120
  let at = 0;
879
1121
  while (at < before.length) {
880
1122
  const word = before[at];
881
1123
  if (word === "--") {
882
- index += before.length - at - 1;
1124
+ typed.push(...before.slice(at + 1));
883
1125
  break;
884
1126
  }
885
1127
  if (!word.startsWith("-"))
886
- index++;
1128
+ typed.push(word);
887
1129
  else if (takesValue(word))
888
1130
  at++;
889
1131
  at++;
890
1132
  }
891
1133
  const last = positionals.at(-1);
892
- if (index < positionals.length)
893
- return positionals[index];
894
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1134
+ if (typed.length < positionals.length)
1135
+ return { name: positionals[typed.length], typed };
1136
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
895
1137
  }
896
1138
  async function leafCandidates(run, words) {
897
1139
  const completing = await completingOf(run);
@@ -899,12 +1141,12 @@ async function leafCandidates(run, words) {
899
1141
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
900
1142
  const flag = words.at(-2);
901
1143
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1144
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
902
1145
  if (option?.type === "string") {
903
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1146
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
904
1147
  return values === undefined ? [FILES] : values.map(candidateLine);
905
1148
  }
906
- const name = positionalBeingTyped(words.slice(0, -1), completing);
907
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1149
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
908
1150
  return values === undefined ? [FILES] : values.map(candidateLine);
909
1151
  }
910
1152
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -935,17 +1177,21 @@ async function printCandidates(found) {
935
1177
  return 0;
936
1178
  }
937
1179
  function packageVersion(entry = Bun.main) {
938
- for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1180
+ let resolved = entry;
1181
+ try {
1182
+ resolved = realpathSync2(entry);
1183
+ } catch {}
1184
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
939
1185
  try {
940
- const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
1186
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
941
1187
  if (typeof version === "string")
942
1188
  return version;
943
1189
  } catch {}
944
- if (dirname2(dir) === dir)
1190
+ if (dirname3(dir) === dir)
945
1191
  return "0.0.0";
946
1192
  }
947
1193
  }
948
- async function runCli(cli, argv = process9.argv.slice(2)) {
1194
+ async function runCli(cli, argv = scriptArgs()) {
949
1195
  const version = cli.version ?? packageVersion();
950
1196
  if (argv[0] === COMPLETE)
951
1197
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -972,7 +1218,7 @@ function commandPath(scope, argv) {
972
1218
  }
973
1219
  return path.length === 0 ? undefined : path.join(" ");
974
1220
  }
975
- async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
1221
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
976
1222
  if (argv[0] === COMPLETE)
977
1223
  return printCandidates(leafCandidates(run, argv.slice(1)));
978
1224
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1016,7 +1262,7 @@ function parseSize(text, bareUnit = 1) {
1016
1262
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1017
1263
  }
1018
1264
  // ../kit/src/watch.ts
1019
- import process10 from "process";
1265
+ import process14 from "process";
1020
1266
  import { format } from "util";
1021
1267
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1022
1268
  var DEFAULT_SECONDS = 2;
@@ -1038,7 +1284,7 @@ function withoutWatch(args) {
1038
1284
  }
1039
1285
  return rest;
1040
1286
  }
1041
- async function watching(value, step, stream = process10.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1287
+ async function watching(value, step, stream = process14.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1042
1288
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1043
1289
  if (!takesControlCodes(stream))
1044
1290
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1046,12 +1292,12 @@ async function watching(value, step, stream = process10.stdout, sleep = Bun.slee
1046
1292
  for (let round = 0;round < rounds; round++) {
1047
1293
  const held = [];
1048
1294
  const { log, info } = console;
1049
- const write = process10.stdout.write.bind(process10.stdout);
1295
+ const write = process14.stdout.write.bind(process14.stdout);
1050
1296
  const hold = (...parts) => void held.push(`${format(...parts)}
1051
1297
  `);
1052
1298
  console.log = hold;
1053
1299
  console.info = hold;
1054
- process10.stdout.write = (text) => {
1300
+ process14.stdout.write = (text) => {
1055
1301
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1056
1302
  return true;
1057
1303
  };
@@ -1060,7 +1306,7 @@ async function watching(value, step, stream = process10.stdout, sleep = Bun.slee
1060
1306
  } finally {
1061
1307
  console.log = log;
1062
1308
  console.info = info;
1063
- process10.stdout.write = write;
1309
+ process14.stdout.write = write;
1064
1310
  }
1065
1311
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1066
1312
  await sleep(interval);
@@ -1068,7 +1314,7 @@ async function watching(value, step, stream = process10.stdout, sleep = Bun.slee
1068
1314
  return code;
1069
1315
  }
1070
1316
  // src/pid.ts
1071
- import process12 from "process";
1317
+ import process16 from "process";
1072
1318
 
1073
1319
  // src/mask.ts
1074
1320
  import { basename } from "path";
@@ -1385,9 +1631,8 @@ async function userName(uid) {
1385
1631
  var usage2 = `pid <pid>
1386
1632
 
1387
1633
  Shows what a process is: its executable, working directory, command line, parent chain up to init, user, start time and age, memory, open files and limits, the TCP and UDP ports it listens on and its cgroup. Everything is read from /proc; what the calling user cannot read of another user's process is left out and named at the end.
1388
- The environment is not shown unless --env is given, with every value that looks like a secret masked.
1389
-
1390
- Exits 0 when it showed the process, 1 when no process has this pid, 2 on a usage error.`;
1634
+ The environment is not shown unless --env is given, with every value that looks like a secret masked.`;
1635
+ var EXITS = [[0, "it showed the process"], [1, "no process has this pid"], [2, "a usage error"]];
1391
1636
  var DIGITS2 = /^\d+$/;
1392
1637
  var options = {
1393
1638
  env: { type: "boolean", description: "show the environment, secrets masked" },
@@ -1459,9 +1704,9 @@ function limitLine(limits, name) {
1459
1704
  return limit === undefined ? "-" : `soft ${limit.soft}, hard ${limit.hard}`;
1460
1705
  }
1461
1706
  function render(info, showEnv) {
1462
- const colors = paint(process12.stdout);
1707
+ const colors = paint(process16.stdout);
1463
1708
  const memory = info.memory;
1464
- const size = (bytes) => bytes === undefined ? "-" : tt2(bytes);
1709
+ const size = (bytes) => bytes === undefined ? "-" : tt(bytes);
1465
1710
  const rows = [
1466
1711
  ["Executable", info.exe ?? "-"],
1467
1712
  ["Directory", info.cwd ?? "-"],
@@ -1489,6 +1734,7 @@ function render(info, showEnv) {
1489
1734
  }
1490
1735
  async function pid(args) {
1491
1736
  const { values, positionals } = parse(args, usage2, options, {
1737
+ exits: EXITS,
1492
1738
  positionals: ["<pid>"],
1493
1739
  replaces: "cat /proc/<pid>/{cmdline,environ,limits}, readlink /proc/<pid>/{exe,cwd}, the fish pid function",
1494
1740
  examples: [
@@ -1512,10 +1758,10 @@ async function pid(args) {
1512
1758
 
1513
1759
  // src/ports.ts
1514
1760
  import { basename as basename2 } from "path";
1515
- import process14 from "process";
1761
+ import process18 from "process";
1516
1762
 
1517
1763
  // ../kit/src/prompt.ts
1518
- import process13 from "process";
1764
+ import process17 from "process";
1519
1765
 
1520
1766
  // ../kit/src/picker/score.ts
1521
1767
  var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
@@ -1525,7 +1771,9 @@ var NONE = Number.NEGATIVE_INFINITY;
1525
1771
  var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1526
1772
  var PASTE_START = "\x1B[200~";
1527
1773
  var PASTE_END = "\x1B[201~";
1528
- var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1774
+ var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1775
+ var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1776
+ var WHEEL_LINES = 3;
1529
1777
  var KEYS = {
1530
1778
  "\x1B[A": "up",
1531
1779
  "\x1BOA": "up",
@@ -1554,9 +1802,15 @@ var KEYS = {
1554
1802
  "\x1BOP": "help",
1555
1803
  "\x1B[11~": "help"
1556
1804
  };
1805
+ function repeat(value, count) {
1806
+ return Array.from({ length: count }).fill(value);
1807
+ }
1557
1808
  function parseKeys(input, paste = { active: false }, ctrls = []) {
1558
1809
  const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1559
1810
  return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1811
+ const wheel = MOUSE.exec(sequence)?.[1];
1812
+ if (wheel !== undefined)
1813
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1560
1814
  const named = codes.get(sequence);
1561
1815
  const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1562
1816
  if (sequence === PASTE_START || sequence === PASTE_END) {
@@ -1599,21 +1853,18 @@ function asking(colors, question, typed, keys) {
1599
1853
  function answer(colors, question, state, picked) {
1600
1854
  return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1601
1855
  }
1602
- async function ask(question, { hint, terminal = process13 }, render, press) {
1856
+ async function ask(question, { hint, terminal = process17 }, render, press) {
1603
1857
  const { stdin, stderr } = terminal;
1604
1858
  if (!isInteractive(terminal))
1605
1859
  fail(`cannot ask "${question}" off a terminal`, 2, hint);
1606
1860
  const colors = paint(stderr);
1607
- let drawn = [];
1608
1861
  let current = "asking";
1609
1862
  let outcome;
1610
1863
  const columns = () => stderr.columns || 80;
1611
- const draw = (state) => {
1864
+ const draw = (state, last = false) => {
1612
1865
  const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1613
- const rows = drawn.reduce((sum, line) => sum + Math.max(1, Math.ceil(Bun.stringWidth(line) / columns())), 0);
1614
- stderr.write(`${rows > 1 ? `\x1B[${rows - 1}A` : ""}\r\x1B[0J${frame.join(`
1615
- `)}`);
1616
- drawn = frame;
1866
+ stderr.write(`\r\x1B[0J${frame.join(`
1867
+ `)}${last || frame.length < 2 ? "" : `\x1B[${frame.length - 1}A`}${last ? "" : "\r"}`);
1617
1868
  current = state;
1618
1869
  };
1619
1870
  const redraw = () => draw(current);
@@ -1649,7 +1900,7 @@ async function ask(question, { hint, terminal = process13 }, render, press) {
1649
1900
  });
1650
1901
  } finally {
1651
1902
  stderr.off?.("resize", redraw);
1652
- draw(outcome ?? "cancel");
1903
+ draw(outcome ?? "cancel", true);
1653
1904
  stderr.write(`
1654
1905
  \x1B[?25h\x1B[?2004l`);
1655
1906
  stdin.setRawMode(false);
@@ -1737,15 +1988,15 @@ var usage3 = `ports [port]
1737
1988
 
1738
1989
  Lists what listens on this machine, TCP and UDP over IPv4 and IPv6, one row per port with its bound address, the owning process, its command and its working directory. A port Docker publishes is held by docker-proxy, and shows as its compose project and service when docker is installed; the owner of a socket of another user cannot be read and shows as -.
1739
1990
  \`ports <port>\` keeps that port alone and exits 1 when nothing listens on it.
1740
- \`ports <port> --kill\` stops its owner with SIGTERM, and with --force SIGKILL once --grace has passed, after asking on a terminal unless --yes is given. It refuses processes of other users, pid 1, this command and its ancestors, and docker-proxy, for which it names the container to stop instead.
1741
-
1742
- Exits 0 when it listed or stopped, 1 when nothing listens on the given port or the owner could not be stopped, 2 on a usage error.`;
1991
+ \`ports <port> --kill\` stops its owner with SIGTERM, and with --force SIGKILL once --grace has passed, after asking on a terminal unless --yes is given. It refuses processes of other users, pid 1, this command and its ancestors, and docker-proxy, for which it names the container to stop instead.`;
1992
+ var EXITS2 = [[0, "it listed or stopped"], [1, "nothing listens on the given port or the owner could not be stopped"], [2, "a usage error"]];
1743
1993
  var options2 = {
1744
1994
  json: jsonOption("[{ port, protocol, addresses, pid, command, cwd, container }]"),
1745
1995
  kill: { type: "boolean", conflicts: ["watch"], description: "stop the owner of the given port" },
1746
1996
  watch: watchOption("the ports"),
1747
1997
  force: { type: "boolean", description: "with --kill, SIGKILL what SIGTERM did not stop within --grace" },
1748
1998
  yes: { type: "boolean", short: "y", description: "with --kill, do not ask first" },
1999
+ quiet: { type: "boolean", short: "q", description: "with --kill, print nothing about what was stopped" },
1749
2000
  grace: { type: "string", description: "with --force, how long SIGTERM gets before SIGKILL (5s)" }
1750
2001
  };
1751
2002
  function buildRows(sockets, owners, procs, containers) {
@@ -1787,7 +2038,7 @@ function refusal(row, proc, guard) {
1787
2038
  return reason === undefined ? undefined : `pid ${row.pid} is ${reason}`;
1788
2039
  }
1789
2040
  function render2(rows) {
1790
- const colors = paint(process14.stdout);
2041
+ const colors = paint(process18.stdout);
1791
2042
  const cells = rows.map((row) => [
1792
2043
  colors.cyan(String(row.port)),
1793
2044
  row.protocol,
@@ -1799,12 +2050,12 @@ function render2(rows) {
1799
2050
  return table([["PORT", "PROTO", "ADDRESS", "PID", "COMMAND", "CWD"], ...cells], { header: true });
1800
2051
  }
1801
2052
  async function stop(port, rows, procs, values) {
1802
- const guard = { uid: process14.getuid?.() ?? -1, mine: new Set(ancestry(process14.pid, procs)) };
2053
+ const guard = { uid: process18.getuid?.() ?? -1, mine: new Set(ancestry(process18.pid, procs)) };
1803
2054
  const targets = new Map;
1804
2055
  for (const row of rows) {
1805
2056
  const reason = refusal(row, row.pid === undefined ? undefined : procs.get(row.pid), guard);
1806
2057
  if (reason !== undefined)
1807
- console.error(`port ${port}: ${reason}`);
2058
+ problem(`port ${port}: ${reason}`);
1808
2059
  else if (row.pid !== undefined)
1809
2060
  targets.set(row.pid, row);
1810
2061
  }
@@ -1812,20 +2063,21 @@ async function stop(port, rows, procs, values) {
1812
2063
  return 1;
1813
2064
  const names = [...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? "", 40)})`).join(", ");
1814
2065
  if (values.yes !== true) {
1815
- if (!process14.stdin.isTTY)
2066
+ if (!process18.stdin.isTTY)
1816
2067
  fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2);
1817
2068
  if (await confirm(`Stop ${names}?`, { default: false }) !== true)
1818
2069
  return 1;
1819
2070
  }
1820
2071
  const outcome = await terminate([...targets.keys()], { escalate: values.force === true, graceMs: duration(values.grace, "grace", 5000) });
1821
- for (const pid of [...outcome.terminated, ...outcome.killed])
2072
+ for (const pid of values.quiet === true ? [] : [...outcome.terminated, ...outcome.killed])
1822
2073
  console.log(`stopped ${pid}${outcome.killed.includes(pid) ? " (SIGKILL)" : ""}`);
1823
2074
  for (const pid of outcome.survived)
1824
- console.error(`${pid} is still running${values.force === true ? "" : ", pass --force to SIGKILL it"}`);
2075
+ problem(`${pid} is still running${values.force === true ? "" : ", pass --force to SIGKILL it"}`);
1825
2076
  return outcome.survived.length === 0 ? 0 : 1;
1826
2077
  }
1827
2078
  async function ports(args) {
1828
2079
  const { values, positionals } = parse(args, usage3, options2, {
2080
+ exits: EXITS2,
1829
2081
  positionals: ["[port]"],
1830
2082
  replaces: "ss -ltnp | grep, lsof -i, fuser -k and lookups of docker-proxy by hand",
1831
2083
  examples: [
@@ -1843,7 +2095,7 @@ async function ports(args) {
1843
2095
  badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`);
1844
2096
  if (values.kill === true && port === undefined)
1845
2097
  badUsage("--kill takes the port to free: ports <port> --kill");
1846
- const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process14.getuid?.())]);
2098
+ const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process18.getuid?.())]);
1847
2099
  const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
1848
2100
  const wanted = sockets.filter((socket) => port === undefined || socket.port === port);
1849
2101
  const needsDocker = wanted.some((socket) => {
@@ -1852,7 +2104,7 @@ async function ports(args) {
1852
2104
  });
1853
2105
  const rows = buildRows(wanted, owners, byPid, needsDocker ? await dockerContainers() : []);
1854
2106
  if (port !== undefined && rows.length === 0) {
1855
- console.error(`nothing listens on port ${port}`);
2107
+ problem(`nothing listens on port ${port}`);
1856
2108
  return 1;
1857
2109
  }
1858
2110
  if (values.kill === true && port !== undefined)
@@ -1864,17 +2116,17 @@ async function ports(args) {
1864
2116
  console.log(render2(rows));
1865
2117
  const unknown = rows.filter((row) => row.pid === undefined && row.container === undefined).length;
1866
2118
  if (unknown > 0)
1867
- console.error(paint(process14.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
2119
+ console.error(paint(process18.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
1868
2120
  return 0;
1869
2121
  }
1870
2122
 
1871
2123
  // src/procs.ts
1872
- import { existsSync } from "fs";
1873
- import { homedir as homedir2 } from "os";
1874
- import process15 from "process";
2124
+ import { existsSync as existsSync3 } from "fs";
2125
+ import { homedir as homedir4 } from "os";
2126
+ import process19 from "process";
1875
2127
 
1876
2128
  // src/select.ts
1877
- import { basename as basename3, join as join3, relative } from "path";
2129
+ import { basename as basename3, join as join6, relative } from "path";
1878
2130
  var BROWSERS = /^(?:chrom(?:e|ium)(?:-browser)?|google-chrome(?:-stable|-beta|-unstable)?|chrome_crashpad_handler|chrome-headless-shell|headless_shell|chromium-headless-shell|brave|brave-browser|msedge|microsoft-edge|webkitwebprocess|webkitnetworkprocess|webkitgpuprocess|minibrowser|webkitwebdriver|wpewebprocess|wpenetworkprocess|bun-webview.*)$/i;
1879
2131
  var NATIVE = new Set(["rust-analyzer", "gopls", "clangd", "lua-language-server", "pyright-langserver", "pylsp", "intelephense", "phpactor", "tsgo", "esbuild", "biome", "ruff", "phpunit", "pytest", "vitest", "jest"]);
1880
2132
  var RUNTIMES = new Set(["node", "bun", "bunx", "deno", "nodejs"]);
@@ -1911,9 +2163,9 @@ function projectOf(cwd, exists, home) {
1911
2163
  if (cwd === undefined || !cwd.startsWith(`${home}/`))
1912
2164
  return;
1913
2165
  const folders = [];
1914
- for (let dir = cwd;dir.startsWith(`${home}/`); dir = join3(dir, ".."))
2166
+ for (let dir = cwd;dir.startsWith(`${home}/`); dir = join6(dir, ".."))
1915
2167
  folders.push(dir);
1916
- return folders.find((dir) => exists(join3(dir, ".git"))) ?? folders.find((dir) => MARKERS.some((marker) => exists(join3(dir, marker))));
2168
+ return folders.find((dir) => exists(join6(dir, ".git"))) ?? folders.find((dir) => MARKERS.some((marker) => exists(join6(dir, marker))));
1917
2169
  }
1918
2170
  function isOrphan(proc, byPid) {
1919
2171
  if (proc.unit?.endsWith(".service") === true)
@@ -1991,14 +2243,14 @@ var usage4 = `procs
1991
2243
 
1992
2244
  Lists the leftover or heavy processes of the calling user that are worth cleaning, grouped by origin: the project folder their working directory is in, a browser profile for a chromium and its helpers, else their command. Each group shows its process count, total resident memory and oldest age.
1993
2245
  A process is listed when it is a dev tool (bun, node, vite, nuxt, next, chromium and chrome, playwright and webview browsers and their helpers, language servers, test runners) and either an orphan, reparented to init or to the user's systemd, or heavy (500M resident by default). The processes below a listed one, and those sharing a browser profile with it, are listed too, so a chromium whose main process was killed groups with its leftover helpers.
1994
- \`--kill\` is a dry run that names what it would stop unless --yes is given; it sends SIGTERM, then SIGKILL after --grace to what is still there. It never signals pid 1, shells, terminals, this command and its ancestors, or processes of other users.
1995
-
1996
- Exits 0 when it listed or stopped everything, 1 when a process survived SIGKILL, 2 on a usage error.`;
2246
+ \`--kill\` is a dry run that names what it would stop unless --yes is given; it sends SIGTERM, then SIGKILL after --grace to what is still there. It never signals pid 1, shells, terminals, this command and its ancestors, or processes of other users.`;
2247
+ var EXITS3 = [[0, "it listed or stopped everything"], [1, "a process survived SIGKILL"], [2, "a usage error"]];
1997
2248
  var options3 = {
1998
2249
  json: jsonOption("{ groups: [{ origin, kind, count, rss, oldestSeconds, tools, orphans, pids, processes }], skipped }"),
1999
2250
  kill: { type: "boolean", conflicts: ["watch"], description: "stop the listed processes: a dry run without --yes" },
2000
2251
  watch: watchOption("the processes"),
2001
2252
  yes: { type: "boolean", short: "y", description: "with --kill, really stop them, without asking" },
2253
+ quiet: { type: "boolean", short: "q", description: "with --kill --yes, print nothing about what was stopped" },
2002
2254
  "min-mem": { type: "string", description: "heavy from this resident size (500M), and the least a left over process must use to be listed; a bare number counts megabytes" },
2003
2255
  older: { type: "string", description: "only processes at least this old: 30m, 2h, 1d" },
2004
2256
  grace: { type: "string", description: "how long SIGTERM gets before SIGKILL (5s)" }
@@ -2020,11 +2272,11 @@ function summary(group) {
2020
2272
  };
2021
2273
  }
2022
2274
  function render3(groups) {
2023
- const colors = paint(process15.stdout);
2275
+ const colors = paint(process19.stdout);
2024
2276
  const rows = groups.map((group) => [
2025
2277
  group.origin,
2026
2278
  String(group.members.length),
2027
- tt2(group.rss),
2279
+ tt(group.rss),
2028
2280
  formatSeconds(group.oldestMs / 1000),
2029
2281
  colors.dim(truncate(Object.entries(Object.groupBy(group.members, ({ tool }) => tool)).map(([tool, list]) => `${tool}${list.length > 1 ? ` x${list.length}` : ""}`).join(", "), 50)),
2030
2282
  group.orphans === 0 ? "" : colors.yellow(`${group.orphans} orphaned`)
@@ -2033,6 +2285,7 @@ function render3(groups) {
2033
2285
  }
2034
2286
  async function procs(args) {
2035
2287
  const { values } = parse(args, usage4, options3, {
2288
+ exits: EXITS3,
2036
2289
  replaces: "pkill -f and pgrep -f one-liners (which match their own shell), ps aux | grep for leftover chromium, bun or vite processes",
2037
2290
  examples: [
2038
2291
  ["procs", "leftover and heavy dev processes, by origin"],
@@ -2047,10 +2300,10 @@ async function procs(args) {
2047
2300
  if (values.watch !== undefined)
2048
2301
  return watching(values.watch, async () => procs(withoutWatch(args)));
2049
2302
  const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0, "m");
2050
- const uid = process15.getuid?.() ?? -1;
2303
+ const uid = process19.getuid?.() ?? -1;
2051
2304
  const all = await snapshot("/proc", (owner) => owner === uid);
2052
- const mine = new Set(ancestry(process15.pid, new Map(all.map((proc) => [proc.pid, proc]))));
2053
- const { groups, protectedCount } = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir2(), exists: existsSync, minMem, olderMs });
2305
+ const mine = new Set(ancestry(process19.pid, new Map(all.map((proc) => [proc.pid, proc]))));
2306
+ const { groups, protectedCount } = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir4(), exists: existsSync3, minMem, olderMs });
2054
2307
  const pids = groups.flatMap((group) => group.members.map(({ proc }) => proc.pid));
2055
2308
  const show = (extra = {}) => {
2056
2309
  if (values.json === true) {
@@ -2062,22 +2315,23 @@ async function procs(args) {
2062
2315
  if (values.kill !== true || pids.length === 0 || values.yes !== true) {
2063
2316
  show();
2064
2317
  if (values.json !== true && protectedCount > 0)
2065
- console.error(paint(process15.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`));
2318
+ console.error(paint(process19.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`));
2066
2319
  if (values.kill === true && pids.length > 0)
2067
2320
  console.error(`dry run: would stop ${pids.length} ${pids.length === 1 ? "process" : "processes"} (${pids.join(" ")}), pass --yes to do it`);
2068
2321
  return 0;
2069
2322
  }
2070
2323
  const outcome = await terminate(pids, { escalate: true, graceMs: duration(values.grace, "grace", 5000) });
2071
- show({ stopped: [...outcome.terminated, ...outcome.killed], killed: outcome.killed, survived: outcome.survived });
2072
- if (values.json !== true)
2324
+ if (values.quiet !== true || values.json === true)
2325
+ show({ stopped: [...outcome.terminated, ...outcome.killed], killed: outcome.killed, survived: outcome.survived });
2326
+ if (values.json !== true && values.quiet !== true)
2073
2327
  console.log(`stopped ${outcome.terminated.length + outcome.killed.length} of ${pids.length}${outcome.killed.length === 0 ? "" : `, ${outcome.killed.length} needed SIGKILL`}`);
2074
2328
  if (outcome.survived.length > 0)
2075
- console.error(`still running: ${outcome.survived.join(" ")}`);
2329
+ problem(`still running: ${outcome.survived.join(" ")}`);
2076
2330
  return outcome.survived.length === 0 ? 0 : 1;
2077
2331
  }
2078
2332
 
2079
2333
  // src/proc-cli.ts
2080
- process16.exitCode = await runCli({
2334
+ process20.exitCode = await runCli({
2081
2335
  name: "proc",
2082
2336
  about: "what a process is, who listens on a port and which dev processes are worth cleaning, read from /proc",
2083
2337
  replaces: "cat /proc/<pid>/..., ss -ltnp, lsof -i and pgrep -f one-liners",