@kaynooo/cli-proc 0.1.0 → 0.2.1

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/pid-cli.js CHANGED
@@ -1,18 +1,17 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env -S bun --no-env-file
2
2
  // @bun
3
3
 
4
4
  // src/pid-cli.ts
5
- import process10 from "process";
6
-
5
+ import process11 from "process";
7
6
  // ../kit/src/args.ts
8
- import process4 from "process";
7
+ import process5 from "process";
9
8
  import { parseArgs } from "util";
10
9
 
11
10
  // ../kit/src/format.ts
12
- import process2 from "process";
11
+ import process3 from "process";
13
12
 
14
13
  // ../kit/src/style.ts
15
- import process from "process";
14
+ import process2 from "process";
16
15
 
17
16
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
17
  function x(s) {
@@ -276,10 +275,10 @@ function le(i = {}) {
276
275
  var t = le();
277
276
 
278
277
  // ../kit/src/style.ts
279
- function takesControlCodes(stream, env = process.env) {
278
+ function takesControlCodes(stream, env = process2.env) {
280
279
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
281
280
  }
282
- function paint(stream, env = process.env) {
281
+ function paint(stream, env = process2.env) {
283
282
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
284
283
  }
285
284
  var STATUSES = {
@@ -337,7 +336,7 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
337
336
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
338
337
  }
339
338
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
340
- const colors = paint(process2.stdout);
339
+ const colors = paint(process3.stdout);
341
340
  const lines = shown.map((row) => row.map((cell, index) => {
342
341
  const width = widths[index] ?? 0;
343
342
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -369,24 +368,30 @@ function printJson(value) {
369
368
  }
370
369
 
371
370
  // ../kit/src/help.ts
372
- import process3 from "process";
371
+ import process4 from "process";
373
372
  var OPTIONAL = /\[[^\]]+\]/g;
374
373
  var USAGE_PREFIX = /^usage:\s*/i;
375
374
  var FULL_STOP = /\.$/;
376
- function usageLine(usage, colors = paint(process3.stdout)) {
375
+ function usageLine(usage, colors = paint(process4.stdout)) {
377
376
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
378
377
  }
379
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
380
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
378
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
379
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
381
380
  `);
382
381
  }
383
- function replacesRows(replaces, colors = paint(process3.stdout)) {
382
+ function exitRows(exits, colors = paint(process4.stdout)) {
383
+ if (exits.length === 0)
384
+ return [];
385
+ const width = Math.max(...exits.map(([code]) => String(code).length));
386
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
387
+ }
388
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
384
389
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
385
390
  }
386
- function wantsHelpJson(env = process3.env) {
391
+ function wantsHelpJson(env = process4.env) {
387
392
  return env.KIT_HELP === "json";
388
393
  }
389
- function description(usage, { examples = [], replaces } = {}) {
394
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
390
395
  const lines = usage.replace(USAGE_PREFIX, "").split(`
391
396
  `);
392
397
  const first = lines[0];
@@ -397,15 +402,17 @@ function description(usage, { examples = [], replaces } = {}) {
397
402
  synopsis: colon === -1 ? first : first.slice(0, colon),
398
403
  summary: colon === -1 ? fallback : first.slice(colon + 2),
399
404
  ...replaces === undefined ? {} : { replaces },
400
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
405
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
406
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
407
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
401
408
  };
402
409
  }
403
- function exampleRows(examples, colors = paint(process3.stdout)) {
410
+ function exampleRows(examples, colors = paint(process4.stdout)) {
404
411
  if (examples.length === 0)
405
412
  return [];
406
413
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
407
414
  }
408
- function optionRows(options, colors = paint(process3.stdout)) {
415
+ function optionRows(options, colors = paint(process4.stdout)) {
409
416
  const rows = Object.entries(options).map(([name, option]) => {
410
417
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
411
418
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -437,6 +444,15 @@ function closest(name, names) {
437
444
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
438
445
  }
439
446
  // ../kit/src/input.ts
447
+ var WHOLE = /^\d+$/;
448
+ function wholeNumber(value, name, fallback, min = 1) {
449
+ if (value === undefined)
450
+ return fallback;
451
+ const number = Number(value);
452
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
453
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
454
+ return number;
455
+ }
440
456
  var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
441
457
  var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
442
458
  function duration(value, name, fallback, unit = "s") {
@@ -498,7 +514,7 @@ var OUTPUT_OPTIONS = {
498
514
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
499
515
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
500
516
  };
501
- function applyOutput(color, plain, env = process4.env) {
517
+ function applyOutput(color, plain, env = process5.env) {
502
518
  const when = plain === true ? "never" : color ?? "auto";
503
519
  if (when === "auto")
504
520
  return;
@@ -521,7 +537,7 @@ function parse(args, usage, options, settings = {}) {
521
537
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
522
538
  let parsed;
523
539
  try {
524
- parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
540
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
525
541
  } catch (error) {
526
542
  const message = parseError(error);
527
543
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -529,7 +545,7 @@ function parse(args, usage, options, settings = {}) {
529
545
  const values = parsed.values;
530
546
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
531
547
  if (values.help === true) {
532
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
548
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
533
549
  throw new HelpShown;
534
550
  }
535
551
  checkChoices(parsed.values, all);
@@ -571,6 +587,18 @@ function listed(options, allowNegative) {
571
587
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
572
588
  }));
573
589
  }
590
+ function withAliases(args, options) {
591
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
592
+ if (named.size === 0)
593
+ return args;
594
+ const separator = args.indexOf("--");
595
+ const own = separator === -1 ? args : args.slice(0, separator);
596
+ return [...own.map((arg) => {
597
+ const at = arg.indexOf("=");
598
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
599
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
600
+ }), ...separator === -1 ? [] : args.slice(separator)];
601
+ }
574
602
  function withBare(args, options) {
575
603
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
576
604
  if (bare.size === 0)
@@ -657,7 +685,7 @@ function nearestOption(message, options, allowNegative) {
657
685
  }
658
686
  // ../kit/src/process.ts
659
687
  import { constants } from "os";
660
- import process5 from "process";
688
+ import process6 from "process";
661
689
  var KILL_GRACE_MS = 2000;
662
690
  function exitCodeOf(code, signal) {
663
691
  if (code !== null)
@@ -677,7 +705,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
677
705
  return;
678
706
  try {
679
707
  if (grouped)
680
- process5.kill(-proc.pid, killing);
708
+ process6.kill(-proc.pid, killing);
681
709
  else
682
710
  proc.kill(killing);
683
711
  } catch {}
@@ -751,13 +779,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
751
779
  var RESET_STYLE = `${ESC}[0m`;
752
780
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
753
781
  // ../kit/src/cli.ts
754
- import process7 from "process";
782
+ import { readFileSync, realpathSync } from "fs";
783
+ import { dirname as dirname2, join as join2 } from "path";
784
+ import process8 from "process";
755
785
 
756
786
  // ../kit/src/usage.ts
757
787
  import { appendFileSync, mkdirSync } from "fs";
758
788
  import { homedir } from "os";
759
789
  import { dirname, isAbsolute, join } from "path";
760
- import process6 from "process";
790
+ import process7 from "process";
761
791
 
762
792
  // ../kit/src/logs.ts
763
793
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -771,14 +801,14 @@ var usageError;
771
801
  function noteUsageError(message) {
772
802
  usageError = message;
773
803
  }
774
- function stateHome(env = process6.env) {
804
+ function stateHome(env = process7.env) {
775
805
  const dir = env.XDG_STATE_HOME;
776
806
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
777
807
  }
778
- function usagePath(env = process6.env) {
808
+ function usagePath(env = process7.env) {
779
809
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
780
810
  }
781
- function usageRecorded(env = process6.env) {
811
+ function usageRecorded(env = process7.env) {
782
812
  const off = env.KAYNOOO_CLI_NO_USAGE;
783
813
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
784
814
  }
@@ -792,7 +822,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
792
822
  usageError = undefined;
793
823
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
794
824
  }
795
- function recordUsage(entry, env = process6.env) {
825
+ function recordUsage(entry, env = process7.env) {
796
826
  if (!usageRecorded(env))
797
827
  return;
798
828
  try {
@@ -810,8 +840,8 @@ var LEVEL_OPTIONS = {
810
840
  };
811
841
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
812
842
  function printError(prefix, message, hint, cause) {
813
- const colors = paint(process7.stderr);
814
- const styled = takesControlCodes(process7.stderr);
843
+ const colors = paint(process8.stderr);
844
+ const styled = takesControlCodes(process8.stderr);
815
845
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
816
846
  const under = (label, text, tint) => text === undefined ? "" : `
817
847
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -893,11 +923,22 @@ async function printCandidates(found) {
893
923
  console.log(line);
894
924
  return 0;
895
925
  }
896
- async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
926
+ function packageVersion(entry = Bun.main) {
927
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
928
+ try {
929
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
930
+ if (typeof version === "string")
931
+ return version;
932
+ } catch {}
933
+ if (dirname2(dir) === dir)
934
+ return "0.0.0";
935
+ }
936
+ }
937
+ async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
897
938
  if (argv[0] === COMPLETE)
898
939
  return printCandidates(leafCandidates(run, argv.slice(1)));
899
940
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
900
- console.log(version);
941
+ console.log(version ?? packageVersion());
901
942
  return 0;
902
943
  }
903
944
  let code;
@@ -906,8 +947,11 @@ async function runMain({ name, version, run, redact, usage }, argv = process7.ar
906
947
  } catch (error) {
907
948
  code = reportThrown(name, error, redact, wantsJson(argv));
908
949
  }
909
- if (usage !== false)
910
- recordUsage(usageEntry(name, undefined, argv, code));
950
+ if (usage !== false) {
951
+ try {
952
+ recordUsage(usageEntry(name, undefined, argv, code));
953
+ } catch {}
954
+ }
911
955
  return code;
912
956
  }
913
957
  // ../kit/src/secrets.ts
@@ -921,13 +965,21 @@ function isSecretName(name) {
921
965
  var {Glob } = globalThis.Bun;
922
966
  var SESSION_FILES = new Glob("*.json");
923
967
  var ACCOUNT_DIRS = new Glob("*/sessions");
924
- // package.json
925
- var version = "0.1.0";
926
-
968
+ // ../kit/src/size.ts
969
+ var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
970
+ var POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
971
+ function parseSize(text, bareUnit = 1) {
972
+ const match = SIZE.exec(text.trim());
973
+ if (match === null)
974
+ return;
975
+ const suffix = match[2].toLowerCase();
976
+ return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
977
+ }
927
978
  // src/pid.ts
928
- import process9 from "process";
979
+ import process10 from "process";
929
980
 
930
981
  // src/mask.ts
982
+ import { basename } from "path";
931
983
  var MASK = "***";
932
984
  var URL_PASSWORD = /(?<![a-z0-9+.-])([a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:)[^\s'"@]{1,1024}@/gi;
933
985
  var TOKEN = /\b(?:gh[pousr]_|github_pat_|glpat-|sk-|xox[abprs]-|npm_|[sr]k_(?:live|test)_)[\w-]{10,}|\beyJ[\w-]+\.[\w-]+\.[\w-]+|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bBearer\s+[\w.~+/=-]{16,}/g;
@@ -946,13 +998,22 @@ function maskEnviron(entries) {
946
998
  }
947
999
  var FLAG = /^-{1,2}([\w.-]+)(=|$)/;
948
1000
  var ASSIGNMENT_NAME = /^[\w.-]+$/;
1001
+ var PASSWORD_SPLIT = new Set(["sshpass"]);
1002
+ var PASSWORD_JOINED = new Set(["mysql", "mysqldump", "mysqladmin", "mariadb", "mariadb-dump"]);
949
1003
  function maskArgs(args) {
1004
+ const command = basename(args[0] ?? "");
950
1005
  let hidden = false;
951
- return args.map((arg) => {
1006
+ return args.map((arg, index) => {
952
1007
  if (hidden) {
953
1008
  hidden = false;
954
1009
  return arg.startsWith("-") ? maskText(arg) : MASK;
955
1010
  }
1011
+ if (index > 0 && arg === "-p" && PASSWORD_SPLIT.has(command)) {
1012
+ hidden = true;
1013
+ return arg;
1014
+ }
1015
+ if (index > 0 && arg.length > 2 && arg.startsWith("-p") && PASSWORD_JOINED.has(command))
1016
+ return `-p${MASK}`;
956
1017
  const flag = FLAG.exec(arg);
957
1018
  if (flag !== null) {
958
1019
  if (flag[2] === "=")
@@ -1089,12 +1150,6 @@ function cgroupContainer(entries) {
1089
1150
  }
1090
1151
  return;
1091
1152
  }
1092
- var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
1093
- var SIZE_UNITS = { "": 1024 ** 2, k: 1024, m: 1024 ** 2, g: 1024 ** 3, t: 1024 ** 4 };
1094
- function parseSize(text) {
1095
- const match = SIZE.exec(text.trim());
1096
- return match === null ? undefined : Math.round(Number(match[1]) * SIZE_UNITS[match[2].toLowerCase()]);
1097
- }
1098
1153
  function userNameOf(passwd, uid) {
1099
1154
  for (const line of passwd.split(`
1100
1155
  `)) {
@@ -1312,7 +1367,7 @@ function limitLine(limits, name) {
1312
1367
  return limit === undefined ? "-" : `soft ${limit.soft}, hard ${limit.hard}`;
1313
1368
  }
1314
1369
  function render(info, showEnv) {
1315
- const colors = paint(process9.stdout);
1370
+ const colors = paint(process10.stdout);
1316
1371
  const memory = info.memory;
1317
1372
  const size = (bytes) => bytes === undefined ? "-" : $e(bytes);
1318
1373
  const rows = [
@@ -1364,4 +1419,4 @@ async function pid(args) {
1364
1419
  }
1365
1420
 
1366
1421
  // src/pid-cli.ts
1367
- process10.exitCode = await runMain({ name: "pid", version, run: pid });
1422
+ process11.exitCode = await runMain({ name: "pid", run: pid });
package/dist/ports-cli.js CHANGED
@@ -1,9 +1,8 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env -S bun --no-env-file
2
2
  // @bun
3
3
 
4
4
  // src/ports-cli.ts
5
5
  import process12 from "process";
6
-
7
6
  // ../kit/src/args.ts
8
7
  import process5 from "process";
9
8
  import { parseArgs } from "util";
@@ -365,17 +364,23 @@ var FULL_STOP = /\.$/;
365
364
  function usageLine(usage, colors = paint(process4.stdout)) {
366
365
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
367
366
  }
368
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces } = {}) {
369
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
367
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
368
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
370
369
  `);
371
370
  }
371
+ function exitRows(exits, colors = paint(process4.stdout)) {
372
+ if (exits.length === 0)
373
+ return [];
374
+ const width = Math.max(...exits.map(([code]) => String(code).length));
375
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
376
+ }
372
377
  function replacesRows(replaces, colors = paint(process4.stdout)) {
373
378
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
374
379
  }
375
380
  function wantsHelpJson(env = process4.env) {
376
381
  return env.KIT_HELP === "json";
377
382
  }
378
- function description(usage, { examples = [], replaces } = {}) {
383
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
379
384
  const lines = usage.replace(USAGE_PREFIX, "").split(`
380
385
  `);
381
386
  const first = lines[0];
@@ -386,7 +391,9 @@ function description(usage, { examples = [], replaces } = {}) {
386
391
  synopsis: colon === -1 ? first : first.slice(0, colon),
387
392
  summary: colon === -1 ? fallback : first.slice(colon + 2),
388
393
  ...replaces === undefined ? {} : { replaces },
389
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
394
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
395
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
396
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
390
397
  };
391
398
  }
392
399
  function exampleRows(examples, colors = paint(process4.stdout)) {
@@ -426,6 +433,15 @@ function closest(name, names) {
426
433
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
427
434
  }
428
435
  // ../kit/src/input.ts
436
+ var WHOLE = /^\d+$/;
437
+ function wholeNumber(value, name, fallback, min = 1) {
438
+ if (value === undefined)
439
+ return fallback;
440
+ const number = Number(value);
441
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
442
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
443
+ return number;
444
+ }
429
445
  var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
430
446
  var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
431
447
  function duration(value, name, fallback, unit = "s") {
@@ -510,7 +526,7 @@ function parse(args, usage, options, settings = {}) {
510
526
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
511
527
  let parsed;
512
528
  try {
513
- parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
529
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
514
530
  } catch (error) {
515
531
  const message = parseError(error);
516
532
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -518,7 +534,7 @@ function parse(args, usage, options, settings = {}) {
518
534
  const values = parsed.values;
519
535
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
520
536
  if (values.help === true) {
521
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
537
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
522
538
  throw new HelpShown;
523
539
  }
524
540
  checkChoices(parsed.values, all);
@@ -560,6 +576,18 @@ function listed(options, allowNegative) {
560
576
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
561
577
  }));
562
578
  }
579
+ function withAliases(args, options) {
580
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
581
+ if (named.size === 0)
582
+ return args;
583
+ const separator = args.indexOf("--");
584
+ const own = separator === -1 ? args : args.slice(0, separator);
585
+ return [...own.map((arg) => {
586
+ const at = arg.indexOf("=");
587
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
588
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
589
+ }), ...separator === -1 ? [] : args.slice(separator)];
590
+ }
563
591
  function withBare(args, options) {
564
592
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
565
593
  if (bare.size === 0)
@@ -740,6 +768,8 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
740
768
  var RESET_STYLE = `${ESC}[0m`;
741
769
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
742
770
  // ../kit/src/cli.ts
771
+ import { readFileSync, realpathSync } from "fs";
772
+ import { dirname as dirname2, join as join2 } from "path";
743
773
  import process8 from "process";
744
774
 
745
775
  // ../kit/src/usage.ts
@@ -882,11 +912,22 @@ async function printCandidates(found) {
882
912
  console.log(line);
883
913
  return 0;
884
914
  }
915
+ function packageVersion(entry = Bun.main) {
916
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
917
+ try {
918
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
919
+ if (typeof version === "string")
920
+ return version;
921
+ } catch {}
922
+ if (dirname2(dir) === dir)
923
+ return "0.0.0";
924
+ }
925
+ }
885
926
  async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
886
927
  if (argv[0] === COMPLETE)
887
928
  return printCandidates(leafCandidates(run, argv.slice(1)));
888
929
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
889
- console.log(version);
930
+ console.log(version ?? packageVersion());
890
931
  return 0;
891
932
  }
892
933
  let code;
@@ -895,8 +936,11 @@ async function runMain({ name, version, run, redact, usage }, argv = process8.ar
895
936
  } catch (error) {
896
937
  code = reportThrown(name, error, redact, wantsJson(argv));
897
938
  }
898
- if (usage !== false)
899
- recordUsage(usageEntry(name, undefined, argv, code));
939
+ if (usage !== false) {
940
+ try {
941
+ recordUsage(usageEntry(name, undefined, argv, code));
942
+ } catch {}
943
+ }
900
944
  return code;
901
945
  }
902
946
  // ../kit/src/secrets.ts
@@ -910,11 +954,18 @@ function isSecretName(name) {
910
954
  var {Glob } = globalThis.Bun;
911
955
  var SESSION_FILES = new Glob("*.json");
912
956
  var ACCOUNT_DIRS = new Glob("*/sessions");
913
- // package.json
914
- var version = "0.1.0";
915
-
957
+ // ../kit/src/size.ts
958
+ var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
959
+ var POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
960
+ function parseSize(text, bareUnit = 1) {
961
+ const match = SIZE.exec(text.trim());
962
+ if (match === null)
963
+ return;
964
+ const suffix = match[2].toLowerCase();
965
+ return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
966
+ }
916
967
  // src/ports.ts
917
- import { basename } from "path";
968
+ import { basename as basename2 } from "path";
918
969
  import process11 from "process";
919
970
 
920
971
  // ../kit/src/prompt.ts
@@ -1121,12 +1172,6 @@ function cgroupContainer(entries) {
1121
1172
  }
1122
1173
  return;
1123
1174
  }
1124
- var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
1125
- var SIZE_UNITS = { "": 1024 ** 2, k: 1024, m: 1024 ** 2, g: 1024 ** 3, t: 1024 ** 4 };
1126
- function parseSize(text) {
1127
- const match = SIZE.exec(text.trim());
1128
- return match === null ? undefined : Math.round(Number(match[1]) * SIZE_UNITS[match[2].toLowerCase()]);
1129
- }
1130
1175
  function userNameOf(passwd, uid) {
1131
1176
  for (const line of passwd.split(`
1132
1177
  `)) {
@@ -1328,10 +1373,11 @@ async function filterAlive(pids, signaller) {
1328
1373
  return alive;
1329
1374
  }
1330
1375
  async function terminate(pids, { escalate, graceMs, signaller = realSignaller }) {
1331
- const refused = pids.filter((pid) => !signaller.send(pid, "SIGTERM"));
1332
- const sent = pids.filter((pid) => !refused.includes(pid));
1376
+ const failed = pids.filter((pid) => !signaller.send(pid, "SIGTERM"));
1377
+ const refused = await filterAlive(failed, signaller);
1378
+ const sent = pids.filter((pid) => !failed.includes(pid));
1333
1379
  const remaining = await waitGone(sent, graceMs, signaller);
1334
- const terminated = sent.filter((pid) => !remaining.includes(pid));
1380
+ const terminated = pids.filter((pid) => failed.includes(pid) ? !refused.includes(pid) : !remaining.includes(pid));
1335
1381
  if (!escalate || remaining.length === 0)
1336
1382
  return { terminated, killed: [], survived: [...refused, ...remaining] };
1337
1383
  for (const pid of remaining)
@@ -1341,6 +1387,7 @@ async function terminate(pids, { escalate, graceMs, signaller = realSignaller })
1341
1387
  }
1342
1388
 
1343
1389
  // src/mask.ts
1390
+ import { basename } from "path";
1344
1391
  var MASK = "***";
1345
1392
  var URL_PASSWORD = /(?<![a-z0-9+.-])([a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:)[^\s'"@]{1,1024}@/gi;
1346
1393
  var TOKEN = /\b(?:gh[pousr]_|github_pat_|glpat-|sk-|xox[abprs]-|npm_|[sr]k_(?:live|test)_)[\w-]{10,}|\beyJ[\w-]+\.[\w-]+\.[\w-]+|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bBearer\s+[\w.~+/=-]{16,}/g;
@@ -1359,13 +1406,22 @@ function maskEnviron(entries) {
1359
1406
  }
1360
1407
  var FLAG = /^-{1,2}([\w.-]+)(=|$)/;
1361
1408
  var ASSIGNMENT_NAME = /^[\w.-]+$/;
1409
+ var PASSWORD_SPLIT = new Set(["sshpass"]);
1410
+ var PASSWORD_JOINED = new Set(["mysql", "mysqldump", "mysqladmin", "mariadb", "mariadb-dump"]);
1362
1411
  function maskArgs(args) {
1412
+ const command = basename(args[0] ?? "");
1363
1413
  let hidden = false;
1364
- return args.map((arg) => {
1414
+ return args.map((arg, index) => {
1365
1415
  if (hidden) {
1366
1416
  hidden = false;
1367
1417
  return arg.startsWith("-") ? maskText(arg) : MASK;
1368
1418
  }
1419
+ if (index > 0 && arg === "-p" && PASSWORD_SPLIT.has(command)) {
1420
+ hidden = true;
1421
+ return arg;
1422
+ }
1423
+ if (index > 0 && arg.length > 2 && arg.startsWith("-p") && PASSWORD_JOINED.has(command))
1424
+ return `-p${MASK}`;
1369
1425
  const flag = FLAG.exec(arg);
1370
1426
  if (flag !== null) {
1371
1427
  if (flag[2] === "=")
@@ -1412,7 +1468,7 @@ function buildRows(sockets, owners, procs, containers) {
1412
1468
  protocol: socket.protocol,
1413
1469
  addresses: [socket.address],
1414
1470
  pid,
1415
- command: proc === undefined ? undefined : maskArgs([basename(proc.args[0] ?? proc.comm), ...proc.args.slice(1)]).join(" "),
1471
+ command: proc === undefined ? undefined : maskArgs([basename2(proc.args[0] ?? proc.comm), ...proc.args.slice(1)]).join(" "),
1416
1472
  cwd: proc?.cwd,
1417
1473
  uid: proc?.uid ?? socket.uid,
1418
1474
  container: container === undefined ? undefined : { name: container.name, project: container.project, service: container.service }
@@ -1481,9 +1537,9 @@ async function ports(args) {
1481
1537
  ]
1482
1538
  });
1483
1539
  const [given] = positionals;
1484
- const port = given === undefined ? undefined : Number(given);
1485
- if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535))
1486
- badUsage(`the port takes a number from 1 to 65535, not ${given}`);
1540
+ const port = given === undefined ? undefined : wholeNumber(given, "<port>", 0);
1541
+ if (port !== undefined && port > 65535)
1542
+ badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`);
1487
1543
  if (values.kill === true && port === undefined)
1488
1544
  badUsage("--kill takes the port to free: ports <port> --kill");
1489
1545
  const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process11.getuid?.())]);
@@ -1512,4 +1568,4 @@ async function ports(args) {
1512
1568
  }
1513
1569
 
1514
1570
  // src/ports-cli.ts
1515
- process12.exitCode = await runMain({ name: "ports", version, run: ports });
1571
+ process12.exitCode = await runMain({ name: "ports", run: ports });
package/dist/procs-cli.js CHANGED
@@ -1,9 +1,8 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env -S bun --no-env-file
2
2
  // @bun
3
3
 
4
4
  // src/procs-cli.ts
5
5
  import process11 from "process";
6
-
7
6
  // ../kit/src/args.ts
8
7
  import process5 from "process";
9
8
  import { parseArgs } from "util";
@@ -376,17 +375,23 @@ var FULL_STOP = /\.$/;
376
375
  function usageLine(usage, colors = paint(process4.stdout)) {
377
376
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
378
377
  }
379
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces } = {}) {
380
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
378
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
379
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
381
380
  `);
382
381
  }
382
+ function exitRows(exits, colors = paint(process4.stdout)) {
383
+ if (exits.length === 0)
384
+ return [];
385
+ const width = Math.max(...exits.map(([code]) => String(code).length));
386
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
387
+ }
383
388
  function replacesRows(replaces, colors = paint(process4.stdout)) {
384
389
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
385
390
  }
386
391
  function wantsHelpJson(env = process4.env) {
387
392
  return env.KIT_HELP === "json";
388
393
  }
389
- function description(usage, { examples = [], replaces } = {}) {
394
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
390
395
  const lines = usage.replace(USAGE_PREFIX, "").split(`
391
396
  `);
392
397
  const first = lines[0];
@@ -397,7 +402,9 @@ function description(usage, { examples = [], replaces } = {}) {
397
402
  synopsis: colon === -1 ? first : first.slice(0, colon),
398
403
  summary: colon === -1 ? fallback : first.slice(colon + 2),
399
404
  ...replaces === undefined ? {} : { replaces },
400
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
405
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
406
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
407
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
401
408
  };
402
409
  }
403
410
  function exampleRows(examples, colors = paint(process4.stdout)) {
@@ -437,6 +444,15 @@ function closest(name, names) {
437
444
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
438
445
  }
439
446
  // ../kit/src/input.ts
447
+ var WHOLE = /^\d+$/;
448
+ function wholeNumber(value, name, fallback, min = 1) {
449
+ if (value === undefined)
450
+ return fallback;
451
+ const number = Number(value);
452
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
453
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
454
+ return number;
455
+ }
440
456
  var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
441
457
  var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
442
458
  function duration(value, name, fallback, unit = "s") {
@@ -521,7 +537,7 @@ function parse(args, usage, options, settings = {}) {
521
537
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
522
538
  let parsed;
523
539
  try {
524
- parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
540
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
525
541
  } catch (error) {
526
542
  const message = parseError(error);
527
543
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -529,7 +545,7 @@ function parse(args, usage, options, settings = {}) {
529
545
  const values = parsed.values;
530
546
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
531
547
  if (values.help === true) {
532
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
548
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
533
549
  throw new HelpShown;
534
550
  }
535
551
  checkChoices(parsed.values, all);
@@ -571,6 +587,18 @@ function listed(options, allowNegative) {
571
587
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
572
588
  }));
573
589
  }
590
+ function withAliases(args, options) {
591
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
592
+ if (named.size === 0)
593
+ return args;
594
+ const separator = args.indexOf("--");
595
+ const own = separator === -1 ? args : args.slice(0, separator);
596
+ return [...own.map((arg) => {
597
+ const at = arg.indexOf("=");
598
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
599
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
600
+ }), ...separator === -1 ? [] : args.slice(separator)];
601
+ }
574
602
  function withBare(args, options) {
575
603
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
576
604
  if (bare.size === 0)
@@ -751,6 +779,8 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
751
779
  var RESET_STYLE = `${ESC}[0m`;
752
780
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
753
781
  // ../kit/src/cli.ts
782
+ import { readFileSync, realpathSync } from "fs";
783
+ import { dirname as dirname2, join as join2 } from "path";
754
784
  import process8 from "process";
755
785
 
756
786
  // ../kit/src/usage.ts
@@ -893,11 +923,22 @@ async function printCandidates(found) {
893
923
  console.log(line);
894
924
  return 0;
895
925
  }
926
+ function packageVersion(entry = Bun.main) {
927
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
928
+ try {
929
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
930
+ if (typeof version === "string")
931
+ return version;
932
+ } catch {}
933
+ if (dirname2(dir) === dir)
934
+ return "0.0.0";
935
+ }
936
+ }
896
937
  async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
897
938
  if (argv[0] === COMPLETE)
898
939
  return printCandidates(leafCandidates(run, argv.slice(1)));
899
940
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
900
- console.log(version);
941
+ console.log(version ?? packageVersion());
901
942
  return 0;
902
943
  }
903
944
  let code;
@@ -906,8 +947,11 @@ async function runMain({ name, version, run, redact, usage }, argv = process8.ar
906
947
  } catch (error) {
907
948
  code = reportThrown(name, error, redact, wantsJson(argv));
908
949
  }
909
- if (usage !== false)
910
- recordUsage(usageEntry(name, undefined, argv, code));
950
+ if (usage !== false) {
951
+ try {
952
+ recordUsage(usageEntry(name, undefined, argv, code));
953
+ } catch {}
954
+ }
911
955
  return code;
912
956
  }
913
957
  // ../kit/src/secrets.ts
@@ -921,9 +965,16 @@ function isSecretName(name) {
921
965
  var {Glob } = globalThis.Bun;
922
966
  var SESSION_FILES = new Glob("*.json");
923
967
  var ACCOUNT_DIRS = new Glob("*/sessions");
924
- // package.json
925
- var version = "0.1.0";
926
-
968
+ // ../kit/src/size.ts
969
+ var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
970
+ var POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
971
+ function parseSize(text, bareUnit = 1) {
972
+ const match = SIZE.exec(text.trim());
973
+ if (match === null)
974
+ return;
975
+ const suffix = match[2].toLowerCase();
976
+ return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
977
+ }
927
978
  // src/procs.ts
928
979
  import { existsSync } from "fs";
929
980
  import { homedir as homedir2 } from "os";
@@ -1056,12 +1107,6 @@ function cgroupContainer(entries) {
1056
1107
  }
1057
1108
  return;
1058
1109
  }
1059
- var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
1060
- var SIZE_UNITS = { "": 1024 ** 2, k: 1024, m: 1024 ** 2, g: 1024 ** 3, t: 1024 ** 4 };
1061
- function parseSize(text) {
1062
- const match = SIZE.exec(text.trim());
1063
- return match === null ? undefined : Math.round(Number(match[1]) * SIZE_UNITS[match[2].toLowerCase()]);
1064
- }
1065
1110
  function userNameOf(passwd, uid) {
1066
1111
  for (const line of passwd.split(`
1067
1112
  `)) {
@@ -1249,10 +1294,11 @@ async function filterAlive(pids, signaller) {
1249
1294
  return alive;
1250
1295
  }
1251
1296
  async function terminate(pids, { escalate, graceMs, signaller = realSignaller }) {
1252
- const refused = pids.filter((pid) => !signaller.send(pid, "SIGTERM"));
1253
- const sent = pids.filter((pid) => !refused.includes(pid));
1297
+ const failed = pids.filter((pid) => !signaller.send(pid, "SIGTERM"));
1298
+ const refused = await filterAlive(failed, signaller);
1299
+ const sent = pids.filter((pid) => !failed.includes(pid));
1254
1300
  const remaining = await waitGone(sent, graceMs, signaller);
1255
- const terminated = sent.filter((pid) => !remaining.includes(pid));
1301
+ const terminated = pids.filter((pid) => failed.includes(pid) ? !refused.includes(pid) : !remaining.includes(pid));
1256
1302
  if (!escalate || remaining.length === 0)
1257
1303
  return { terminated, killed: [], survived: [...refused, ...remaining] };
1258
1304
  for (const pid of remaining)
@@ -1262,6 +1308,7 @@ async function terminate(pids, { escalate, graceMs, signaller = realSignaller })
1262
1308
  }
1263
1309
 
1264
1310
  // src/mask.ts
1311
+ import { basename } from "path";
1265
1312
  var MASK = "***";
1266
1313
  var URL_PASSWORD = /(?<![a-z0-9+.-])([a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:)[^\s'"@]{1,1024}@/gi;
1267
1314
  var TOKEN = /\b(?:gh[pousr]_|github_pat_|glpat-|sk-|xox[abprs]-|npm_|[sr]k_(?:live|test)_)[\w-]{10,}|\beyJ[\w-]+\.[\w-]+\.[\w-]+|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bBearer\s+[\w.~+/=-]{16,}/g;
@@ -1280,13 +1327,22 @@ function maskEnviron(entries) {
1280
1327
  }
1281
1328
  var FLAG = /^-{1,2}([\w.-]+)(=|$)/;
1282
1329
  var ASSIGNMENT_NAME = /^[\w.-]+$/;
1330
+ var PASSWORD_SPLIT = new Set(["sshpass"]);
1331
+ var PASSWORD_JOINED = new Set(["mysql", "mysqldump", "mysqladmin", "mariadb", "mariadb-dump"]);
1283
1332
  function maskArgs(args) {
1333
+ const command = basename(args[0] ?? "");
1284
1334
  let hidden = false;
1285
- return args.map((arg) => {
1335
+ return args.map((arg, index) => {
1286
1336
  if (hidden) {
1287
1337
  hidden = false;
1288
1338
  return arg.startsWith("-") ? maskText(arg) : MASK;
1289
1339
  }
1340
+ if (index > 0 && arg === "-p" && PASSWORD_SPLIT.has(command)) {
1341
+ hidden = true;
1342
+ return arg;
1343
+ }
1344
+ if (index > 0 && arg.length > 2 && arg.startsWith("-p") && PASSWORD_JOINED.has(command))
1345
+ return `-p${MASK}`;
1290
1346
  const flag = FLAG.exec(arg);
1291
1347
  if (flag !== null) {
1292
1348
  if (flag[2] === "=")
@@ -1300,7 +1356,7 @@ function maskArgs(args) {
1300
1356
  }
1301
1357
 
1302
1358
  // src/select.ts
1303
- import { basename, join as join2, relative } from "path";
1359
+ import { basename as basename2, join as join3, relative } from "path";
1304
1360
  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;
1305
1361
  var NATIVE = new Set(["rust-analyzer", "gopls", "clangd", "lua-language-server", "pyright-langserver", "pylsp", "intelephense", "phpactor", "tsgo", "esbuild", "biome", "ruff", "phpunit", "pytest", "vitest", "jest"]);
1306
1362
  var RUNTIMES = new Set(["node", "bun", "bunx", "deno", "nodejs"]);
@@ -1310,7 +1366,7 @@ var MARKERS = ["package.json", "composer.json", "Cargo.toml", "go.mod", "pyproje
1310
1366
  var AUTOMATION = /^--(?:headless|remote-debugging-(?:pipe|port)|enable-automation)/;
1311
1367
  var HEAVY_DEFAULT = 500 * 1024 ** 2;
1312
1368
  function toolOf(proc) {
1313
- const names = [proc.exe, proc.args[0], proc.comm].filter((name) => name !== undefined && name !== "").map((name) => basename(name));
1369
+ const names = [proc.exe, proc.args[0], proc.comm].filter((name) => name !== undefined && name !== "").map((name) => basename2(name));
1314
1370
  for (const name of names) {
1315
1371
  if (BROWSERS.test(name))
1316
1372
  return name.toLowerCase().startsWith("webkit") || name.toLowerCase().startsWith("wpe") || name.toLowerCase() === "minibrowser" ? "webkit" : "chromium";
@@ -1323,7 +1379,7 @@ function toolOf(proc) {
1323
1379
  for (const arg of proc.args.slice(1)) {
1324
1380
  if (arg.startsWith("-"))
1325
1381
  continue;
1326
- const script = basename(arg).replace(EXTENSION, "");
1382
+ const script = basename2(arg).replace(EXTENSION, "");
1327
1383
  if (SCRIPTS.has(script))
1328
1384
  return script;
1329
1385
  }
@@ -1337,9 +1393,9 @@ function projectOf(cwd, exists, home) {
1337
1393
  if (cwd === undefined || !cwd.startsWith(`${home}/`))
1338
1394
  return;
1339
1395
  const folders = [];
1340
- for (let dir = cwd;dir.startsWith(`${home}/`); dir = join2(dir, ".."))
1396
+ for (let dir = cwd;dir.startsWith(`${home}/`); dir = join3(dir, ".."))
1341
1397
  folders.push(dir);
1342
- return folders.find((dir) => exists(join2(dir, ".git"))) ?? folders.find((dir) => MARKERS.some((marker) => exists(join2(dir, marker))));
1398
+ return folders.find((dir) => exists(join3(dir, ".git"))) ?? folders.find((dir) => MARKERS.some((marker) => exists(join3(dir, marker))));
1343
1399
  }
1344
1400
  function isOrphan(proc, byPid) {
1345
1401
  if (proc.unit?.endsWith(".service") === true)
@@ -1350,7 +1406,7 @@ function isOrphan(proc, byPid) {
1350
1406
  const tool = toolOf(proc);
1351
1407
  if (!reparented || tool !== "chromium" && tool !== "webkit")
1352
1408
  return reparented;
1353
- if (basename(proc.exe ?? proc.args[0] ?? proc.comm).includes("crashpad"))
1409
+ if (basename2(proc.exe ?? proc.args[0] ?? proc.comm).includes("crashpad"))
1354
1410
  return false;
1355
1411
  return proc.args.some((arg) => arg.startsWith("--type=")) || proc.args.some((arg) => AUTOMATION.test(arg));
1356
1412
  }
@@ -1466,7 +1522,7 @@ async function procs(args) {
1466
1522
  "procs --kill --yes"
1467
1523
  ]
1468
1524
  });
1469
- const minMem = values["min-mem"] === undefined ? undefined : parseSize(values["min-mem"]);
1525
+ const minMem = values["min-mem"] === undefined ? undefined : parseSize(values["min-mem"], 1024 ** 2);
1470
1526
  if (values["min-mem"] !== undefined && minMem === undefined)
1471
1527
  fail(`--min-mem takes a size such as 500M or 1.5G, not ${values["min-mem"]}`, 2);
1472
1528
  const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0, "m");
@@ -1499,4 +1555,4 @@ async function procs(args) {
1499
1555
  }
1500
1556
 
1501
1557
  // src/procs-cli.ts
1502
- process11.exitCode = await runMain({ name: "procs", version, run: procs });
1558
+ process11.exitCode = await runMain({ name: "procs", run: procs });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-proc",
3
3
  "type": "module",
4
- "version": "0.1.0",
4
+ "version": "0.2.1",
5
5
  "description": "pid, ports, procs: one process inspected, who listens on a port, and leftover or heavy dev processes cleaned, read straight from /proc (Linux).",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -33,6 +33,6 @@
33
33
  "procs": "$npm_execpath src/procs-cli.ts"
34
34
  },
35
35
  "devDependencies": {
36
- "@kaynooo/cli-kit": "0.20.0"
36
+ "@kaynooo/cli-kit": "0.21.0"
37
37
  }
38
38
  }
package/src/kill.ts CHANGED
@@ -90,10 +90,12 @@ async function filterAlive(pids: number[], signaller: Signaller): Promise<number
90
90
 
91
91
  // SIGTERM to each pid, then with `escalate` SIGKILL to those still there after `graceMs`.
92
92
  export async function terminate(pids: number[], { escalate, graceMs, signaller = realSignaller }: { escalate: boolean, graceMs: number, signaller?: Signaller }): Promise<Outcome> {
93
- const refused = pids.filter(pid => !signaller.send(pid, 'SIGTERM'))
94
- const sent = pids.filter(pid => !refused.includes(pid))
93
+ const failed = pids.filter(pid => !signaller.send(pid, 'SIGTERM'))
94
+ // A pid that no longer exists (ESRCH) is gone, not a survivor; only one that exists yet refused the signal is.
95
+ const refused = await filterAlive(failed, signaller)
96
+ const sent = pids.filter(pid => !failed.includes(pid))
95
97
  const remaining = await waitGone(sent, graceMs, signaller)
96
- const terminated = sent.filter(pid => !remaining.includes(pid))
98
+ const terminated = pids.filter(pid => (failed.includes(pid) ? !refused.includes(pid) : !remaining.includes(pid)))
97
99
 
98
100
  if (!escalate || remaining.length === 0)
99
101
  return { terminated, killed: [], survived: [...refused, ...remaining] }
package/src/mask.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { basename } from 'node:path'
1
2
  import { isSecretName } from '@kaynooo/cli-kit'
2
3
 
3
4
  export const MASK = '***'
@@ -27,18 +28,31 @@ export function maskEnviron(entries: [name: string, value: string][]): [name: st
27
28
 
28
29
  const FLAG = /^-{1,2}([\w.-]+)(=|$)/
29
30
  const ASSIGNMENT_NAME = /^[\w.-]+$/
31
+ // Commands whose short -p flag carries a password; for the others (ssh, docker, psql) it is a port.
32
+ const PASSWORD_SPLIT = new Set(['sshpass'])
33
+ const PASSWORD_JOINED = new Set(['mysql', 'mysqldump', 'mysqladmin', 'mariadb', 'mariadb-dump'])
30
34
 
31
35
  // A command line with secrets masked: `--password=x`, `--token x` and `API_KEY=x` words, and secret shapes in any other.
32
36
  export function maskArgs(args: string[]): string[] {
37
+ const command = basename(args[0] ?? '')
33
38
  let hidden = false
34
39
 
35
- return args.map((arg) => {
40
+ return args.map((arg, index) => {
36
41
  if (hidden) {
37
42
  hidden = false
38
43
 
39
44
  return arg.startsWith('-') ? maskText(arg) : MASK
40
45
  }
41
46
 
47
+ if (index > 0 && arg === '-p' && PASSWORD_SPLIT.has(command)) {
48
+ hidden = true
49
+
50
+ return arg
51
+ }
52
+
53
+ if (index > 0 && arg.length > 2 && arg.startsWith('-p') && PASSWORD_JOINED.has(command))
54
+ return `-p${MASK}`
55
+
42
56
  const flag = FLAG.exec(arg)
43
57
 
44
58
  if (flag !== null) {
package/src/parse.ts CHANGED
@@ -219,16 +219,6 @@ export function cgroupContainer(entries: CgroupEntry[]): string | undefined {
219
219
  return undefined
220
220
  }
221
221
 
222
- const SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i
223
- const SIZE_UNITS: Record<string, number> = { '': 1024 ** 2, 'k': 1024, 'm': 1024 ** 2, 'g': 1024 ** 3, 't': 1024 ** 4 }
224
-
225
- // A size such as `500M`, `1.5G` or `800k` in bytes, a bare number counting megabytes; undefined when it is none.
226
- export function parseSize(text: string): number | undefined {
227
- const match = SIZE.exec(text.trim())
228
-
229
- return match === null ? undefined : Math.round(Number(match[1]) * SIZE_UNITS[match[2]!.toLowerCase()]!)
230
- }
231
-
232
222
  // The name behind a uid in /etc/passwd text.
233
223
  export function userNameOf(passwd: string, uid: number): string | undefined {
234
224
  for (const line of passwd.split('\n')) {
package/src/pid-cli.ts CHANGED
@@ -1,8 +1,7 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env -S bun --no-env-file
2
2
 
3
3
  import process from 'node:process'
4
4
  import { runMain } from '@kaynooo/cli-kit'
5
- import { version } from '../package.json'
6
5
  import { pid } from './pid'
7
6
 
8
- process.exitCode = await runMain({ name: 'pid', version, run: pid })
7
+ process.exitCode = await runMain({ name: 'pid', run: pid })
package/src/ports-cli.ts CHANGED
@@ -1,8 +1,7 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env -S bun --no-env-file
2
2
 
3
3
  import process from 'node:process'
4
4
  import { runMain } from '@kaynooo/cli-kit'
5
- import { version } from '../package.json'
6
5
  import { ports } from './ports'
7
6
 
8
- process.exitCode = await runMain({ name: 'ports', version, run: ports })
7
+ process.exitCode = await runMain({ name: 'ports', run: ports })
package/src/ports.ts CHANGED
@@ -2,7 +2,7 @@ import type { Container, Protocol, Socket } from './parse'
2
2
  import type { ProcInfo } from './read'
3
3
  import { basename } from 'node:path'
4
4
  import process from 'node:process'
5
- import { badUsage, duration, fail, jsonOption, paint, parse, printJson, table, truncate } from '@kaynooo/cli-kit'
5
+ import { badUsage, duration, fail, jsonOption, paint, parse, printJson, table, truncate, wholeNumber } from '@kaynooo/cli-kit'
6
6
  import { confirm } from '@kaynooo/cli-kit/prompt'
7
7
  import { dockerContainers } from './docker'
8
8
  import { protectionOf, terminate } from './kill'
@@ -151,10 +151,10 @@ export async function ports(args: string[]): Promise<number> {
151
151
  ],
152
152
  })
153
153
  const [given] = positionals
154
- const port = given === undefined ? undefined : Number(given)
154
+ const port = given === undefined ? undefined : wholeNumber(given, '<port>', 0)
155
155
 
156
- if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65_535))
157
- badUsage(`the port takes a number from 1 to 65535, not ${given}`)
156
+ if (port !== undefined && port > 65_535)
157
+ badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`)
158
158
 
159
159
  if (values.kill === true && port === undefined)
160
160
  badUsage('--kill takes the port to free: ports <port> --kill')
package/src/procs-cli.ts CHANGED
@@ -1,8 +1,7 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env -S bun --no-env-file
2
2
 
3
3
  import process from 'node:process'
4
4
  import { runMain } from '@kaynooo/cli-kit'
5
- import { version } from '../package.json'
6
5
  import { procs } from './procs'
7
6
 
8
- process.exitCode = await runMain({ name: 'procs', version, run: procs })
7
+ process.exitCode = await runMain({ name: 'procs', run: procs })
package/src/procs.ts CHANGED
@@ -2,10 +2,9 @@ import type { Group } from './select'
2
2
  import { existsSync } from 'node:fs'
3
3
  import { homedir } from 'node:os'
4
4
  import process from 'node:process'
5
- import { duration, fail, formatFileSize, formatSeconds, jsonOption, paint, parse, printJson, table, truncate } from '@kaynooo/cli-kit'
5
+ import { duration, fail, formatFileSize, formatSeconds, jsonOption, paint, parse, parseSize, printJson, table, truncate } from '@kaynooo/cli-kit'
6
6
  import { terminate } from './kill'
7
7
  import { maskArgs } from './mask'
8
- import { parseSize } from './parse'
9
8
  import { ancestry, snapshot } from './read'
10
9
  import { selectGroups } from './select'
11
10
 
@@ -69,7 +68,7 @@ export async function procs(args: string[]): Promise<number> {
69
68
  'procs --kill --yes',
70
69
  ],
71
70
  })
72
- const minMem = values['min-mem'] === undefined ? undefined : parseSize(values['min-mem'])
71
+ const minMem = values['min-mem'] === undefined ? undefined : parseSize(values['min-mem'], 1024 ** 2)
73
72
 
74
73
  if (values['min-mem'] !== undefined && minMem === undefined)
75
74
  fail(`--min-mem takes a size such as 500M or 1.5G, not ${values['min-mem']}`, 2)