@kaynooo/cli-wait 0.5.0 → 0.6.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/cli.js CHANGED
@@ -3,19 +3,18 @@
3
3
 
4
4
  // src/cli.ts
5
5
  import { existsSync as existsSync3 } from "fs";
6
- import process11 from "process";
7
-
6
+ import process14 from "process";
8
7
  // ../kit/src/args.ts
9
- import process3 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
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
17
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
19
18
  function x(s) {
20
19
  let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
21
20
  if (!/^[a-f0-9]+$/.test(r))
@@ -235,7 +234,7 @@ class e {
235
234
  }
236
235
  }
237
236
 
238
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
237
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
239
238
  var r = 39;
240
239
  var o = 49;
241
240
  var f2 = "\x1B[";
@@ -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)));
@@ -371,6 +370,63 @@ function printJson(value) {
371
370
  console.log(JSON.stringify(value, undefined, 2));
372
371
  }
373
372
 
373
+ // ../kit/src/help.ts
374
+ import process4 from "process";
375
+ var OPTIONAL = /\[[^\]]+\]/g;
376
+ var USAGE_PREFIX = /^usage:\s*/i;
377
+ var FULL_STOP = /\.$/;
378
+ function usageLine(usage, colors = paint(process4.stdout)) {
379
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
380
+ }
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(`
383
+ `);
384
+ }
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)) {
392
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
393
+ }
394
+ function wantsHelpJson(env = process4.env) {
395
+ return env.KIT_HELP === "json";
396
+ }
397
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
398
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
399
+ `);
400
+ const first = lines[0];
401
+ const colon = first.indexOf(": ");
402
+ const prose = lines[lines.indexOf("") + 1] ?? "";
403
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
404
+ return {
405
+ synopsis: colon === -1 ? first : first.slice(0, colon),
406
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
407
+ ...replaces === undefined ? {} : { replaces },
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 } })) }
411
+ };
412
+ }
413
+ function exampleRows(examples, colors = paint(process4.stdout)) {
414
+ if (examples.length === 0)
415
+ return [];
416
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
417
+ }
418
+ function optionRows(options, colors = paint(process4.stdout)) {
419
+ const rows = Object.entries(options).map(([name, option]) => {
420
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
421
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
422
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
423
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
424
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
425
+ });
426
+ const width = Math.max(0, ...rows.map((row) => row.width));
427
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
428
+ }
429
+
374
430
  // ../kit/src/text.ts
375
431
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
376
432
  function distance(a, b) {
@@ -390,8 +446,30 @@ function closest(name, names) {
390
446
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
391
447
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
392
448
  }
449
+ // ../kit/src/input.ts
450
+ var WHOLE = /^\d+$/;
451
+ function wholeNumber(value, name, fallback, min = 1) {
452
+ if (value === undefined)
453
+ return fallback;
454
+ const number = Number(value);
455
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
456
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
457
+ return number;
458
+ }
459
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
460
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
461
+ function duration(value, name, fallback, unit = "s") {
462
+ if (value === undefined)
463
+ return fallback;
464
+ const match = DURATION.exec(value.trim());
465
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
466
+ if (ms < 1)
467
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
468
+ return ms;
469
+ }
393
470
 
394
471
  // ../kit/src/args.ts
472
+ var DASHES = /^-+/;
395
473
  function jsonOption(holds) {
396
474
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
397
475
  }
@@ -426,61 +504,20 @@ class HelpShown extends Exit {
426
504
 
427
505
  class Completing {
428
506
  options;
429
- constructor(options) {
507
+ positionals;
508
+ candidates;
509
+ constructor(options, positionals = [], candidates = {}) {
430
510
  this.options = options;
511
+ this.positionals = positionals;
512
+ this.candidates = candidates;
431
513
  }
432
514
  }
433
515
  var completion = { active: false };
434
- var OPTIONAL = /\[[^\]]+\]/g;
435
- var USAGE_PREFIX = /^usage:\s*/i;
436
- var FULL_STOP = /\.$/;
437
- var DASHES = /^-+/;
438
- function usageLine(usage, colors = paint(process3.stdout)) {
439
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
440
- }
441
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
442
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
443
- `);
444
- }
445
- function replacesRows(replaces, colors = paint(process3.stdout)) {
446
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
447
- }
448
- function wantsHelpJson(env = process3.env) {
449
- return env.KIT_HELP === "json";
450
- }
451
- function description(usage, { examples = [], replaces } = {}) {
452
- const lines = usage.replace(USAGE_PREFIX, "").split(`
453
- `);
454
- const first = lines[0];
455
- const colon = first.indexOf(": ");
456
- const prose = lines[lines.indexOf("") + 1] ?? "";
457
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
458
- return {
459
- synopsis: colon === -1 ? first : first.slice(0, colon),
460
- summary: colon === -1 ? fallback : first.slice(colon + 2),
461
- ...replaces === undefined ? {} : { replaces },
462
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
463
- };
464
- }
465
- function exampleRows(examples, colors = paint(process3.stdout)) {
466
- if (examples.length === 0)
467
- return [];
468
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
469
- }
470
- function optionRows(options, colors = paint(process3.stdout)) {
471
- const rows = Object.entries(options).map(([name, option]) => {
472
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
473
- const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
474
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
475
- });
476
- const width = Math.max(0, ...rows.map((row) => row.width));
477
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
478
- }
479
516
  var OUTPUT_OPTIONS = {
480
517
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
481
518
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
482
519
  };
483
- function applyOutput(color, plain, env = process3.env) {
520
+ function applyOutput(color, plain, env = process5.env) {
484
521
  const when = plain === true ? "never" : color ?? "auto";
485
522
  if (when === "auto")
486
523
  return;
@@ -497,14 +534,13 @@ function applyOutput(color, plain, env = process3.env) {
497
534
  function parse(args, usage, options, settings = {}) {
498
535
  const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
499
536
  const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
537
+ const listing = listed(all, settings.allowNegative === true);
500
538
  if (completion.active)
501
- throw new Completing(all);
502
- const separator = settings.rest === true ? args.indexOf("--") : -1;
503
- const own = separator === -1 ? args : args.slice(0, separator);
504
- const rest = separator === -1 ? undefined : args.slice(separator + 1);
539
+ throw new Completing(listing, settings.positionals, settings.candidates);
540
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
505
541
  let parsed;
506
542
  try {
507
- parsed = parseArgs({ args: joinDashValues(own, 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 });
508
544
  } catch (error) {
509
545
  const message = parseError(error);
510
546
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -512,12 +548,96 @@ function parse(args, usage, options, settings = {}) {
512
548
  const values = parsed.values;
513
549
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
514
550
  if (values.help === true) {
515
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
551
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
516
552
  throw new HelpShown;
517
553
  }
554
+ checkChoices(parsed.values, all);
555
+ checkConflicts(parsed.values, all);
518
556
  if (settings.positionals !== undefined)
519
557
  checkPositionals(parsed.positionals, settings.positionals);
520
- return { ...parsed, positionals: parsed.positionals, rest };
558
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
559
+ }
560
+ function splitRest(args, passes) {
561
+ const separator = passes ? args.indexOf("--") : -1;
562
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
563
+ }
564
+ function splitTrailing(args, options, count) {
565
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
566
+ let seen = 0;
567
+ if (count === 0)
568
+ return { own: args, rest: undefined };
569
+ for (let at = 0;at < args.length; at++) {
570
+ const word = args[at];
571
+ if (word === "--")
572
+ break;
573
+ if (word.startsWith("-")) {
574
+ if (takesValue(word))
575
+ at++;
576
+ continue;
577
+ }
578
+ seen++;
579
+ if (seen === count)
580
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
581
+ }
582
+ return { own: args, rest: undefined };
583
+ }
584
+ function listed(options, allowNegative) {
585
+ if (!allowNegative)
586
+ return options;
587
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
588
+ if (option.type !== "boolean" || option.negative === undefined)
589
+ return [[name, option]];
590
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
591
+ }));
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
+ }
605
+ function withBare(args, options) {
606
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
607
+ if (bare.size === 0)
608
+ return args;
609
+ const separator = args.indexOf("--");
610
+ const own = separator === -1 ? args : args.slice(0, separator);
611
+ return [...own.flatMap((arg, index) => {
612
+ const optional = bare.get(arg);
613
+ const next = own[index + 1];
614
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
615
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
616
+ }), ...separator === -1 ? [] : args.slice(separator)];
617
+ }
618
+ function checkConflicts(values, options) {
619
+ const given = (name) => values[name] !== undefined && values[name] !== false;
620
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
621
+ const other = given(name) ? conflicts.find(given) : undefined;
622
+ if (other !== undefined)
623
+ badUsage(`--${name} cannot be used with --${other}`);
624
+ }
625
+ }
626
+ function checkChoices(values, options) {
627
+ for (const [name, option] of Object.entries(options)) {
628
+ if (option.choices === undefined)
629
+ continue;
630
+ const given = values[name];
631
+ for (const value of Array.isArray(given) ? given : [given]) {
632
+ if (typeof value === "string")
633
+ oneOf(value, name, option.choices);
634
+ }
635
+ }
636
+ }
637
+ function oneOf(value, name, choices) {
638
+ if (!choices.includes(value))
639
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
640
+ return value;
521
641
  }
522
642
  function checkPositionals(given, names) {
523
643
  const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
@@ -566,32 +686,13 @@ function nearestOption(message, options, allowNegative) {
566
686
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
567
687
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
568
688
  }
569
- var WHOLE = /^\d+$/;
570
- function wholeNumber(value, name, fallback, min = 1) {
571
- if (value === undefined)
572
- return fallback;
573
- const number = Number(value);
574
- if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
575
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
576
- return number;
577
- }
578
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
579
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
580
- function duration(value, name, fallback, unit = "s") {
581
- if (value === undefined)
582
- return fallback;
583
- const match = DURATION.exec(value.trim());
584
- const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
585
- if (ms < 1)
586
- badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
587
- return ms;
588
- }
589
689
  // ../kit/src/progress.ts
590
- import process5 from "process";
690
+ import process7 from "process";
591
691
 
592
692
  // ../kit/src/process.ts
593
693
  import { constants } from "os";
594
- import process4 from "process";
694
+ import process6 from "process";
695
+ var KILL_GRACE_MS = 2000;
595
696
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
596
697
  function exitCodeOf(code, signal) {
597
698
  if (code !== null)
@@ -612,7 +713,7 @@ function holdSignals(cleanup) {
612
713
  },
613
714
  release: () => {
614
715
  for (const signal of SIGNALS)
615
- process4.off(signal, onSignal);
716
+ process6.off(signal, onSignal);
616
717
  }
617
718
  };
618
719
  function onSignal(signal) {
@@ -625,12 +726,90 @@ function holdSignals(cleanup) {
625
726
  return;
626
727
  held.release();
627
728
  cleanup(signal);
628
- process4.kill(process4.pid, signal);
729
+ process6.kill(process6.pid, signal);
629
730
  }
630
731
  for (const signal of SIGNALS)
631
- process4.on(signal, onSignal);
732
+ process6.on(signal, onSignal);
632
733
  return held;
633
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
+ }
634
813
 
635
814
  // ../kit/src/progress.ts
636
815
  var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
@@ -643,7 +822,7 @@ var RESET_STYLE = `${ESC}[0m`;
643
822
  var CTRL_C = 3;
644
823
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
645
824
  var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
646
- function liveRegion(render, stream = process5.stderr, env = process5.env) {
825
+ function liveRegion(render, stream = process7.stderr, env = process7.env) {
647
826
  if (!takesControlCodes(stream, env))
648
827
  return { redraw: () => {
649
828
  return;
@@ -684,11 +863,11 @@ function liveRegion(render, stream = process5.stderr, env = process5.env) {
684
863
  clear();
685
864
  restore();
686
865
  release();
687
- process5.off("exit", onExit);
866
+ process7.off("exit", onExit);
688
867
  signals.release();
689
868
  }
690
869
  timer.unref();
691
- process5.on("exit", onExit);
870
+ process7.on("exit", onExit);
692
871
  return {
693
872
  redraw: draw,
694
873
  print: (text) => {
@@ -727,14 +906,14 @@ function cutToWidth(line, width) {
727
906
  return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
728
907
  }
729
908
  function swallowInput() {
730
- const input = process5.stdin;
909
+ const input = process7.stdin;
731
910
  if (!input.isTTY)
732
911
  return () => {
733
912
  return;
734
913
  };
735
914
  const onData = (data) => {
736
915
  if (data.includes(CTRL_C))
737
- process5.kill(process5.pid, "SIGINT");
916
+ process7.kill(process7.pid, "SIGINT");
738
917
  };
739
918
  input.setRawMode(true);
740
919
  input.on("data", onData);
@@ -750,7 +929,7 @@ function swallowInput() {
750
929
  };
751
930
  }
752
931
  function interceptOutput(clear) {
753
- const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process5.stdout, "write"], [process5.stderr, "write"]];
932
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process7.stdout, "write"], [process7.stderr, "write"]];
754
933
  const wrapped = targets.map(([target, name]) => {
755
934
  const original = Reflect.get(target, name);
756
935
  const wrapper = (...args) => {
@@ -768,15 +947,93 @@ function interceptOutput(clear) {
768
947
  };
769
948
  }
770
949
  // ../kit/src/cli.ts
771
- import process6 from "process";
950
+ import { readFileSync, realpathSync } from "fs";
951
+ import { dirname as dirname2, join as join3 } from "path";
952
+ import process10 from "process";
953
+
954
+ // ../kit/src/usage.ts
955
+ import { appendFileSync, mkdirSync } from "fs";
956
+ import { homedir as homedir2 } from "os";
957
+ import { dirname, isAbsolute, join as join2 } from "path";
958
+ import process9 from "process";
959
+
960
+ // ../kit/src/logs.ts
961
+ import { lstatSync, openSync } from "fs";
962
+ import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
963
+ import { homedir, tmpdir } from "os";
964
+ import { join } from "path";
965
+ import process8 from "process";
966
+ var DAY_MS = 24 * 60 * 60 * 1000;
967
+ var CLI_FOLDER = "kaynooo-cli";
968
+ function isPrivateDirectory(path) {
969
+ try {
970
+ const info = lstatSync(path, { throwIfNoEntry: false });
971
+ return info !== undefined && info.isDirectory() && info.uid === (process8.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
972
+ } catch {
973
+ return false;
974
+ }
975
+ }
976
+ async function privateLogDirectory(name, env = process8.env) {
977
+ const runtime = env.XDG_RUNTIME_DIR;
978
+ const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
979
+ const path = join(base, name);
980
+ try {
981
+ await mkdir(path, { recursive: true, mode: 448 });
982
+ if (isPrivateDirectory(path))
983
+ return path;
984
+ } catch {}
985
+ return mkdtemp(join(tmpdir(), `${name.replaceAll("/", "-")}-`));
986
+ }
987
+
988
+ // ../kit/src/usage.ts
989
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
990
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
991
+ var LONGEST_NAME = 40;
992
+ var usageError;
993
+ function noteUsageError(message) {
994
+ usageError = message;
995
+ }
996
+ function stateHome(env = process9.env) {
997
+ const dir = env.XDG_STATE_HOME;
998
+ return dir !== undefined && isAbsolute(dir) ? dir : join2(homedir2(), ".local", "state");
999
+ }
1000
+ function usagePath(env = process9.env) {
1001
+ return join2(stateHome(env), CLI_FOLDER, "usage.jsonl");
1002
+ }
1003
+ function usageRecorded(env = process9.env) {
1004
+ const off = env.KAYNOOO_CLI_NO_USAGE;
1005
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1006
+ }
1007
+ function flagNames(argv) {
1008
+ const end = argv.indexOf("--");
1009
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1010
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1011
+ }
1012
+ function usageEntry(bin, command, argv, code, now = new Date) {
1013
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1014
+ usageError = undefined;
1015
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1016
+ }
1017
+ function recordUsage(entry, env = process9.env) {
1018
+ if (!usageRecorded(env))
1019
+ return;
1020
+ try {
1021
+ const path = usagePath(env);
1022
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
1023
+ appendFileSync(path, `${JSON.stringify(entry)}
1024
+ `, { mode: 384 });
1025
+ } catch {}
1026
+ }
1027
+
1028
+ // ../kit/src/cli.ts
772
1029
  var LEVEL_OPTIONS = {
773
1030
  ...OUTPUT_OPTIONS,
774
1031
  help: { type: "boolean", short: "h", description: "show this help" }
775
1032
  };
776
1033
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
777
1034
  function printError(prefix, message, hint, cause) {
778
- const colors = paint(process6.stderr);
779
- const styled = takesControlCodes(process6.stderr);
1035
+ const colors = paint(process10.stderr);
1036
+ const styled = takesControlCodes(process10.stderr);
780
1037
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
781
1038
  const under = (label, text, tint) => text === undefined ? "" : `
782
1039
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -795,90 +1052,116 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
795
1052
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
796
1053
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
797
1054
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1055
+ if (error instanceof UsageError)
1056
+ noteUsageError(error.message);
798
1057
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
799
1058
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
800
1059
  return error instanceof Exit ? error.code : 1;
801
1060
  }
802
1061
  var COMPLETE = "__complete";
803
1062
  var FILES = "__files__";
804
- async function optionsOf(run) {
1063
+ async function completingOf(run) {
805
1064
  completion.active = true;
806
1065
  try {
807
1066
  await run([]);
808
1067
  } catch (error) {
809
1068
  if (error instanceof Completing)
810
- return error.options;
1069
+ return error;
811
1070
  } finally {
812
1071
  completion.active = false;
813
1072
  }
814
- return {};
1073
+ return new Completing({});
1074
+ }
1075
+ function candidateLine(candidate) {
1076
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
1077
+ }
1078
+ function positionalBeingTyped(before, { options, positionals }) {
1079
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1080
+ let index = 0;
1081
+ let at = 0;
1082
+ while (at < before.length) {
1083
+ const word = before[at];
1084
+ if (word === "--") {
1085
+ index += before.length - at - 1;
1086
+ break;
1087
+ }
1088
+ if (!word.startsWith("-"))
1089
+ index++;
1090
+ else if (takesValue(word))
1091
+ at++;
1092
+ at++;
1093
+ }
1094
+ const last = positionals.at(-1);
1095
+ if (index < positionals.length)
1096
+ return positionals[index];
1097
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
815
1098
  }
816
1099
  async function leafCandidates(run, words) {
817
- if (!(words.at(-1) ?? "").startsWith("-"))
818
- return [FILES];
819
- return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1100
+ const completing = await completingOf(run);
1101
+ if ((words.at(-1) ?? "").startsWith("-"))
1102
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1103
+ const flag = words.at(-2);
1104
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1105
+ if (option?.type === "string") {
1106
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1107
+ return values === undefined ? [FILES] : values.map(candidateLine);
1108
+ }
1109
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
1110
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
1111
+ return values === undefined ? [FILES] : values.map(candidateLine);
820
1112
  }
821
1113
  async function printCandidates(found) {
822
1114
  for (const line of await found)
823
1115
  console.log(line);
824
1116
  return 0;
825
1117
  }
826
- async function runMain({ name, version, run, redact }, argv = process6.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)) {
827
1130
  if (argv[0] === COMPLETE)
828
1131
  return printCandidates(leafCandidates(run, argv.slice(1)));
829
1132
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
830
- console.log(version);
1133
+ console.log(version ?? packageVersion());
831
1134
  return 0;
832
1135
  }
1136
+ let code;
833
1137
  try {
834
- return await run(argv);
1138
+ code = await run(argv);
835
1139
  } catch (error) {
836
- return reportThrown(name, error, redact, wantsJson(argv));
1140
+ code = reportThrown(name, error, redact, wantsJson(argv));
837
1141
  }
838
- }
839
- // ../kit/src/logs.ts
840
- import { lstatSync, openSync } from "fs";
841
- import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
842
- import { homedir, tmpdir } from "os";
843
- import { join } from "path";
844
- import process7 from "process";
845
- var DAY_MS = 24 * 60 * 60 * 1000;
846
- var CLI_FOLDER = "kaynooo-cli";
847
- function isPrivateDirectory(path) {
848
- try {
849
- const info = lstatSync(path, { throwIfNoEntry: false });
850
- return info !== undefined && info.isDirectory() && info.uid === (process7.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
851
- } catch {
852
- return false;
1142
+ if (usage !== false) {
1143
+ try {
1144
+ recordUsage(usageEntry(name, undefined, argv, code));
1145
+ } catch {}
853
1146
  }
854
- }
855
- async function privateLogDirectory(name, env = process7.env) {
856
- const runtime = env.XDG_RUNTIME_DIR;
857
- const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
858
- const path = join(base, name);
859
- try {
860
- await mkdir(path, { recursive: true, mode: 448 });
861
- if (isPrivateDirectory(path))
862
- return path;
863
- } catch {}
864
- return mkdtemp(join(tmpdir(), `${name.replaceAll("/", "-")}-`));
1147
+ return code;
865
1148
  }
866
1149
  // ../kit/src/secrets.ts
867
1150
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
868
1151
  // ../kit/src/sessions.ts
869
- import { homedir as homedir2 } from "os";
870
- import { join as join2 } from "path";
871
- import process8 from "process";
1152
+ import { homedir as homedir3 } from "os";
1153
+ import { join as join4 } from "path";
1154
+ import process11 from "process";
872
1155
  var {Glob } = globalThis.Bun;
873
1156
  var SESSION_FILES = new Glob("*.json");
874
1157
  var ACCOUNT_DIRS = new Glob("*/sessions");
875
1158
  async function sessionDirs() {
876
- const home = homedir2();
877
- const dirs = new Set([join2(home, ".claude", "sessions")]);
878
- if (process8.env.CLAUDE_CONFIG_DIR !== undefined)
879
- dirs.add(join2(process8.env.CLAUDE_CONFIG_DIR, "sessions"));
1159
+ const home = homedir3();
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"));
880
1163
  try {
881
- for await (const dir of ACCOUNT_DIRS.scan({ cwd: join2(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 }))
882
1165
  dirs.add(dir);
883
1166
  } catch {}
884
1167
  return [...dirs];
@@ -922,7 +1205,7 @@ async function liveSessions() {
922
1205
  }
923
1206
  async function currentSession(sessions) {
924
1207
  const byPid = new Map(sessions.map((session) => [session.pid, session]));
925
- let pid = process8.ppid;
1208
+ let pid = process11.ppid;
926
1209
  for (let depth = 0;depth < 32 && pid > 1; depth++) {
927
1210
  const session = byPid.get(pid);
928
1211
  if (session !== undefined)
@@ -934,9 +1217,6 @@ async function currentSession(sessions) {
934
1217
  }
935
1218
  return;
936
1219
  }
937
- // package.json
938
- var version = "0.5.0";
939
-
940
1220
  // src/conditions.ts
941
1221
  import { existsSync, statSync } from "fs";
942
1222
  var TAIL = 20;
@@ -1062,9 +1342,9 @@ async function urlCheck(url, timeout) {
1062
1342
  }
1063
1343
 
1064
1344
  // src/task.ts
1065
- import { existsSync as existsSync2, lstatSync as lstatSync2, readFileSync, statSync as statSync2 } from "fs";
1066
- import { join as join3 } from "path";
1067
- import process10 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";
1068
1348
  var EXITED = /(?:^|\n)\[exited with code (-?\d+)\]\n*$/;
1069
1349
  var FAILURE = /\(fail\)|\berror:/i;
1070
1350
  var TASK_ID = /^[\w-]+$/;
@@ -1072,16 +1352,16 @@ var TAIL_BYTES = 256;
1072
1352
  var LONGEST_FAILURES = 30;
1073
1353
  var CARRIAGE_RETURN2 = /\r$/;
1074
1354
  function tasksRoot(env) {
1075
- return join3(env.CLAUDE_CODE_TMPDIR ?? env.TMPDIR ?? "/tmp", `claude-${process10.getuid?.() ?? 0}`);
1355
+ return join5(env.CLAUDE_CODE_TMPDIR ?? env.TMPDIR ?? "/tmp", `claude-${process13.getuid?.() ?? 0}`);
1076
1356
  }
1077
- function taskFile(task, env = process10.env) {
1357
+ function taskFile(task, env = process13.env) {
1078
1358
  if (task.includes("/") || task.endsWith(".output"))
1079
1359
  return task;
1080
1360
  if (!TASK_ID.test(task))
1081
1361
  return;
1082
1362
  const root = tasksRoot(env);
1083
1363
  const found = existsSync2(root) ? [...new Bun.Glob(`*/*/tasks/${task}.output`).scanSync({ cwd: root, onlyFiles: false })] : [];
1084
- return found.length === 0 ? undefined : join3(root, found[0] ?? "");
1364
+ return found.length === 0 ? undefined : join5(root, found[0] ?? "");
1085
1365
  }
1086
1366
  function isTranscript(path) {
1087
1367
  return existsSync2(path) && lstatSync2(path).isSymbolicLink() && path.endsWith(".output");
@@ -1107,7 +1387,7 @@ async function taskEnd(path, lines) {
1107
1387
  }
1108
1388
  function pidAlive(pid) {
1109
1389
  try {
1110
- process10.kill(pid, 0);
1390
+ process13.kill(pid, 0);
1111
1391
  } catch (error) {
1112
1392
  return error.code === "EPERM";
1113
1393
  }
@@ -1115,7 +1395,7 @@ function pidAlive(pid) {
1115
1395
  }
1116
1396
  function isZombie(pid) {
1117
1397
  try {
1118
- const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
1398
+ const stat = readFileSync2(`/proc/${pid}/stat`, "utf8");
1119
1399
  return stat.slice(stat.lastIndexOf(")") + 2, stat.lastIndexOf(")") + 3) === "Z";
1120
1400
  } catch {
1121
1401
  return false;
@@ -1123,21 +1403,23 @@ function isZombie(pid) {
1123
1403
  }
1124
1404
 
1125
1405
  // src/cli.ts
1126
- 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
1127
1407
  waitfor task <task id | file>: waits for a Claude Code background task to end (waitfor task --help)
1128
1408
 
1129
- Every condition given must be met. A --fail line in --file ends the wait at once.
1130
- 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.`;
1131
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
1132
1412
 
1133
1413
  The task is the id a background Bash call returned, or the path of its .output file.
1134
- Exits 0 when the task exited 0, 1 when it exited with another code, 2 on a timeout or a usage error.
1135
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"]];
1136
1417
  var TIMEOUT = { type: "string", short: "t", description: "how long before giving up (5m): 30s, 5m, 1h, a bare number in seconds" };
1137
1418
  var TASK_OPTIONS = {
1138
1419
  lines: { type: "string", short: "n", description: "how many of its last lines to print (20)" },
1139
1420
  timeout: TIMEOUT,
1140
- json: jsonOption()
1421
+ json: jsonOption(),
1422
+ quiet: { type: "boolean", short: "q", description: "no live progress line" }
1141
1423
  };
1142
1424
  var OPTIONS = {
1143
1425
  file: { type: "string", short: "f", description: "a log file to read, from its start, waiting for it to exist" },
@@ -1147,11 +1429,18 @@ var OPTIONS = {
1147
1429
  host: { type: "string", short: "H", description: "the host of --port (127.0.0.1)" },
1148
1430
  url: { type: "string", description: "a URL that must answer 2xx" },
1149
1431
  pid: { type: "string", description: "a process id that must exit" },
1150
- 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" }
1151
1438
  };
1152
1439
  var POLL = 250;
1153
1440
  var URL_TIMEOUT = 5000;
1154
1441
  var WIDTH = 400;
1442
+ var CMD_RUN_LIMIT = 30000;
1443
+ var LAST_LINE = /[^\n]+(?=\n*$)/;
1155
1444
  function regex(source, name) {
1156
1445
  if (source === undefined)
1157
1446
  return;
@@ -1166,8 +1455,19 @@ function numbered(lines, marked) {
1166
1455
  return lines.map((line) => `${line === marked ? ">" : " "} ${String(line.number).padStart(width)} ${truncate(line.text, WIDTH)}`).join(`
1167
1456
  `);
1168
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
+ }
1169
1469
  async function waitTask(args) {
1170
- 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 });
1171
1471
  const path = taskFile(task);
1172
1472
  if (path === undefined)
1173
1473
  fail(`no background task ${task}: give the id a background Bash call returned, or the path of its .output file`);
@@ -1178,8 +1478,8 @@ async function waitTask(args) {
1178
1478
  const lines = wholeNumber(values.lines, "lines", 20);
1179
1479
  const timeout = duration(values.timeout, "timeout", 5 * 60000);
1180
1480
  const started = Date.now();
1181
- const { dim } = paint(process11.stderr);
1182
- 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))}`]);
1183
1483
  let code;
1184
1484
  try {
1185
1485
  for (;; ) {
@@ -1189,7 +1489,7 @@ async function waitTask(args) {
1189
1489
  await Bun.sleep(POLL);
1190
1490
  }
1191
1491
  } finally {
1192
- region.stop();
1492
+ region?.stop();
1193
1493
  }
1194
1494
  const { failures, tail } = await taskEnd(path, lines);
1195
1495
  const last = tail.length === 0 ? "" : `
@@ -1210,20 +1510,25 @@ ${numbered(failures)}`;
1210
1510
  async function main(args) {
1211
1511
  if (args[0] === "task")
1212
1512
  return waitTask(args.slice(1));
1213
- 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"]] });
1214
1514
  const { values, positionals } = parsed;
1215
1515
  if (positionals.length > 0)
1216
1516
  fail(`unexpected argument ${positionals[0]}
1217
1517
 
1218
1518
  ${USAGE}`);
1219
- if (values.until === undefined && values.port === undefined && values.url === undefined && values.pid === undefined)
1220
- 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
1221
1521
 
1222
1522
  ${USAGE}`);
1223
1523
  if ((values.until !== undefined || values.fail !== undefined) !== (values.file !== undefined))
1224
1524
  fail("--until and --fail read the --file lines, and --file needs one of them");
1225
1525
  if (values.host !== undefined && values.port === undefined)
1226
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");
1227
1532
  const port = values.port === undefined ? undefined : wholeNumber(values.port, "port", 0);
1228
1533
  if (port !== undefined && port > 65535)
1229
1534
  fail(`--port takes a port up to 65535, not ${port}`);
@@ -1231,20 +1536,28 @@ ${USAGE}`);
1231
1536
  fail(`--url ${values.url} is no URL`);
1232
1537
  const pid = values.pid === undefined ? undefined : wholeNumber(values.pid, "pid", 0);
1233
1538
  const host = values.host ?? "127.0.0.1";
1539
+ const interval = duration(values.interval, "interval", 1000);
1540
+ const isAny = values.any === true;
1234
1541
  const timeout = duration(values.timeout, "timeout", 5 * 60000);
1235
1542
  const watch = values.file === undefined ? undefined : new FileWatch(values.file, regex(values.until, "until"), regex(values.fail, "fail"));
1236
1543
  const started = Date.now();
1544
+ const json = values.json === true;
1545
+ const say = json ? console.error : console.log;
1546
+ let matched;
1237
1547
  let portLeft = port === undefined ? undefined : "not checked yet";
1238
1548
  let urlLeft = values.url === undefined ? undefined : "not checked yet";
1239
1549
  let isPidLeft = pid !== undefined;
1240
- const { dim } = paint(process11.stderr);
1241
- 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) => {
1242
1554
  const waited = dim(formatElapsed(Date.now() - started));
1243
1555
  const left = [
1244
1556
  watch === undefined || watch.done ? undefined : `${watch.path}: ${watch.exists ? "no --until line yet" : "does not exist yet"}`,
1245
1557
  portLeft === undefined ? undefined : `${host}:${port}: ${portLeft}`,
1246
1558
  urlLeft === undefined ? undefined : `${values.url}: ${urlLeft}`,
1247
- isPidLeft ? `pid ${pid}: still running` : undefined
1559
+ isPidLeft ? `pid ${pid}: still running` : undefined,
1560
+ cmdLeft === undefined ? undefined : `\`${values.cmd}\`: ${cmdLeft}`
1248
1561
  ];
1249
1562
  return left.filter((line) => line !== undefined).map((line) => `${spinner} ${line} ${waited}`);
1250
1563
  });
@@ -1253,18 +1566,21 @@ ${USAGE}`);
1253
1566
  if (watch !== undefined) {
1254
1567
  for (const event of await watch.poll()) {
1255
1568
  if (event.kind === "until") {
1256
- 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 };
1257
1571
  continue;
1258
1572
  }
1259
1573
  console.error(`waitfor: ${watch.path}:${event.line.number} matched --fail after ${formatDuration(Date.now() - started)}
1260
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 } });
1261
1577
  return 1;
1262
1578
  }
1263
1579
  }
1264
1580
  if (port !== undefined && portLeft !== undefined) {
1265
1581
  portLeft = await portProblem(host, port);
1266
1582
  if (portLeft === undefined)
1267
- console.log(`${host}:${port} listening after ${formatDuration(Date.now() - started)}`);
1583
+ say(`${host}:${port} listening after ${formatDuration(Date.now() - started)}`);
1268
1584
  }
1269
1585
  if (values.url !== undefined && urlLeft !== undefined) {
1270
1586
  const budget = Math.max(1, Math.min(URL_TIMEOUT, started + timeout - Date.now()));
@@ -1273,21 +1589,40 @@ ${numbered(event.excerpt, event.line)}`);
1273
1589
  if (!isCutShort)
1274
1590
  urlLeft = "problem" in check ? check.problem : undefined;
1275
1591
  if ("status" in check)
1276
- console.log(`${values.url} answered ${check.status} after ${formatDuration(Date.now() - started)}`);
1592
+ say(`${values.url} answered ${check.status} after ${formatDuration(Date.now() - started)}`);
1277
1593
  }
1278
1594
  if (pid !== undefined && isPidLeft) {
1279
1595
  isPidLeft = pidAlive(pid);
1280
1596
  if (!isPidLeft)
1281
- console.log(`pid ${pid} exited after ${formatDuration(Date.now() - started)}`);
1597
+ say(`pid ${pid} exited after ${formatDuration(Date.now() - started)}`);
1598
+ }
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)}`);
1282
1607
  }
1283
- if ((watch?.done ?? true) && portLeft === undefined && urlLeft === undefined && !isPidLeft)
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 });
1284
1618
  return 0;
1619
+ }
1285
1620
  if (Date.now() - started >= timeout && !(watch?.failing ?? false))
1286
1621
  break;
1287
1622
  await Bun.sleep(POLL);
1288
1623
  }
1289
1624
  } finally {
1290
- region.stop();
1625
+ region?.stop();
1291
1626
  }
1292
1627
  const missing = [];
1293
1628
  if (watch !== undefined && !watch.done)
@@ -1298,9 +1633,11 @@ ${numbered(event.excerpt, event.line)}`);
1298
1633
  missing.push(`${values.url} ${urlLeft}`);
1299
1634
  if (isPidLeft)
1300
1635
  missing.push(`pid ${pid} is still running`);
1636
+ if (cmdLeft !== undefined)
1637
+ missing.push(`\`${values.cmd}\` ${cmdLeft}`);
1301
1638
  const lines = watch?.excerpt() ?? [];
1302
- 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 ? "" : `
1303
1640
  last lines of ${watch?.path}:
1304
1641
  ${numbered(lines)}`}`);
1305
1642
  }
1306
- process11.exitCode = await runMain({ name: "waitfor", version, run: main });
1643
+ process14.exitCode = await runMain({ name: "waitfor", run: main });