@kaynooo/cli-proc 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ports-cli.js CHANGED
@@ -2,16 +2,37 @@
2
2
  // @bun
3
3
 
4
4
  // src/ports-cli.ts
5
- import process12 from "process";
5
+ import process14 from "process";
6
6
  // ../kit/src/args.ts
7
- import process5 from "process";
7
+ import process6 from "process";
8
8
  import { parseArgs } from "util";
9
9
 
10
10
  // ../kit/src/format.ts
11
- import process3 from "process";
11
+ import process4 from "process";
12
12
 
13
- // ../kit/src/style.ts
13
+ // ../kit/src/mode.ts
14
14
  import process2 from "process";
15
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
16
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
17
+ function isSet(value) {
18
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
19
+ }
20
+ function outputMode(stream = process2.stdout, env = process2.env) {
21
+ const chosen = env.KIT_MODE;
22
+ if (chosen !== undefined && MODES.has(chosen))
23
+ return chosen;
24
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
25
+ return "agent";
26
+ if (stream.isTTY === true)
27
+ return "terminal";
28
+ return isSet(env.CI) ? "ci" : "pipe";
29
+ }
30
+ function isInteractive(streams = process2) {
31
+ return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
32
+ }
33
+
34
+ // ../kit/src/style.ts
35
+ import process3 from "process";
15
36
 
16
37
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
17
38
  function x(s) {
@@ -274,21 +295,26 @@ function le(i = {}) {
274
295
  }
275
296
  var t = le();
276
297
 
298
+ // ../kit/src/theme.ts
299
+ 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"]);
300
+ var MAX_FILE_BYTES = 64 * 1024;
301
+ var warned = new Set;
302
+
277
303
  // ../kit/src/style.ts
278
- function takesControlCodes(stream, env = process2.env) {
279
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
304
+ function takesControlCodes(stream, env = process3.env) {
305
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
280
306
  }
281
- function paint(stream, env = process2.env) {
307
+ function paint(stream, env = process3.env) {
282
308
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
283
309
  }
284
- var STATUSES = {
285
- passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
286
- failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
287
- running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
288
- queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
289
- skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
310
+ var STATUS_WORDS = {
311
+ passed: ["passed", "success", "succeeded", "ok"],
312
+ failed: ["failed", "failure", "error", "errored"],
313
+ running: ["running", "in_progress", "started", "holding"],
314
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
315
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
290
316
  };
291
- var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
317
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
292
318
 
293
319
  // ../kit/src/format.ts
294
320
  var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
@@ -317,15 +343,18 @@ var ESCAPE = String.fromCharCode(27);
317
343
  function textWidth(text) {
318
344
  return Bun.stringWidth(text);
319
345
  }
320
- function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
346
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process4.stdout, env = process4.env } = {}) {
321
347
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
348
+ if (outputMode(stream, env) === "agent")
349
+ return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
350
+ `);
322
351
  const widths = [];
323
352
  for (const row of cells) {
324
353
  for (const [index, cell] of row.entries())
325
354
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
326
355
  }
327
356
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
328
- const colors = paint(process3.stdout);
357
+ const colors = paint(stream);
329
358
  const lines = shown.map((row) => row.map((cell, index) => {
330
359
  const width = widths[index] ?? 0;
331
360
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -333,7 +362,8 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
333
362
  return `${gap}${cell}`;
334
363
  return index === row.length - 1 ? cell : `${cell}${gap}`;
335
364
  }).join(" ").trimEnd());
336
- return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
365
+ const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
366
+ return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
337
367
  `);
338
368
  }
339
369
  function narrow(rows, widths, limit) {
@@ -352,32 +382,35 @@ function narrow(rows, widths, limit) {
352
382
  }
353
383
  return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
354
384
  }
385
+ function jsonText(value, replacer, { stream = process4.stdout, env = process4.env } = {}) {
386
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
387
+ }
355
388
  function printJson(value) {
356
- console.log(JSON.stringify(value, undefined, 2));
389
+ console.log(jsonText(value));
357
390
  }
358
391
 
359
392
  // ../kit/src/help.ts
360
- import process4 from "process";
393
+ import process5 from "process";
361
394
  var OPTIONAL = /\[[^\]]+\]/g;
362
395
  var USAGE_PREFIX = /^usage:\s*/i;
363
396
  var FULL_STOP = /\.$/;
364
- function usageLine(usage, colors = paint(process4.stdout)) {
397
+ function usageLine(usage, colors = paint(process5.stdout)) {
365
398
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
366
399
  }
367
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
400
+ function helpText(usage, options, colors = paint(process5.stdout), { examples = [], replaces, exits = [] } = {}) {
368
401
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
369
402
  `);
370
403
  }
371
- function exitRows(exits, colors = paint(process4.stdout)) {
404
+ function exitRows(exits, colors = paint(process5.stdout)) {
372
405
  if (exits.length === 0)
373
406
  return [];
374
407
  const width = Math.max(...exits.map(([code]) => String(code).length));
375
408
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
376
409
  }
377
- function replacesRows(replaces, colors = paint(process4.stdout)) {
378
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
410
+ function replacesRows(replaces, colors = paint(process5.stdout)) {
411
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
379
412
  }
380
- function wantsHelpJson(env = process4.env) {
413
+ function wantsHelpJson(env = process5.env) {
381
414
  return env.KIT_HELP === "json";
382
415
  }
383
416
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -396,12 +429,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
396
429
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
397
430
  };
398
431
  }
399
- function exampleRows(examples, colors = paint(process4.stdout)) {
400
- if (examples.length === 0)
432
+ function exampleRows(examples, colors = paint(process5.stdout)) {
433
+ if (examples.length === 0 || outputMode() === "agent")
401
434
  return [];
402
435
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
403
436
  }
404
- function optionRows(options, colors = paint(process4.stdout)) {
437
+ function optionRows(options, colors = paint(process5.stdout)) {
405
438
  const rows = Object.entries(options).map(([name, option]) => {
406
439
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
407
440
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -459,7 +492,6 @@ var DASHES = /^-+/;
459
492
  function jsonOption(holds) {
460
493
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
461
494
  }
462
-
463
495
  class Exit extends Error {
464
496
  code;
465
497
  hint;
@@ -503,7 +535,7 @@ var OUTPUT_OPTIONS = {
503
535
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
504
536
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
505
537
  };
506
- function applyOutput(color, plain, env = process5.env) {
538
+ function applyOutput(color, plain, env = process6.env) {
507
539
  const when = plain === true ? "never" : color ?? "auto";
508
540
  if (when === "auto")
509
541
  return;
@@ -674,7 +706,7 @@ function nearestOption(message, options, allowNegative) {
674
706
  }
675
707
  // ../kit/src/process.ts
676
708
  import { constants } from "os";
677
- import process6 from "process";
709
+ import process7 from "process";
678
710
  var KILL_GRACE_MS = 2000;
679
711
  function exitCodeOf(code, signal) {
680
712
  if (code !== null)
@@ -694,7 +726,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
694
726
  return;
695
727
  try {
696
728
  if (grouped)
697
- process6.kill(-proc.pid, killing);
729
+ process7.kill(-proc.pid, killing);
698
730
  else
699
731
  proc.kill(killing);
700
732
  } catch {}
@@ -770,13 +802,13 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
770
802
  // ../kit/src/cli.ts
771
803
  import { readFileSync, realpathSync } from "fs";
772
804
  import { dirname as dirname2, join as join2 } from "path";
773
- import process8 from "process";
805
+ import process9 from "process";
774
806
 
775
807
  // ../kit/src/usage.ts
776
808
  import { appendFileSync, mkdirSync } from "fs";
777
809
  import { homedir } from "os";
778
810
  import { dirname, isAbsolute, join } from "path";
779
- import process7 from "process";
811
+ import process8 from "process";
780
812
 
781
813
  // ../kit/src/logs.ts
782
814
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -790,14 +822,14 @@ var usageError;
790
822
  function noteUsageError(message) {
791
823
  usageError = message;
792
824
  }
793
- function stateHome(env = process7.env) {
825
+ function stateHome(env = process8.env) {
794
826
  const dir = env.XDG_STATE_HOME;
795
827
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
796
828
  }
797
- function usagePath(env = process7.env) {
829
+ function usagePath(env = process8.env) {
798
830
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
799
831
  }
800
- function usageRecorded(env = process7.env) {
832
+ function usageRecorded(env = process8.env) {
801
833
  const off = env.KAYNOOO_CLI_NO_USAGE;
802
834
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
803
835
  }
@@ -811,7 +843,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
811
843
  usageError = undefined;
812
844
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
813
845
  }
814
- function recordUsage(entry, env = process7.env) {
846
+ function recordUsage(entry, env = process8.env) {
815
847
  if (!usageRecorded(env))
816
848
  return;
817
849
  try {
@@ -902,8 +934,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
902
934
  `);
903
935
  }
904
936
  function printError(prefix, message, hint, cause) {
905
- const colors = paint(process8.stderr);
906
- const styled = takesControlCodes(process8.stderr);
937
+ const colors = paint(process9.stderr);
938
+ const styled = takesControlCodes(process9.stderr);
907
939
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
908
940
  const under = (label, text, tint) => text === undefined ? "" : `
909
941
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -946,11 +978,11 @@ async function dispatch(level, typed, { version, redact }) {
946
978
  }
947
979
  }
948
980
  if (name === undefined && level.path.length > 1) {
949
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
981
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
950
982
  return 2;
951
983
  }
952
984
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
953
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
985
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
954
986
  return 0;
955
987
  }
956
988
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1077,7 +1109,7 @@ function packageVersion(entry = Bun.main) {
1077
1109
  return "0.0.0";
1078
1110
  }
1079
1111
  }
1080
- async function runCli(cli, argv = process8.argv.slice(2)) {
1112
+ async function runCli(cli, argv = process9.argv.slice(2)) {
1081
1113
  const version = cli.version ?? packageVersion();
1082
1114
  if (argv[0] === COMPLETE)
1083
1115
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -1104,7 +1136,7 @@ function commandPath(scope, argv) {
1104
1136
  }
1105
1137
  return path.length === 0 ? undefined : path.join(" ");
1106
1138
  }
1107
- async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
1139
+ async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
1108
1140
  if (argv[0] === COMPLETE)
1109
1141
  return printCandidates(leafCandidates(run, argv.slice(1)));
1110
1142
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1145,17 +1177,124 @@ function parseSize(text, bareUnit = 1) {
1145
1177
  const suffix = match[2].toLowerCase();
1146
1178
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1147
1179
  }
1180
+ // ../kit/src/watch.ts
1181
+ import process10 from "process";
1182
+ import { format } from "util";
1183
+ var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1184
+ var DEFAULT_SECONDS = 2;
1185
+ var ATTACHED_SHORT = /^-w./;
1186
+ var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
1187
+ function watchOption(what) {
1188
+ return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
1189
+ }
1190
+ function withoutWatch(args) {
1191
+ const rest = [];
1192
+ for (let at = 0;at < args.length; at++) {
1193
+ const arg = args[at];
1194
+ if (arg === "--watch" || arg === "-w") {
1195
+ if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
1196
+ at++;
1197
+ } else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
1198
+ rest.push(arg);
1199
+ }
1200
+ }
1201
+ return rest;
1202
+ }
1203
+ async function watching(value, step, stream = process10.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1204
+ const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1205
+ if (!takesControlCodes(stream))
1206
+ badUsage("--watch redraws the screen, so it needs a terminal");
1207
+ let code = 0;
1208
+ for (let round = 0;round < rounds; round++) {
1209
+ const held = [];
1210
+ const { log, info } = console;
1211
+ const write = process10.stdout.write.bind(process10.stdout);
1212
+ const hold = (...parts) => void held.push(`${format(...parts)}
1213
+ `);
1214
+ console.log = hold;
1215
+ console.info = hold;
1216
+ process10.stdout.write = (text) => {
1217
+ held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1218
+ return true;
1219
+ };
1220
+ try {
1221
+ code = await step();
1222
+ } finally {
1223
+ console.log = log;
1224
+ console.info = info;
1225
+ process10.stdout.write = write;
1226
+ }
1227
+ stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1228
+ await sleep(interval);
1229
+ }
1230
+ return code;
1231
+ }
1148
1232
  // src/ports.ts
1149
1233
  import { basename as basename2 } from "path";
1150
- import process11 from "process";
1234
+ import process13 from "process";
1151
1235
 
1152
1236
  // ../kit/src/prompt.ts
1153
- import process10 from "process";
1154
- var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|[\s\S]/giu;
1155
- var CONTROL = /^[\x00-\x1F\x7F]/;
1156
- var KEYS = { "\x1B[A": "up", "\x1BOA": "up", "\x1B[B": "down", "\x1BOB": "down", "\r": "enter", "\n": "enter", "\x03": "cancel", "\x1B": "cancel", "\x7F": "erase", "\b": "erase" };
1157
- function readKeys(input) {
1158
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => KEYS[sequence] ?? (CONTROL.test(sequence) ? [] : [{ text: sequence }]));
1237
+ import process12 from "process";
1238
+
1239
+ // ../kit/src/picker/score.ts
1240
+ var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1241
+ var NONE = Number.NEGATIVE_INFINITY;
1242
+
1243
+ // ../kit/src/picker/state.ts
1244
+ var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1245
+ var PASTE_START = "\x1B[200~";
1246
+ var PASTE_END = "\x1B[201~";
1247
+ var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1248
+ var KEYS = {
1249
+ "\x1B[A": "up",
1250
+ "\x1BOA": "up",
1251
+ "\x10": "up",
1252
+ "\x1B[B": "down",
1253
+ "\x1BOB": "down",
1254
+ "\x0E": "down",
1255
+ "\x1B[5~": "pageup",
1256
+ "\x1B[6~": "pagedown",
1257
+ "\x1B[H": "home",
1258
+ "\x1B[1~": "home",
1259
+ "\x1BOH": "home",
1260
+ "\x1B[F": "end",
1261
+ "\x1B[4~": "end",
1262
+ "\x1BOF": "end",
1263
+ "\r": "enter",
1264
+ "\n": "enter",
1265
+ "\x03": "cancel",
1266
+ "\x1B": "cancel",
1267
+ "\x7F": "erase",
1268
+ "\b": "erase",
1269
+ "\x15": "clear",
1270
+ "\x17": "word",
1271
+ "\t": "tab",
1272
+ "\x1F": "help",
1273
+ "\x1BOP": "help",
1274
+ "\x1B[11~": "help"
1275
+ };
1276
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
1277
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1278
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1279
+ const named = codes.get(sequence);
1280
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1281
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1282
+ paste.active = sequence === PASTE_START;
1283
+ return [];
1284
+ }
1285
+ if (paste.active && (sequence === "\r" || sequence === `
1286
+ `))
1287
+ return [];
1288
+ if (key !== undefined)
1289
+ return [key];
1290
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1291
+ });
1292
+ }
1293
+
1294
+ // ../kit/src/prompt.ts
1295
+ var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "erase"]);
1296
+ function readKeys(input, paste = { active: false }) {
1297
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key));
1159
1298
  }
1160
1299
  async function confirm(question, { default: fallback, ...settings } = {}) {
1161
1300
  let answered = fallback;
@@ -1179,27 +1318,34 @@ function asking(colors, question, typed, keys) {
1179
1318
  function answer(colors, question, state, picked) {
1180
1319
  return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1181
1320
  }
1182
- async function ask(question, { hint, terminal = process10 }, render, press) {
1321
+ async function ask(question, { hint, terminal = process12 }, render, press) {
1183
1322
  const { stdin, stderr } = terminal;
1184
- if (stdin.isTTY !== true || stderr.isTTY !== true)
1323
+ if (!isInteractive(terminal))
1185
1324
  fail(`cannot ask "${question}" off a terminal`, 2, hint);
1186
1325
  const colors = paint(stderr);
1187
- let drawn = 0;
1326
+ let drawn = [];
1327
+ let current = "asking";
1188
1328
  let outcome;
1329
+ const columns = () => stderr.columns || 80;
1189
1330
  const draw = (state) => {
1190
- const frame = render(colors, state, { columns: stderr.columns || 80, rows: stderr.rows || 24 });
1191
- stderr.write(`${drawn > 1 ? `\x1B[${drawn - 1}A` : ""}\r\x1B[0J${frame.join(`
1331
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1332
+ const rows = drawn.reduce((sum, line) => sum + Math.max(1, Math.ceil(Bun.stringWidth(line) / columns())), 0);
1333
+ stderr.write(`${rows > 1 ? `\x1B[${rows - 1}A` : ""}\r\x1B[0J${frame.join(`
1192
1334
  `)}`);
1193
- drawn = frame.length;
1335
+ drawn = frame;
1336
+ current = state;
1194
1337
  };
1338
+ const redraw = () => draw(current);
1339
+ const paste = { active: false };
1195
1340
  try {
1341
+ stderr.on?.("resize", redraw);
1196
1342
  stdin.setRawMode(true);
1197
1343
  stdin.resume();
1198
- stderr.write("\x1B[?25l");
1344
+ stderr.write("\x1B[?25l\x1B[?2004h");
1199
1345
  draw("asking");
1200
1346
  return await new Promise((resolve) => {
1201
1347
  function onData(data) {
1202
- for (const key of readKeys(data.toString())) {
1348
+ for (const key of readKeys(data.toString(), paste)) {
1203
1349
  const pressed = press(key);
1204
1350
  if (pressed !== undefined) {
1205
1351
  settle(pressed);
@@ -1221,9 +1367,10 @@ async function ask(question, { hint, terminal = process10 }, render, press) {
1221
1367
  stdin.on("end", onEnd);
1222
1368
  });
1223
1369
  } finally {
1370
+ stderr.off?.("resize", redraw);
1224
1371
  draw(outcome ?? "cancel");
1225
1372
  stderr.write(`
1226
- \x1B[?25h`);
1373
+ \x1B[?25h\x1B[?2004l`);
1227
1374
  stdin.setRawMode(false);
1228
1375
  stdin.pause();
1229
1376
  }
@@ -1625,7 +1772,8 @@ Lists what listens on this machine, TCP and UDP over IPv4 and IPv6, one row per
1625
1772
  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.`;
1626
1773
  var options = {
1627
1774
  json: jsonOption("[{ port, protocol, addresses, pid, command, cwd, container }]"),
1628
- kill: { type: "boolean", description: "stop the owner of the given port" },
1775
+ kill: { type: "boolean", conflicts: ["watch"], description: "stop the owner of the given port" },
1776
+ watch: watchOption("the ports"),
1629
1777
  force: { type: "boolean", description: "with --kill, SIGKILL what SIGTERM did not stop within --grace" },
1630
1778
  yes: { type: "boolean", short: "y", description: "with --kill, do not ask first" },
1631
1779
  grace: { type: "string", description: "with --force, how long SIGTERM gets before SIGKILL (5s)" }
@@ -1669,7 +1817,7 @@ function refusal(row, proc, guard) {
1669
1817
  return reason === undefined ? undefined : `pid ${row.pid} is ${reason}`;
1670
1818
  }
1671
1819
  function render(rows) {
1672
- const colors = paint(process11.stdout);
1820
+ const colors = paint(process13.stdout);
1673
1821
  const cells = rows.map((row) => [
1674
1822
  colors.cyan(String(row.port)),
1675
1823
  row.protocol,
@@ -1681,7 +1829,7 @@ function render(rows) {
1681
1829
  return table([["PORT", "PROTO", "ADDRESS", "PID", "COMMAND", "CWD"], ...cells], { header: true });
1682
1830
  }
1683
1831
  async function stop(port, rows, procs, values) {
1684
- const guard = { uid: process11.getuid?.() ?? -1, mine: new Set(ancestry(process11.pid, procs)) };
1832
+ const guard = { uid: process13.getuid?.() ?? -1, mine: new Set(ancestry(process13.pid, procs)) };
1685
1833
  const targets = new Map;
1686
1834
  for (const row of rows) {
1687
1835
  const reason = refusal(row, row.pid === undefined ? undefined : procs.get(row.pid), guard);
@@ -1694,7 +1842,7 @@ async function stop(port, rows, procs, values) {
1694
1842
  return 1;
1695
1843
  const names = [...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? "", 40)})`).join(", ");
1696
1844
  if (values.yes !== true) {
1697
- if (!process11.stdin.isTTY)
1845
+ if (!process13.stdin.isTTY)
1698
1846
  fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2);
1699
1847
  if (await confirm(`Stop ${names}?`, { default: false }) !== true)
1700
1848
  return 1;
@@ -1717,13 +1865,15 @@ async function ports(args) {
1717
1865
  "ports --json"
1718
1866
  ]
1719
1867
  });
1868
+ if (values.watch !== undefined)
1869
+ return watching(values.watch, async () => ports(withoutWatch(args)));
1720
1870
  const [given] = positionals;
1721
1871
  const port = given === undefined ? undefined : wholeNumber(given, "<port>", 0);
1722
1872
  if (port !== undefined && port > 65535)
1723
1873
  badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`);
1724
1874
  if (values.kill === true && port === undefined)
1725
1875
  badUsage("--kill takes the port to free: ports <port> --kill");
1726
- const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process11.getuid?.())]);
1876
+ const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process13.getuid?.())]);
1727
1877
  const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
1728
1878
  const wanted = sockets.filter((socket) => port === undefined || socket.port === port);
1729
1879
  const needsDocker = wanted.some((socket) => {
@@ -1744,9 +1894,9 @@ async function ports(args) {
1744
1894
  console.log(render(rows));
1745
1895
  const unknown = rows.filter((row) => row.pid === undefined && row.container === undefined).length;
1746
1896
  if (unknown > 0)
1747
- console.error(paint(process11.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
1897
+ console.error(paint(process13.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
1748
1898
  return 0;
1749
1899
  }
1750
1900
 
1751
1901
  // src/ports-cli.ts
1752
- process12.exitCode = await runMain({ name: "ports", run: ports });
1902
+ process14.exitCode = await runMain({ name: "ports", run: ports });