@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/pid-cli.js CHANGED
@@ -2,16 +2,37 @@
2
2
  // @bun
3
3
 
4
4
  // src/pid-cli.ts
5
- import process11 from "process";
5
+ import process13 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
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-hrsswv1w.js
293
319
  function $e(t, e = false, i = 1) {
294
320
  let n = typeof e === "object" ? e : { units: e ? "si" : "iec", dp: i }, { units: s = "iec", dp: u = 1 } = n, r = s === "si" ? 1000 : 1024;
@@ -328,15 +354,18 @@ var ESCAPE = String.fromCharCode(27);
328
354
  function textWidth(text) {
329
355
  return Bun.stringWidth(text);
330
356
  }
331
- function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
357
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process4.stdout, env = process4.env } = {}) {
332
358
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
359
+ if (outputMode(stream, env) === "agent")
360
+ return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
361
+ `);
333
362
  const widths = [];
334
363
  for (const row of cells) {
335
364
  for (const [index, cell] of row.entries())
336
365
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
337
366
  }
338
367
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
339
- const colors = paint(process3.stdout);
368
+ const colors = paint(stream);
340
369
  const lines = shown.map((row) => row.map((cell, index) => {
341
370
  const width = widths[index] ?? 0;
342
371
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -344,7 +373,8 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
344
373
  return `${gap}${cell}`;
345
374
  return index === row.length - 1 ? cell : `${cell}${gap}`;
346
375
  }).join(" ").trimEnd());
347
- return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
376
+ const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
377
+ return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
348
378
  `);
349
379
  }
350
380
  function narrow(rows, widths, limit) {
@@ -363,32 +393,35 @@ function narrow(rows, widths, limit) {
363
393
  }
364
394
  return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
365
395
  }
396
+ function jsonText(value, replacer, { stream = process4.stdout, env = process4.env } = {}) {
397
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
398
+ }
366
399
  function printJson(value) {
367
- console.log(JSON.stringify(value, undefined, 2));
400
+ console.log(jsonText(value));
368
401
  }
369
402
 
370
403
  // ../kit/src/help.ts
371
- import process4 from "process";
404
+ import process5 from "process";
372
405
  var OPTIONAL = /\[[^\]]+\]/g;
373
406
  var USAGE_PREFIX = /^usage:\s*/i;
374
407
  var FULL_STOP = /\.$/;
375
- function usageLine(usage, colors = paint(process4.stdout)) {
408
+ function usageLine(usage, colors = paint(process5.stdout)) {
376
409
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
377
410
  }
378
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
411
+ function helpText(usage, options, colors = paint(process5.stdout), { examples = [], replaces, exits = [] } = {}) {
379
412
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
380
413
  `);
381
414
  }
382
- function exitRows(exits, colors = paint(process4.stdout)) {
415
+ function exitRows(exits, colors = paint(process5.stdout)) {
383
416
  if (exits.length === 0)
384
417
  return [];
385
418
  const width = Math.max(...exits.map(([code]) => String(code).length));
386
419
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
387
420
  }
388
- function replacesRows(replaces, colors = paint(process4.stdout)) {
389
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
421
+ function replacesRows(replaces, colors = paint(process5.stdout)) {
422
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
390
423
  }
391
- function wantsHelpJson(env = process4.env) {
424
+ function wantsHelpJson(env = process5.env) {
392
425
  return env.KIT_HELP === "json";
393
426
  }
394
427
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -407,12 +440,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
407
440
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
408
441
  };
409
442
  }
410
- function exampleRows(examples, colors = paint(process4.stdout)) {
411
- if (examples.length === 0)
443
+ function exampleRows(examples, colors = paint(process5.stdout)) {
444
+ if (examples.length === 0 || outputMode() === "agent")
412
445
  return [];
413
446
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
414
447
  }
415
- function optionRows(options, colors = paint(process4.stdout)) {
448
+ function optionRows(options, colors = paint(process5.stdout)) {
416
449
  const rows = Object.entries(options).map(([name, option]) => {
417
450
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
418
451
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -470,7 +503,6 @@ var DASHES = /^-+/;
470
503
  function jsonOption(holds) {
471
504
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
472
505
  }
473
-
474
506
  class Exit extends Error {
475
507
  code;
476
508
  hint;
@@ -514,7 +546,7 @@ var OUTPUT_OPTIONS = {
514
546
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
515
547
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
516
548
  };
517
- function applyOutput(color, plain, env = process5.env) {
549
+ function applyOutput(color, plain, env = process6.env) {
518
550
  const when = plain === true ? "never" : color ?? "auto";
519
551
  if (when === "auto")
520
552
  return;
@@ -685,7 +717,7 @@ function nearestOption(message, options, allowNegative) {
685
717
  }
686
718
  // ../kit/src/process.ts
687
719
  import { constants } from "os";
688
- import process6 from "process";
720
+ import process7 from "process";
689
721
  var KILL_GRACE_MS = 2000;
690
722
  function exitCodeOf(code, signal) {
691
723
  if (code !== null)
@@ -705,7 +737,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
705
737
  return;
706
738
  try {
707
739
  if (grouped)
708
- process6.kill(-proc.pid, killing);
740
+ process7.kill(-proc.pid, killing);
709
741
  else
710
742
  proc.kill(killing);
711
743
  } catch {}
@@ -781,13 +813,13 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
781
813
  // ../kit/src/cli.ts
782
814
  import { readFileSync, realpathSync } from "fs";
783
815
  import { dirname as dirname2, join as join2 } from "path";
784
- import process8 from "process";
816
+ import process9 from "process";
785
817
 
786
818
  // ../kit/src/usage.ts
787
819
  import { appendFileSync, mkdirSync } from "fs";
788
820
  import { homedir } from "os";
789
821
  import { dirname, isAbsolute, join } from "path";
790
- import process7 from "process";
822
+ import process8 from "process";
791
823
 
792
824
  // ../kit/src/logs.ts
793
825
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -801,14 +833,14 @@ var usageError;
801
833
  function noteUsageError(message) {
802
834
  usageError = message;
803
835
  }
804
- function stateHome(env = process7.env) {
836
+ function stateHome(env = process8.env) {
805
837
  const dir = env.XDG_STATE_HOME;
806
838
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
807
839
  }
808
- function usagePath(env = process7.env) {
840
+ function usagePath(env = process8.env) {
809
841
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
810
842
  }
811
- function usageRecorded(env = process7.env) {
843
+ function usageRecorded(env = process8.env) {
812
844
  const off = env.KAYNOOO_CLI_NO_USAGE;
813
845
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
814
846
  }
@@ -822,7 +854,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
822
854
  usageError = undefined;
823
855
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
824
856
  }
825
- function recordUsage(entry, env = process7.env) {
857
+ function recordUsage(entry, env = process8.env) {
826
858
  if (!usageRecorded(env))
827
859
  return;
828
860
  try {
@@ -913,8 +945,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
913
945
  `);
914
946
  }
915
947
  function printError(prefix, message, hint, cause) {
916
- const colors = paint(process8.stderr);
917
- const styled = takesControlCodes(process8.stderr);
948
+ const colors = paint(process9.stderr);
949
+ const styled = takesControlCodes(process9.stderr);
918
950
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
919
951
  const under = (label, text, tint) => text === undefined ? "" : `
920
952
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -957,11 +989,11 @@ async function dispatch(level, typed, { version, redact }) {
957
989
  }
958
990
  }
959
991
  if (name === undefined && level.path.length > 1) {
960
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
992
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
961
993
  return 2;
962
994
  }
963
995
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
964
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
996
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
965
997
  return 0;
966
998
  }
967
999
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1088,7 +1120,7 @@ function packageVersion(entry = Bun.main) {
1088
1120
  return "0.0.0";
1089
1121
  }
1090
1122
  }
1091
- async function runCli(cli, argv = process8.argv.slice(2)) {
1123
+ async function runCli(cli, argv = process9.argv.slice(2)) {
1092
1124
  const version = cli.version ?? packageVersion();
1093
1125
  if (argv[0] === COMPLETE)
1094
1126
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -1115,7 +1147,7 @@ function commandPath(scope, argv) {
1115
1147
  }
1116
1148
  return path.length === 0 ? undefined : path.join(" ");
1117
1149
  }
1118
- async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
1150
+ async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
1119
1151
  if (argv[0] === COMPLETE)
1120
1152
  return printCandidates(leafCandidates(run, argv.slice(1)));
1121
1153
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1156,8 +1188,60 @@ function parseSize(text, bareUnit = 1) {
1156
1188
  const suffix = match[2].toLowerCase();
1157
1189
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1158
1190
  }
1159
- // src/pid.ts
1191
+ // ../kit/src/watch.ts
1160
1192
  import process10 from "process";
1193
+ import { format } from "util";
1194
+ var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1195
+ var DEFAULT_SECONDS = 2;
1196
+ var ATTACHED_SHORT = /^-w./;
1197
+ var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
1198
+ function watchOption(what) {
1199
+ return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
1200
+ }
1201
+ function withoutWatch(args) {
1202
+ const rest = [];
1203
+ for (let at = 0;at < args.length; at++) {
1204
+ const arg = args[at];
1205
+ if (arg === "--watch" || arg === "-w") {
1206
+ if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
1207
+ at++;
1208
+ } else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
1209
+ rest.push(arg);
1210
+ }
1211
+ }
1212
+ return rest;
1213
+ }
1214
+ async function watching(value, step, stream = process10.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1215
+ const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1216
+ if (!takesControlCodes(stream))
1217
+ badUsage("--watch redraws the screen, so it needs a terminal");
1218
+ let code = 0;
1219
+ for (let round = 0;round < rounds; round++) {
1220
+ const held = [];
1221
+ const { log, info } = console;
1222
+ const write = process10.stdout.write.bind(process10.stdout);
1223
+ const hold = (...parts) => void held.push(`${format(...parts)}
1224
+ `);
1225
+ console.log = hold;
1226
+ console.info = hold;
1227
+ process10.stdout.write = (text) => {
1228
+ held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1229
+ return true;
1230
+ };
1231
+ try {
1232
+ code = await step();
1233
+ } finally {
1234
+ console.log = log;
1235
+ console.info = info;
1236
+ process10.stdout.write = write;
1237
+ }
1238
+ stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1239
+ await sleep(interval);
1240
+ }
1241
+ return code;
1242
+ }
1243
+ // src/pid.ts
1244
+ import process12 from "process";
1161
1245
 
1162
1246
  // src/mask.ts
1163
1247
  import { basename } from "path";
@@ -1548,7 +1632,7 @@ function limitLine(limits, name) {
1548
1632
  return limit === undefined ? "-" : `soft ${limit.soft}, hard ${limit.hard}`;
1549
1633
  }
1550
1634
  function render(info, showEnv) {
1551
- const colors = paint(process10.stdout);
1635
+ const colors = paint(process12.stdout);
1552
1636
  const memory = info.memory;
1553
1637
  const size = (bytes) => bytes === undefined ? "-" : $e(bytes);
1554
1638
  const rows = [
@@ -1600,4 +1684,4 @@ async function pid(args) {
1600
1684
  }
1601
1685
 
1602
1686
  // src/pid-cli.ts
1603
- process11.exitCode = await runMain({ name: "pid", run: pid });
1687
+ process13.exitCode = await runMain({ name: "pid", run: pid });