@kaynooo/cli-wait 0.5.1 → 0.6.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/cli.js CHANGED
@@ -1,19 +1,18 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env -S bun --no-env-file
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
5
  import { existsSync as existsSync3 } from "fs";
6
- import process13 from "process";
7
-
6
+ import process14 from "process";
8
7
  // ../kit/src/args.ts
9
- import process4 from "process";
8
+ import process5 from "process";
10
9
  import { parseArgs } from "util";
11
10
 
12
11
  // ../kit/src/format.ts
13
- import process2 from "process";
12
+ import process3 from "process";
14
13
 
15
14
  // ../kit/src/style.ts
16
- import process from "process";
15
+ import process2 from "process";
17
16
 
18
17
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
19
18
  function x(s) {
@@ -277,10 +276,10 @@ function le(i = {}) {
277
276
  var t = le();
278
277
 
279
278
  // ../kit/src/style.ts
280
- function takesControlCodes(stream, env = process.env) {
279
+ function takesControlCodes(stream, env = process2.env) {
281
280
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
282
281
  }
283
- function paint(stream, env = process.env) {
282
+ function paint(stream, env = process2.env) {
284
283
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
285
284
  }
286
285
  var STATUSES = {
@@ -340,7 +339,7 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
340
339
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
341
340
  }
342
341
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
343
- const colors = paint(process2.stdout);
342
+ const colors = paint(process3.stdout);
344
343
  const lines = shown.map((row) => row.map((cell, index) => {
345
344
  const width = widths[index] ?? 0;
346
345
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -372,24 +371,30 @@ function printJson(value) {
372
371
  }
373
372
 
374
373
  // ../kit/src/help.ts
375
- import process3 from "process";
374
+ import process4 from "process";
376
375
  var OPTIONAL = /\[[^\]]+\]/g;
377
376
  var USAGE_PREFIX = /^usage:\s*/i;
378
377
  var FULL_STOP = /\.$/;
379
- function usageLine(usage, colors = paint(process3.stdout)) {
378
+ function usageLine(usage, colors = paint(process4.stdout)) {
380
379
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
381
380
  }
382
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
383
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
381
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
382
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
384
383
  `);
385
384
  }
386
- function replacesRows(replaces, colors = paint(process3.stdout)) {
385
+ function exitRows(exits, colors = paint(process4.stdout)) {
386
+ if (exits.length === 0)
387
+ return [];
388
+ const width = Math.max(...exits.map(([code]) => String(code).length));
389
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
390
+ }
391
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
387
392
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
388
393
  }
389
- function wantsHelpJson(env = process3.env) {
394
+ function wantsHelpJson(env = process4.env) {
390
395
  return env.KIT_HELP === "json";
391
396
  }
392
- function description(usage, { examples = [], replaces } = {}) {
397
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
393
398
  const lines = usage.replace(USAGE_PREFIX, "").split(`
394
399
  `);
395
400
  const first = lines[0];
@@ -400,15 +405,17 @@ function description(usage, { examples = [], replaces } = {}) {
400
405
  synopsis: colon === -1 ? first : first.slice(0, colon),
401
406
  summary: colon === -1 ? fallback : first.slice(colon + 2),
402
407
  ...replaces === undefined ? {} : { replaces },
403
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
408
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
409
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
410
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
404
411
  };
405
412
  }
406
- function exampleRows(examples, colors = paint(process3.stdout)) {
413
+ function exampleRows(examples, colors = paint(process4.stdout)) {
407
414
  if (examples.length === 0)
408
415
  return [];
409
416
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
410
417
  }
411
- function optionRows(options, colors = paint(process3.stdout)) {
418
+ function optionRows(options, colors = paint(process4.stdout)) {
412
419
  const rows = Object.entries(options).map(([name, option]) => {
413
420
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
414
421
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -510,7 +517,7 @@ var OUTPUT_OPTIONS = {
510
517
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
511
518
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
512
519
  };
513
- function applyOutput(color, plain, env = process4.env) {
520
+ function applyOutput(color, plain, env = process5.env) {
514
521
  const when = plain === true ? "never" : color ?? "auto";
515
522
  if (when === "auto")
516
523
  return;
@@ -533,7 +540,7 @@ function parse(args, usage, options, settings = {}) {
533
540
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
534
541
  let parsed;
535
542
  try {
536
- parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
543
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
537
544
  } catch (error) {
538
545
  const message = parseError(error);
539
546
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -541,7 +548,7 @@ function parse(args, usage, options, settings = {}) {
541
548
  const values = parsed.values;
542
549
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
543
550
  if (values.help === true) {
544
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
551
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
545
552
  throw new HelpShown;
546
553
  }
547
554
  checkChoices(parsed.values, all);
@@ -583,6 +590,18 @@ function listed(options, allowNegative) {
583
590
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
584
591
  }));
585
592
  }
593
+ function withAliases(args, options) {
594
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
595
+ if (named.size === 0)
596
+ return args;
597
+ const separator = args.indexOf("--");
598
+ const own = separator === -1 ? args : args.slice(0, separator);
599
+ return [...own.map((arg) => {
600
+ const at = arg.indexOf("=");
601
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
602
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
603
+ }), ...separator === -1 ? [] : args.slice(separator)];
604
+ }
586
605
  function withBare(args, options) {
587
606
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
588
607
  if (bare.size === 0)
@@ -668,11 +687,12 @@ function nearestOption(message, options, allowNegative) {
668
687
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
669
688
  }
670
689
  // ../kit/src/progress.ts
671
- import process6 from "process";
690
+ import process7 from "process";
672
691
 
673
692
  // ../kit/src/process.ts
674
693
  import { constants } from "os";
675
- import process5 from "process";
694
+ import process6 from "process";
695
+ var KILL_GRACE_MS = 2000;
676
696
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
677
697
  function exitCodeOf(code, signal) {
678
698
  if (code !== null)
@@ -693,7 +713,7 @@ function holdSignals(cleanup) {
693
713
  },
694
714
  release: () => {
695
715
  for (const signal of SIGNALS)
696
- process5.off(signal, onSignal);
716
+ process6.off(signal, onSignal);
697
717
  }
698
718
  };
699
719
  function onSignal(signal) {
@@ -706,12 +726,90 @@ function holdSignals(cleanup) {
706
726
  return;
707
727
  held.release();
708
728
  cleanup(signal);
709
- process5.kill(process5.pid, signal);
729
+ process6.kill(process6.pid, signal);
710
730
  }
711
731
  for (const signal of SIGNALS)
712
- process5.on(signal, onSignal);
732
+ process6.on(signal, onSignal);
713
733
  return held;
714
734
  }
735
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
736
+ const chunks = [];
737
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
738
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
739
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
740
+ const timers = [];
741
+ const killGroup = (killing) => {
742
+ if (state.done)
743
+ return;
744
+ try {
745
+ if (grouped)
746
+ process6.kill(-proc.pid, killing);
747
+ else
748
+ proc.kill(killing);
749
+ } catch {}
750
+ };
751
+ const stop = () => {
752
+ killGroup("SIGTERM");
753
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
754
+ };
755
+ const onAbort = () => stop();
756
+ if (timeoutMs !== undefined) {
757
+ timers.push(setTimeout(() => {
758
+ state.timedOut = true;
759
+ stop();
760
+ }, timeoutMs));
761
+ }
762
+ if (signal?.aborted === true)
763
+ onAbort();
764
+ else
765
+ signal?.addEventListener("abort", onAbort, { once: true });
766
+ onStart?.({ kill: (killing) => killGroup(killing) });
767
+ const drain = async (stream, name) => {
768
+ for await (const data of stream) {
769
+ if (state.failure !== undefined)
770
+ continue;
771
+ try {
772
+ onChunk?.({ stream: name, data });
773
+ } catch (error) {
774
+ state.failure = error;
775
+ stop();
776
+ continue;
777
+ }
778
+ if (state.kept + data.length > maxBytes) {
779
+ state.truncated = true;
780
+ continue;
781
+ }
782
+ state.kept += data.length;
783
+ chunks.push({ stream: name, data });
784
+ }
785
+ };
786
+ try {
787
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
788
+ await proc.exited;
789
+ } finally {
790
+ state.done = true;
791
+ for (const timer of timers)
792
+ clearTimeout(timer);
793
+ signal?.removeEventListener("abort", onAbort);
794
+ }
795
+ if (state.failure !== undefined)
796
+ throw state.failure;
797
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
798
+ let output;
799
+ let text;
800
+ return {
801
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
802
+ chunks,
803
+ timedOut: state.timedOut,
804
+ truncated: state.truncated,
805
+ get output() {
806
+ return output ??= joined();
807
+ },
808
+ get text() {
809
+ return text ??= (output ??= joined()).toString();
810
+ }
811
+ };
812
+ }
715
813
 
716
814
  // ../kit/src/progress.ts
717
815
  var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
@@ -724,7 +822,7 @@ var RESET_STYLE = `${ESC}[0m`;
724
822
  var CTRL_C = 3;
725
823
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
726
824
  var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
727
- function liveRegion(render, stream = process6.stderr, env = process6.env) {
825
+ function liveRegion(render, stream = process7.stderr, env = process7.env) {
728
826
  if (!takesControlCodes(stream, env))
729
827
  return { redraw: () => {
730
828
  return;
@@ -765,11 +863,11 @@ function liveRegion(render, stream = process6.stderr, env = process6.env) {
765
863
  clear();
766
864
  restore();
767
865
  release();
768
- process6.off("exit", onExit);
866
+ process7.off("exit", onExit);
769
867
  signals.release();
770
868
  }
771
869
  timer.unref();
772
- process6.on("exit", onExit);
870
+ process7.on("exit", onExit);
773
871
  return {
774
872
  redraw: draw,
775
873
  print: (text) => {
@@ -808,14 +906,14 @@ function cutToWidth(line, width) {
808
906
  return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
809
907
  }
810
908
  function swallowInput() {
811
- const input = process6.stdin;
909
+ const input = process7.stdin;
812
910
  if (!input.isTTY)
813
911
  return () => {
814
912
  return;
815
913
  };
816
914
  const onData = (data) => {
817
915
  if (data.includes(CTRL_C))
818
- process6.kill(process6.pid, "SIGINT");
916
+ process7.kill(process7.pid, "SIGINT");
819
917
  };
820
918
  input.setRawMode(true);
821
919
  input.on("data", onData);
@@ -831,7 +929,7 @@ function swallowInput() {
831
929
  };
832
930
  }
833
931
  function interceptOutput(clear) {
834
- const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process6.stdout, "write"], [process6.stderr, "write"]];
932
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process7.stdout, "write"], [process7.stderr, "write"]];
835
933
  const wrapped = targets.map(([target, name]) => {
836
934
  const original = Reflect.get(target, name);
837
935
  const wrapper = (...args) => {
@@ -849,31 +947,33 @@ function interceptOutput(clear) {
849
947
  };
850
948
  }
851
949
  // ../kit/src/cli.ts
852
- import process9 from "process";
950
+ import { readFileSync, realpathSync } from "fs";
951
+ import { dirname as dirname2, join as join3 } from "path";
952
+ import process10 from "process";
853
953
 
854
954
  // ../kit/src/usage.ts
855
955
  import { appendFileSync, mkdirSync } from "fs";
856
956
  import { homedir as homedir2 } from "os";
857
957
  import { dirname, isAbsolute, join as join2 } from "path";
858
- import process8 from "process";
958
+ import process9 from "process";
859
959
 
860
960
  // ../kit/src/logs.ts
861
961
  import { lstatSync, openSync } from "fs";
862
962
  import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
863
963
  import { homedir, tmpdir } from "os";
864
964
  import { join } from "path";
865
- import process7 from "process";
965
+ import process8 from "process";
866
966
  var DAY_MS = 24 * 60 * 60 * 1000;
867
967
  var CLI_FOLDER = "kaynooo-cli";
868
968
  function isPrivateDirectory(path) {
869
969
  try {
870
970
  const info = lstatSync(path, { throwIfNoEntry: false });
871
- return info !== undefined && info.isDirectory() && info.uid === (process7.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
971
+ return info !== undefined && info.isDirectory() && info.uid === (process8.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
872
972
  } catch {
873
973
  return false;
874
974
  }
875
975
  }
876
- async function privateLogDirectory(name, env = process7.env) {
976
+ async function privateLogDirectory(name, env = process8.env) {
877
977
  const runtime = env.XDG_RUNTIME_DIR;
878
978
  const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
879
979
  const path = join(base, name);
@@ -893,14 +993,14 @@ var usageError;
893
993
  function noteUsageError(message) {
894
994
  usageError = message;
895
995
  }
896
- function stateHome(env = process8.env) {
996
+ function stateHome(env = process9.env) {
897
997
  const dir = env.XDG_STATE_HOME;
898
998
  return dir !== undefined && isAbsolute(dir) ? dir : join2(homedir2(), ".local", "state");
899
999
  }
900
- function usagePath(env = process8.env) {
1000
+ function usagePath(env = process9.env) {
901
1001
  return join2(stateHome(env), CLI_FOLDER, "usage.jsonl");
902
1002
  }
903
- function usageRecorded(env = process8.env) {
1003
+ function usageRecorded(env = process9.env) {
904
1004
  const off = env.KAYNOOO_CLI_NO_USAGE;
905
1005
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
906
1006
  }
@@ -914,7 +1014,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
914
1014
  usageError = undefined;
915
1015
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
916
1016
  }
917
- function recordUsage(entry, env = process8.env) {
1017
+ function recordUsage(entry, env = process9.env) {
918
1018
  if (!usageRecorded(env))
919
1019
  return;
920
1020
  try {
@@ -932,8 +1032,8 @@ var LEVEL_OPTIONS = {
932
1032
  };
933
1033
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
934
1034
  function printError(prefix, message, hint, cause) {
935
- const colors = paint(process9.stderr);
936
- const styled = takesControlCodes(process9.stderr);
1035
+ const colors = paint(process10.stderr);
1036
+ const styled = takesControlCodes(process10.stderr);
937
1037
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
938
1038
  const under = (label, text, tint) => text === undefined ? "" : `
939
1039
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1015,11 +1115,22 @@ async function printCandidates(found) {
1015
1115
  console.log(line);
1016
1116
  return 0;
1017
1117
  }
1018
- async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
1118
+ function packageVersion(entry = Bun.main) {
1119
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1120
+ try {
1121
+ const { version } = JSON.parse(readFileSync(join3(dir, "package.json"), "utf8"));
1122
+ if (typeof version === "string")
1123
+ return version;
1124
+ } catch {}
1125
+ if (dirname2(dir) === dir)
1126
+ return "0.0.0";
1127
+ }
1128
+ }
1129
+ async function runMain({ name, version, run, redact, usage }, argv = process10.argv.slice(2)) {
1019
1130
  if (argv[0] === COMPLETE)
1020
1131
  return printCandidates(leafCandidates(run, argv.slice(1)));
1021
1132
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1022
- console.log(version);
1133
+ console.log(version ?? packageVersion());
1023
1134
  return 0;
1024
1135
  }
1025
1136
  let code;
@@ -1028,26 +1139,29 @@ async function runMain({ name, version, run, redact, usage }, argv = process9.ar
1028
1139
  } catch (error) {
1029
1140
  code = reportThrown(name, error, redact, wantsJson(argv));
1030
1141
  }
1031
- if (usage !== false)
1032
- recordUsage(usageEntry(name, undefined, argv, code));
1142
+ if (usage !== false) {
1143
+ try {
1144
+ recordUsage(usageEntry(name, undefined, argv, code));
1145
+ } catch {}
1146
+ }
1033
1147
  return code;
1034
1148
  }
1035
1149
  // ../kit/src/secrets.ts
1036
1150
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1037
1151
  // ../kit/src/sessions.ts
1038
1152
  import { homedir as homedir3 } from "os";
1039
- import { join as join3 } from "path";
1040
- import process10 from "process";
1153
+ import { join as join4 } from "path";
1154
+ import process11 from "process";
1041
1155
  var {Glob } = globalThis.Bun;
1042
1156
  var SESSION_FILES = new Glob("*.json");
1043
1157
  var ACCOUNT_DIRS = new Glob("*/sessions");
1044
1158
  async function sessionDirs() {
1045
1159
  const home = homedir3();
1046
- const dirs = new Set([join3(home, ".claude", "sessions")]);
1047
- if (process10.env.CLAUDE_CONFIG_DIR !== undefined)
1048
- dirs.add(join3(process10.env.CLAUDE_CONFIG_DIR, "sessions"));
1160
+ const dirs = new Set([join4(home, ".claude", "sessions")]);
1161
+ if (process11.env.CLAUDE_CONFIG_DIR !== undefined)
1162
+ dirs.add(join4(process11.env.CLAUDE_CONFIG_DIR, "sessions"));
1049
1163
  try {
1050
- for await (const dir of ACCOUNT_DIRS.scan({ cwd: join3(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
1164
+ for await (const dir of ACCOUNT_DIRS.scan({ cwd: join4(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
1051
1165
  dirs.add(dir);
1052
1166
  } catch {}
1053
1167
  return [...dirs];
@@ -1091,7 +1205,7 @@ async function liveSessions() {
1091
1205
  }
1092
1206
  async function currentSession(sessions) {
1093
1207
  const byPid = new Map(sessions.map((session) => [session.pid, session]));
1094
- let pid = process10.ppid;
1208
+ let pid = process11.ppid;
1095
1209
  for (let depth = 0;depth < 32 && pid > 1; depth++) {
1096
1210
  const session = byPid.get(pid);
1097
1211
  if (session !== undefined)
@@ -1103,9 +1217,6 @@ async function currentSession(sessions) {
1103
1217
  }
1104
1218
  return;
1105
1219
  }
1106
- // package.json
1107
- var version = "0.5.1";
1108
-
1109
1220
  // src/conditions.ts
1110
1221
  import { existsSync, statSync } from "fs";
1111
1222
  var TAIL = 20;
@@ -1231,9 +1342,9 @@ async function urlCheck(url, timeout) {
1231
1342
  }
1232
1343
 
1233
1344
  // src/task.ts
1234
- import { existsSync as existsSync2, lstatSync as lstatSync2, readFileSync, statSync as statSync2 } from "fs";
1235
- import { join as join4 } from "path";
1236
- import process12 from "process";
1345
+ import { existsSync as existsSync2, lstatSync as lstatSync2, readFileSync as readFileSync2, statSync as statSync2 } from "fs";
1346
+ import { join as join5 } from "path";
1347
+ import process13 from "process";
1237
1348
  var EXITED = /(?:^|\n)\[exited with code (-?\d+)\]\n*$/;
1238
1349
  var FAILURE = /\(fail\)|\berror:/i;
1239
1350
  var TASK_ID = /^[\w-]+$/;
@@ -1241,16 +1352,16 @@ var TAIL_BYTES = 256;
1241
1352
  var LONGEST_FAILURES = 30;
1242
1353
  var CARRIAGE_RETURN2 = /\r$/;
1243
1354
  function tasksRoot(env) {
1244
- return join4(env.CLAUDE_CODE_TMPDIR ?? env.TMPDIR ?? "/tmp", `claude-${process12.getuid?.() ?? 0}`);
1355
+ return join5(env.CLAUDE_CODE_TMPDIR ?? env.TMPDIR ?? "/tmp", `claude-${process13.getuid?.() ?? 0}`);
1245
1356
  }
1246
- function taskFile(task, env = process12.env) {
1357
+ function taskFile(task, env = process13.env) {
1247
1358
  if (task.includes("/") || task.endsWith(".output"))
1248
1359
  return task;
1249
1360
  if (!TASK_ID.test(task))
1250
1361
  return;
1251
1362
  const root = tasksRoot(env);
1252
1363
  const found = existsSync2(root) ? [...new Bun.Glob(`*/*/tasks/${task}.output`).scanSync({ cwd: root, onlyFiles: false })] : [];
1253
- return found.length === 0 ? undefined : join4(root, found[0] ?? "");
1364
+ return found.length === 0 ? undefined : join5(root, found[0] ?? "");
1254
1365
  }
1255
1366
  function isTranscript(path) {
1256
1367
  return existsSync2(path) && lstatSync2(path).isSymbolicLink() && path.endsWith(".output");
@@ -1276,7 +1387,7 @@ async function taskEnd(path, lines) {
1276
1387
  }
1277
1388
  function pidAlive(pid) {
1278
1389
  try {
1279
- process12.kill(pid, 0);
1390
+ process13.kill(pid, 0);
1280
1391
  } catch (error) {
1281
1392
  return error.code === "EPERM";
1282
1393
  }
@@ -1284,7 +1395,7 @@ function pidAlive(pid) {
1284
1395
  }
1285
1396
  function isZombie(pid) {
1286
1397
  try {
1287
- const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
1398
+ const stat = readFileSync2(`/proc/${pid}/stat`, "utf8");
1288
1399
  return stat.slice(stat.lastIndexOf(")") + 2, stat.lastIndexOf(")") + 3) === "Z";
1289
1400
  } catch {
1290
1401
  return false;
@@ -1292,21 +1403,23 @@ function isZombie(pid) {
1292
1403
  }
1293
1404
 
1294
1405
  // src/cli.ts
1295
- var USAGE = `waitfor [options]: waits until a file shows a line, a port listens, a URL answers 2xx or a process exits
1406
+ var USAGE = `waitfor [options]: waits until a file shows a line, a port listens, a URL answers 2xx, a process exits or a command exits 0
1296
1407
  waitfor task <task id | file>: waits for a Claude Code background task to end (waitfor task --help)
1297
1408
 
1298
- Every condition given must be met. A --fail line in --file ends the wait at once.
1299
- Exits 0 once met, 1 on a --fail line, 2 on a timeout or a usage error, each with an excerpt of what it saw last.`;
1409
+ Every condition given must be met, or with --any the first of them to be. A --fail line in --file ends the wait at once. A timeout or a --fail line comes with an excerpt of what it saw last.
1410
+ --json prints {met, ms, line} once met or on a --fail line, line being the last --until line or the --fail one as {number, text} (null when none), and the progress lines go to stderr.`;
1300
1411
  var TASK_USAGE = `waitfor task [options] <task id | file>: waits for a Claude Code background task to end, then prints its exit code, its last lines and the (fail) and error: lines above them
1301
1412
 
1302
1413
  The task is the id a background Bash call returned, or the path of its .output file.
1303
- Exits 0 when the task exited 0, 1 when it exited with another code, 2 on a timeout or a usage error.
1304
1414
  --json prints {task, path, code, ms, failures, tail}, each line as {number, text}.`;
1415
+ var EXITS = [[0, "every condition was met"], [1, "a --fail line showed up"], [2, "it timed out or a usage error"]];
1416
+ var TASK_EXITS = [[0, "the task exited 0"], [1, "it exited with another code"], [2, "it timed out or a usage error"]];
1305
1417
  var TIMEOUT = { type: "string", short: "t", description: "how long before giving up (5m): 30s, 5m, 1h, a bare number in seconds" };
1306
1418
  var TASK_OPTIONS = {
1307
1419
  lines: { type: "string", short: "n", description: "how many of its last lines to print (20)" },
1308
1420
  timeout: TIMEOUT,
1309
- json: jsonOption()
1421
+ json: jsonOption(),
1422
+ quiet: { type: "boolean", short: "q", description: "no live progress line" }
1310
1423
  };
1311
1424
  var OPTIONS = {
1312
1425
  file: { type: "string", short: "f", description: "a log file to read, from its start, waiting for it to exist" },
@@ -1316,11 +1429,18 @@ var OPTIONS = {
1316
1429
  host: { type: "string", short: "H", description: "the host of --port (127.0.0.1)" },
1317
1430
  url: { type: "string", description: "a URL that must answer 2xx" },
1318
1431
  pid: { type: "string", description: "a process id that must exit" },
1319
- timeout: TIMEOUT
1432
+ cmd: { type: "string", short: "c", description: "a shell command that must exit 0, re-run every --interval" },
1433
+ interval: { type: "string", description: "how long between two runs of --cmd (1s)" },
1434
+ any: { type: "boolean", description: "met by the first condition that is, not all of them (needs two)" },
1435
+ timeout: TIMEOUT,
1436
+ json: jsonOption("{met, ms, line}"),
1437
+ quiet: { type: "boolean", short: "q", description: "no live progress line: only what was met and the failure" }
1320
1438
  };
1321
1439
  var POLL = 250;
1322
1440
  var URL_TIMEOUT = 5000;
1323
1441
  var WIDTH = 400;
1442
+ var CMD_RUN_LIMIT = 30000;
1443
+ var LAST_LINE = /[^\n]+(?=\n*$)/;
1324
1444
  function regex(source, name) {
1325
1445
  if (source === undefined)
1326
1446
  return;
@@ -1335,8 +1455,19 @@ function numbered(lines, marked) {
1335
1455
  return lines.map((line) => `${line === marked ? ">" : " "} ${String(line.number).padStart(width)} ${truncate(line.text, WIDTH)}`).join(`
1336
1456
  `);
1337
1457
  }
1458
+ async function cmdProblem(command, timeoutMs) {
1459
+ try {
1460
+ const ran = await runCommand(["sh", "-c", command], { timeoutMs });
1461
+ if (ran.code === 0 && !ran.timedOut)
1462
+ return;
1463
+ const last = LAST_LINE.exec(ran.text)?.[0];
1464
+ return `${ran.timedOut ? "timed out" : `exited ${ran.code}`}${last === undefined ? "" : ` (${truncate(last, WIDTH)})`}`;
1465
+ } catch (error) {
1466
+ return `could not run: ${error instanceof Error ? error.message : String(error)}`;
1467
+ }
1468
+ }
1338
1469
  async function waitTask(args) {
1339
- const { values, positionals: [task] } = parse(args, TASK_USAGE, TASK_OPTIONS, { positionals: ["<task>"] });
1470
+ const { values, positionals: [task] } = parse(args, TASK_USAGE, TASK_OPTIONS, { positionals: ["<task>"], exits: TASK_EXITS });
1340
1471
  const path = taskFile(task);
1341
1472
  if (path === undefined)
1342
1473
  fail(`no background task ${task}: give the id a background Bash call returned, or the path of its .output file`);
@@ -1347,8 +1478,8 @@ async function waitTask(args) {
1347
1478
  const lines = wholeNumber(values.lines, "lines", 20);
1348
1479
  const timeout = duration(values.timeout, "timeout", 5 * 60000);
1349
1480
  const started = Date.now();
1350
- const { dim } = paint(process13.stderr);
1351
- const region = liveRegion((spinner) => [`${spinner} task ${task}: still running ${dim(formatElapsed(Date.now() - started))}`]);
1481
+ const { dim } = paint(process14.stderr);
1482
+ const region = values.quiet === true ? undefined : liveRegion((spinner) => [`${spinner} task ${task}: still running ${dim(formatElapsed(Date.now() - started))}`]);
1352
1483
  let code;
1353
1484
  try {
1354
1485
  for (;; ) {
@@ -1358,7 +1489,7 @@ async function waitTask(args) {
1358
1489
  await Bun.sleep(POLL);
1359
1490
  }
1360
1491
  } finally {
1361
- region.stop();
1492
+ region?.stop();
1362
1493
  }
1363
1494
  const { failures, tail } = await taskEnd(path, lines);
1364
1495
  const last = tail.length === 0 ? "" : `
@@ -1379,20 +1510,25 @@ ${numbered(failures)}`;
1379
1510
  async function main(args) {
1380
1511
  if (args[0] === "task")
1381
1512
  return waitTask(args.slice(1));
1382
- const parsed = parse(args, USAGE, OPTIONS, { replaces: "sleep loops, tail -f and until ! pgrep -f", examples: [['waitfor --file dev.log --until "ready in" --fail error', "a dev server up, or its first error"], ["waitfor --port 5432 -t 2m", "Postgres accepting connections"]] });
1513
+ const parsed = parse(args, USAGE, OPTIONS, { exits: EXITS, replaces: "sleep loops, tail -f and until ! pgrep -f", examples: [['waitfor --file dev.log --until "ready in" --fail error', "a dev server up, or its first error"], ["waitfor --port 5432 -t 2m", "Postgres accepting connections"]] });
1383
1514
  const { values, positionals } = parsed;
1384
1515
  if (positionals.length > 0)
1385
1516
  fail(`unexpected argument ${positionals[0]}
1386
1517
 
1387
1518
  ${USAGE}`);
1388
- if (values.until === undefined && values.port === undefined && values.url === undefined && values.pid === undefined)
1389
- fail(`give --until with --file, --port, --url or --pid
1519
+ if (values.until === undefined && values.port === undefined && values.url === undefined && values.pid === undefined && values.cmd === undefined)
1520
+ fail(`give --until with --file, --port, --url, --pid or --cmd
1390
1521
 
1391
1522
  ${USAGE}`);
1392
1523
  if ((values.until !== undefined || values.fail !== undefined) !== (values.file !== undefined))
1393
1524
  fail("--until and --fail read the --file lines, and --file needs one of them");
1394
1525
  if (values.host !== undefined && values.port === undefined)
1395
1526
  fail("--host goes with --port");
1527
+ const conditions = [values.until, values.port, values.url, values.pid, values.cmd].filter((condition) => condition !== undefined).length;
1528
+ if (values.any === true && conditions < 2)
1529
+ fail("--any needs two or more of --until, --port, --url, --pid and --cmd");
1530
+ if (values.interval !== undefined && values.cmd === undefined)
1531
+ fail("--interval goes with --cmd");
1396
1532
  const port = values.port === undefined ? undefined : wholeNumber(values.port, "port", 0);
1397
1533
  if (port !== undefined && port > 65535)
1398
1534
  fail(`--port takes a port up to 65535, not ${port}`);
@@ -1400,20 +1536,28 @@ ${USAGE}`);
1400
1536
  fail(`--url ${values.url} is no URL`);
1401
1537
  const pid = values.pid === undefined ? undefined : wholeNumber(values.pid, "pid", 0);
1402
1538
  const host = values.host ?? "127.0.0.1";
1539
+ const interval = duration(values.interval, "interval", 1000);
1540
+ const isAny = values.any === true;
1403
1541
  const timeout = duration(values.timeout, "timeout", 5 * 60000);
1404
1542
  const watch = values.file === undefined ? undefined : new FileWatch(values.file, regex(values.until, "until"), regex(values.fail, "fail"));
1405
1543
  const started = Date.now();
1544
+ const json = values.json === true;
1545
+ const say = json ? console.error : console.log;
1546
+ let matched;
1406
1547
  let portLeft = port === undefined ? undefined : "not checked yet";
1407
1548
  let urlLeft = values.url === undefined ? undefined : "not checked yet";
1408
1549
  let isPidLeft = pid !== undefined;
1409
- const { dim } = paint(process13.stderr);
1410
- const region = liveRegion((spinner) => {
1550
+ let cmdLeft = values.cmd === undefined ? undefined : "not run yet";
1551
+ let cmdRanAt = 0;
1552
+ const { dim } = paint(process14.stderr);
1553
+ const region = values.quiet === true ? undefined : liveRegion((spinner) => {
1411
1554
  const waited = dim(formatElapsed(Date.now() - started));
1412
1555
  const left = [
1413
1556
  watch === undefined || watch.done ? undefined : `${watch.path}: ${watch.exists ? "no --until line yet" : "does not exist yet"}`,
1414
1557
  portLeft === undefined ? undefined : `${host}:${port}: ${portLeft}`,
1415
1558
  urlLeft === undefined ? undefined : `${values.url}: ${urlLeft}`,
1416
- isPidLeft ? `pid ${pid}: still running` : undefined
1559
+ isPidLeft ? `pid ${pid}: still running` : undefined,
1560
+ cmdLeft === undefined ? undefined : `\`${values.cmd}\`: ${cmdLeft}`
1417
1561
  ];
1418
1562
  return left.filter((line) => line !== undefined).map((line) => `${spinner} ${line} ${waited}`);
1419
1563
  });
@@ -1422,18 +1566,21 @@ ${USAGE}`);
1422
1566
  if (watch !== undefined) {
1423
1567
  for (const event of await watch.poll()) {
1424
1568
  if (event.kind === "until") {
1425
- console.log(`${watch.path}:${event.line.number}: ${truncate(event.line.text, WIDTH)}`);
1569
+ say(`${watch.path}:${event.line.number}: ${truncate(event.line.text, WIDTH)}`);
1570
+ matched = { number: event.line.number, text: event.line.text };
1426
1571
  continue;
1427
1572
  }
1428
1573
  console.error(`waitfor: ${watch.path}:${event.line.number} matched --fail after ${formatDuration(Date.now() - started)}
1429
1574
  ${numbered(event.excerpt, event.line)}`);
1575
+ if (json)
1576
+ printJson({ met: false, ms: Date.now() - started, line: { number: event.line.number, text: event.line.text } });
1430
1577
  return 1;
1431
1578
  }
1432
1579
  }
1433
1580
  if (port !== undefined && portLeft !== undefined) {
1434
1581
  portLeft = await portProblem(host, port);
1435
1582
  if (portLeft === undefined)
1436
- console.log(`${host}:${port} listening after ${formatDuration(Date.now() - started)}`);
1583
+ say(`${host}:${port} listening after ${formatDuration(Date.now() - started)}`);
1437
1584
  }
1438
1585
  if (values.url !== undefined && urlLeft !== undefined) {
1439
1586
  const budget = Math.max(1, Math.min(URL_TIMEOUT, started + timeout - Date.now()));
@@ -1442,21 +1589,40 @@ ${numbered(event.excerpt, event.line)}`);
1442
1589
  if (!isCutShort)
1443
1590
  urlLeft = "problem" in check ? check.problem : undefined;
1444
1591
  if ("status" in check)
1445
- console.log(`${values.url} answered ${check.status} after ${formatDuration(Date.now() - started)}`);
1592
+ say(`${values.url} answered ${check.status} after ${formatDuration(Date.now() - started)}`);
1446
1593
  }
1447
1594
  if (pid !== undefined && isPidLeft) {
1448
1595
  isPidLeft = pidAlive(pid);
1449
1596
  if (!isPidLeft)
1450
- console.log(`pid ${pid} exited after ${formatDuration(Date.now() - started)}`);
1597
+ say(`pid ${pid} exited after ${formatDuration(Date.now() - started)}`);
1451
1598
  }
1452
- if ((watch?.done ?? true) && portLeft === undefined && urlLeft === undefined && !isPidLeft)
1599
+ if (values.cmd !== undefined && cmdLeft !== undefined && Date.now() - cmdRanAt >= interval) {
1600
+ const budget = Math.max(1, Math.min(CMD_RUN_LIMIT, started + timeout - Date.now()));
1601
+ const problem = await cmdProblem(values.cmd, budget);
1602
+ if (!(problem?.startsWith("timed out") === true && budget < CMD_RUN_LIMIT && cmdLeft !== "not run yet"))
1603
+ cmdLeft = problem;
1604
+ cmdRanAt = Date.now();
1605
+ if (cmdLeft === undefined)
1606
+ say(`\`${values.cmd}\` exited 0 after ${formatDuration(Date.now() - started)}`);
1607
+ }
1608
+ const isMet = [
1609
+ values.until !== undefined && (watch?.done ?? false),
1610
+ port !== undefined && portLeft === undefined,
1611
+ values.url !== undefined && urlLeft === undefined,
1612
+ pid !== undefined && !isPidLeft,
1613
+ values.cmd !== undefined && cmdLeft === undefined
1614
+ ];
1615
+ if (isAny ? isMet.includes(true) : (watch?.done ?? true) && portLeft === undefined && urlLeft === undefined && !isPidLeft && cmdLeft === undefined) {
1616
+ if (json)
1617
+ printJson({ met: true, ms: Date.now() - started, line: matched ?? null });
1453
1618
  return 0;
1619
+ }
1454
1620
  if (Date.now() - started >= timeout && !(watch?.failing ?? false))
1455
1621
  break;
1456
1622
  await Bun.sleep(POLL);
1457
1623
  }
1458
1624
  } finally {
1459
- region.stop();
1625
+ region?.stop();
1460
1626
  }
1461
1627
  const missing = [];
1462
1628
  if (watch !== undefined && !watch.done)
@@ -1467,9 +1633,11 @@ ${numbered(event.excerpt, event.line)}`);
1467
1633
  missing.push(`${values.url} ${urlLeft}`);
1468
1634
  if (isPidLeft)
1469
1635
  missing.push(`pid ${pid} is still running`);
1636
+ if (cmdLeft !== undefined)
1637
+ missing.push(`\`${values.cmd}\` ${cmdLeft}`);
1470
1638
  const lines = watch?.excerpt() ?? [];
1471
- fail(`gave up after ${formatDuration(timeout)}: ${missing.join(", ")}${lines.length === 0 ? "" : `
1639
+ fail(`gave up after ${formatDuration(timeout)}${isAny ? ", none met" : ""}: ${missing.join(", ")}${lines.length === 0 ? "" : `
1472
1640
  last lines of ${watch?.path}:
1473
1641
  ${numbered(lines)}`}`);
1474
1642
  }
1475
- process13.exitCode = await runMain({ name: "waitfor", version, run: main });
1643
+ process14.exitCode = await runMain({ name: "waitfor", run: main });