@kaynooo/cli-proc 0.7.0 → 0.7.2

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/procs-cli.js CHANGED
@@ -2,13 +2,13 @@
2
2
  // @bun
3
3
 
4
4
  // src/procs-cli.ts
5
- import process13 from "process";
5
+ import process17 from "process";
6
6
  // ../kit/src/args.ts
7
- import process6 from "process";
7
+ import process9 from "process";
8
8
  import { parseArgs } from "util";
9
9
 
10
10
  // ../kit/src/format.ts
11
- import process4 from "process";
11
+ import process7 from "process";
12
12
 
13
13
  // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-n6z2kk96.js
14
14
  var r = new Map;
@@ -23,6 +23,7 @@ function y(e, t) {
23
23
  n = new Intl.NumberFormat(e, t), i.set(o, n);
24
24
  return n;
25
25
  }
26
+
26
27
  // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
27
28
  var N = new Map;
28
29
  var Nt = /\s+\S*$/;
@@ -40,6 +41,7 @@ function ko(t, e, r = "...") {
40
41
  }
41
42
  var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
42
43
  var z = new Map;
44
+
43
45
  // ../kit/src/mode.ts
44
46
  import process2 from "process";
45
47
  var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
@@ -62,7 +64,7 @@ function isInteractive(streams = process2) {
62
64
  }
63
65
 
64
66
  // ../kit/src/style.ts
65
- import process3 from "process";
67
+ import process6 from "process";
66
68
 
67
69
  // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
68
70
  var G2 = /^[a-f0-9]+$/i;
@@ -88,7 +90,7 @@ function C(r, e = globalThis.process?.env ?? {}) {
88
90
  return false;
89
91
  return r?.isTTY === true;
90
92
  }
91
- function f2(r, e = []) {
93
+ function f(r, e = []) {
92
94
  let l = "", n = "";
93
95
  for (let t = 0, i = e.length;t < i; t++)
94
96
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
@@ -98,7 +100,7 @@ function f2(r, e = []) {
98
100
  if (Array.isArray(a)) {
99
101
  let s = g.get(i);
100
102
  if (s === undefined)
101
- s = f2(r, [...e, a]), g.set(i, s);
103
+ s = f(r, [...e, a]), g.set(i, s);
102
104
  return s;
103
105
  }
104
106
  if (typeof a === "function")
@@ -107,30 +109,251 @@ function f2(r, e = []) {
107
109
  if (u === undefined) {
108
110
  if (g.size >= 64)
109
111
  g.clear();
110
- u = f2(r, [...e, a(...s)]), g.set(y, u);
112
+ u = f(r, [...e, a(...s)]), g.set(y, u);
111
113
  }
112
114
  return u;
113
115
  };
114
116
  throw Error(`Unknown style: ${String(i)}`);
115
117
  } });
116
118
  }
117
- function Fe2(r = {}) {
118
- return f2(r);
119
+ function Fe(r = {}) {
120
+ return f(r);
121
+ }
122
+ var o = Fe();
123
+
124
+ // ../kit/src/theme.ts
125
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
126
+ import { homedir as homedir2 } from "os";
127
+ import { join as join3, resolve as resolve2 } from "path";
128
+ import process5 from "process";
129
+
130
+ // ../kit/src/config.ts
131
+ import { existsSync } from "fs";
132
+ import { dirname, join, resolve } from "path";
133
+ import process3 from "process";
134
+ function findUp(names, from = process3.cwd(), stop = () => false) {
135
+ const wanted = typeof names === "string" ? [names] : names;
136
+ for (let dir = resolve(from);; dir = dirname(dir)) {
137
+ const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
138
+ if (found !== undefined)
139
+ return found;
140
+ if (stop(dir) || dirname(dir) === dir)
141
+ return;
142
+ }
143
+ }
144
+
145
+ // ../kit/src/user-config.ts
146
+ import { homedir } from "os";
147
+ import { join as join2 } from "path";
148
+ import process4 from "process";
149
+ function configBase(where = {}) {
150
+ const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
151
+ return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
152
+ }
153
+ function userConfigPath(bin, where = {}) {
154
+ return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
119
155
  }
120
- var o2 = Fe2();
121
156
 
122
157
  // ../kit/src/theme.ts
123
158
  var ENDS = new Map;
159
+ var DEFAULT = {
160
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
161
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
162
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
163
+ bins: {},
164
+ gradient: ["#c084fc", "#67e8f9"]
165
+ };
166
+ var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
167
+ var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
168
+ var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
169
+ var PRESETS = {
170
+ default: {},
171
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
172
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
173
+ ascii: { glyphs: ASCII }
174
+ };
124
175
  var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
176
+ var HEX = /^#[0-9a-f]{6}$/i;
177
+ var CONTROL = /\p{Cc}/u;
125
178
  var MAX_FILE_BYTES = 64 * 1024;
179
+ var SPACES = /\s+/;
180
+ function isColorSpec(spec) {
181
+ if (typeof spec === "number")
182
+ return Number.isInteger(spec) && spec >= 0 && spec <= 255;
183
+ return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
184
+ }
185
+ var CUBE = [0, 95, 135, 175, 215, 255];
186
+ function cubeLevel(channel) {
187
+ return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
188
+ }
189
+ function nearest256(hex) {
190
+ const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
191
+ const levels = rgb.map(cubeLevel);
192
+ const cube = levels.map((level) => CUBE[level]);
193
+ const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
194
+ const greyValue = 8 + grey * 10;
195
+ const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
196
+ return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
197
+ }
198
+ function hasTrueColor(env) {
199
+ return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
200
+ }
201
+ function tinted(colors, spec, env = process5.env) {
202
+ if (typeof spec === "number")
203
+ return colors.ansi256(spec);
204
+ return spec.trim().split(SPACES).reduce((chain, token) => {
205
+ if (HEX.test(token))
206
+ return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
207
+ return chain[token] ?? chain;
208
+ }, colors);
209
+ }
210
+ function isRecord(value) {
211
+ return typeof value === "object" && value !== null && !Array.isArray(value);
212
+ }
213
+ function readThemeFile(path, warn) {
214
+ try {
215
+ const stat = statSync(path, { throwIfNoEntry: false });
216
+ if (stat === undefined)
217
+ return;
218
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
219
+ warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
220
+ return;
221
+ }
222
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
223
+ if (isRecord(parsed))
224
+ return parsed;
225
+ warn(`${path} is not a JSON object, theme ignored`);
226
+ } catch (error) {
227
+ warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
228
+ }
229
+ return;
230
+ }
231
+ function applyPreset(theme, name, warn, where) {
232
+ if (name === undefined)
233
+ return;
234
+ if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
235
+ warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
236
+ return;
237
+ }
238
+ const preset = PRESETS[name];
239
+ Object.assign(theme.colors, preset.colors);
240
+ Object.assign(theme.glyphs, preset.glyphs);
241
+ if (preset.accents !== undefined)
242
+ theme.accents = [...preset.accents];
243
+ if (Object.hasOwn(preset, "gradient"))
244
+ theme.gradient = preset.gradient;
245
+ return name;
246
+ }
247
+ function applyFile(theme, file, where, warn) {
248
+ if (isRecord(file.colors)) {
249
+ for (const [key, value] of Object.entries(file.colors)) {
250
+ if (!Object.hasOwn(DEFAULT.colors, key))
251
+ warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
252
+ else if (!isColorSpec(value))
253
+ warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
254
+ else
255
+ theme.colors[key] = value;
256
+ }
257
+ }
258
+ if (isRecord(file.glyphs)) {
259
+ for (const [key, value] of Object.entries(file.glyphs)) {
260
+ if (!Object.hasOwn(DEFAULT.glyphs, key))
261
+ warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
262
+ else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
263
+ warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
264
+ else
265
+ theme.glyphs[key] = value;
266
+ }
267
+ }
268
+ if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
269
+ theme.accents = [...file.accents];
270
+ else if (file.accents !== undefined)
271
+ warn(`${where}: accents must be a non-empty list of colours`);
272
+ if (file.gradient === null)
273
+ theme.gradient = undefined;
274
+ else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
275
+ theme.gradient = [file.gradient[0], file.gradient[1]];
276
+ else if (file.gradient !== undefined)
277
+ warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
278
+ if (isRecord(file.bins)) {
279
+ for (const [bin, value] of Object.entries(file.bins)) {
280
+ if (isColorSpec(value))
281
+ theme.bins[bin] = value;
282
+ else
283
+ warn(`${where}: bin ${bin} has no valid colour`);
284
+ }
285
+ }
286
+ }
287
+ function endsWalk(home) {
288
+ return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
289
+ }
126
290
  var warned = new Set;
291
+ function warnOnce(message) {
292
+ if (warned.has(message))
293
+ return;
294
+ warned.add(message);
295
+ console.error(`warning: theme ${message}`);
296
+ }
297
+ function isPath(chosen) {
298
+ return chosen.includes("/") || chosen.endsWith(".json");
299
+ }
300
+ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
301
+ const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
302
+ const sources = [];
303
+ const chosen = env.KIT_THEME ?? "";
304
+ const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
305
+ if (isPath(chosen))
306
+ wanted.push(resolve2(from, chosen));
307
+ const files = [];
308
+ for (const path of wanted) {
309
+ const file = path === undefined ? undefined : readThemeFile(path, warn);
310
+ if (path !== undefined && file !== undefined)
311
+ files.push({ path, file });
312
+ }
313
+ let preset = "default";
314
+ if (chosen !== "" && !isPath(chosen)) {
315
+ preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
316
+ } else {
317
+ const named = files.findLast(({ file }) => file.preset !== undefined);
318
+ if (named !== undefined)
319
+ preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
320
+ }
321
+ for (const { path, file } of files) {
322
+ applyFile(theme, file, path, warn);
323
+ sources.push(path);
324
+ }
325
+ return { theme, sources, preset };
326
+ }
327
+ var current;
328
+ var currentKey = "";
329
+ function activeTheme() {
330
+ const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
331
+ if (current === undefined || key !== currentKey) {
332
+ current = loadTheme();
333
+ currentKey = key;
334
+ }
335
+ return current;
336
+ }
127
337
 
128
338
  // ../kit/src/style.ts
129
- function takesControlCodes(stream, env = process3.env) {
339
+ var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
340
+ function takesControlCodes(stream, env = process6.env) {
130
341
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
131
342
  }
132
- function paint(stream, env = process3.env) {
133
- return Fe2({ stream: { isTTY: takesControlCodes(stream, env) }, env });
343
+ function paint(stream, env = process6.env) {
344
+ return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
345
+ }
346
+ function marked(mark, text, stream, detail, env = process6.env) {
347
+ const colors = paint(stream, env);
348
+ let head = MARK_WORDS[mark];
349
+ if (takesControlCodes(stream, env)) {
350
+ const { theme } = activeTheme();
351
+ head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
352
+ }
353
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
354
+ }
355
+ function problem(text, detail) {
356
+ console.error(marked("problem", text, process6.stderr, detail));
134
357
  }
135
358
  var STATUS_WORDS = {
136
359
  passed: ["passed", "success", "succeeded", "ok"],
@@ -141,7 +364,7 @@ var STATUS_WORDS = {
141
364
  };
142
365
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
143
366
  // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-knqbxp56.js
144
- function tt2(i, { units: r = "iec", dp: t = 1, locale: n } = {}) {
367
+ function tt(i, { units: r = "iec", dp: t = 1, locale: n } = {}) {
145
368
  let e = r === "si" ? 1000 : 1024;
146
369
  if (Math.abs(i) < e)
147
370
  return `${i} B`;
@@ -179,7 +402,7 @@ var ESCAPE = String.fromCharCode(27);
179
402
  function textWidth(text) {
180
403
  return Bun.stringWidth(text);
181
404
  }
182
- function table(rows, { cellWidth, header = false, align = [], fit, stream = process4.stdout, env = process4.env } = {}) {
405
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
183
406
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
184
407
  if (outputMode(stream, env) === "agent")
185
408
  return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
@@ -218,7 +441,7 @@ function narrow(rows, widths, limit) {
218
441
  }
219
442
  return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
220
443
  }
221
- function jsonText(value, replacer, { stream = process4.stdout, env = process4.env } = {}) {
444
+ function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
222
445
  return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
223
446
  }
224
447
  function printJson(value) {
@@ -226,27 +449,23 @@ function printJson(value) {
226
449
  }
227
450
 
228
451
  // ../kit/src/help.ts
229
- import process5 from "process";
452
+ import process8 from "process";
230
453
  var OPTIONAL = /\[[^\]]+\]/g;
231
454
  var USAGE_PREFIX = /^usage:\s*/i;
232
455
  var FULL_STOP = /\.$/;
233
- function usageLine(usage, colors = paint(process5.stdout)) {
456
+ function usageLine(usage, colors = paint(process8.stdout)) {
234
457
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
235
458
  }
236
- function helpText(usage, options, colors = paint(process5.stdout), { examples = [], replaces, exits = [] } = {}) {
237
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
459
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
460
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
238
461
  `);
239
462
  }
240
- function exitRows(exits, colors = paint(process5.stdout)) {
463
+ function exitRows(exits, colors = paint(process8.stdout)) {
241
464
  if (exits.length === 0)
242
465
  return [];
243
- const width = Math.max(...exits.map(([code]) => String(code).length));
244
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
245
- }
246
- function replacesRows(replaces, colors = paint(process5.stdout)) {
247
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
466
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
248
467
  }
249
- function wantsHelpJson(env = process5.env) {
468
+ function wantsHelpJson(env = process8.env) {
250
469
  return env.KIT_HELP === "json";
251
470
  }
252
471
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -265,12 +484,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
265
484
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
266
485
  };
267
486
  }
268
- function exampleRows(examples, colors = paint(process5.stdout)) {
487
+ function exampleRows(examples, colors = paint(process8.stdout)) {
269
488
  if (examples.length === 0 || outputMode() === "agent")
270
489
  return [];
271
490
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
272
491
  }
273
- function optionRows(options, colors = paint(process5.stdout)) {
492
+ function optionRows(options, colors = paint(process8.stdout)) {
274
493
  const rows = Object.entries(options).map(([name, option]) => {
275
494
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
276
495
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -371,7 +590,7 @@ var OUTPUT_OPTIONS = {
371
590
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
372
591
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
373
592
  };
374
- function applyOutput(color, plain, env = process6.env) {
593
+ function applyOutput(color, plain, env = process9.env) {
375
594
  const when = plain === true ? "never" : color ?? "auto";
376
595
  if (when === "auto")
377
596
  return;
@@ -540,9 +759,33 @@ function nearestOption(message, options, allowNegative) {
540
759
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
541
760
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
542
761
  }
762
+ // ../kit/src/argv.ts
763
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
764
+ import { resolve as resolve3 } from "path";
765
+ import process10 from "process";
766
+ function commandLine() {
767
+ try {
768
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
769
+ } catch {
770
+ return;
771
+ }
772
+ }
773
+ function realPath(word) {
774
+ try {
775
+ return realpathSync(resolve3(word));
776
+ } catch {
777
+ return;
778
+ }
779
+ }
780
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
781
+ const target = script === undefined ? undefined : realPath(script) ?? script;
782
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
783
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
784
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
785
+ }
543
786
  // ../kit/src/process.ts
544
787
  import { constants } from "os";
545
- import process7 from "process";
788
+ import process11 from "process";
546
789
  var KILL_GRACE_MS = 2000;
547
790
  function exitCodeOf(code, signal) {
548
791
  if (code !== null)
@@ -562,7 +805,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
562
805
  return;
563
806
  try {
564
807
  if (grouped)
565
- process7.kill(-proc.pid, killing);
808
+ process11.kill(-proc.pid, killing);
566
809
  else
567
810
  proc.kill(killing);
568
811
  } catch {}
@@ -636,15 +879,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
636
879
  var RESET_STYLE = `${ESC}[0m`;
637
880
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
638
881
  // ../kit/src/cli.ts
639
- import { readFileSync, realpathSync } from "fs";
640
- import { dirname as dirname2, join as join2 } from "path";
641
- import process9 from "process";
882
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
883
+ import { dirname as dirname3, join as join5 } from "path";
884
+ import process13 from "process";
642
885
 
643
886
  // ../kit/src/usage.ts
644
887
  import { appendFileSync, mkdirSync } from "fs";
645
- import { homedir } from "os";
646
- import { dirname, isAbsolute, join } from "path";
647
- import process8 from "process";
888
+ import { homedir as homedir3 } from "os";
889
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
890
+ import process12 from "process";
648
891
 
649
892
  // ../kit/src/logs.ts
650
893
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -658,14 +901,14 @@ var usageError;
658
901
  function noteUsageError(message) {
659
902
  usageError = message;
660
903
  }
661
- function stateHome(env = process8.env) {
904
+ function stateHome(env = process12.env) {
662
905
  const dir = env.XDG_STATE_HOME;
663
- return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
906
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
664
907
  }
665
- function usagePath(env = process8.env) {
666
- return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
908
+ function usagePath(env = process12.env) {
909
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
667
910
  }
668
- function usageRecorded(env = process8.env) {
911
+ function usageRecorded(env = process12.env) {
669
912
  const off = env.KAYNOOO_CLI_NO_USAGE;
670
913
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
671
914
  }
@@ -679,12 +922,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
679
922
  usageError = undefined;
680
923
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
681
924
  }
682
- function recordUsage(entry, env = process8.env) {
925
+ function recordUsage(entry, env = process12.env) {
683
926
  if (!usageRecorded(env))
684
927
  return;
685
928
  try {
686
929
  const path = usagePath(env);
687
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
930
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
688
931
  appendFileSync(path, `${JSON.stringify(entry)}
689
932
  `, { mode: 384 });
690
933
  } catch {}
@@ -756,7 +999,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
756
999
  header(colors, summary),
757
1000
  "",
758
1001
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
759
- ...replacesRows(replaces, colors),
760
1002
  "",
761
1003
  ...await commandRows(commands, colors),
762
1004
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -770,8 +1012,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
770
1012
  `);
771
1013
  }
772
1014
  function printError(prefix, message, hint, cause) {
773
- const colors = paint(process9.stderr);
774
- const styled = takesControlCodes(process9.stderr);
1015
+ const colors = paint(process13.stderr);
1016
+ const styled = takesControlCodes(process13.stderr);
775
1017
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
776
1018
  const under = (label, text, tint) => text === undefined ? "" : `
777
1019
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -814,11 +1056,11 @@ async function dispatch(level, typed, { version, redact }) {
814
1056
  }
815
1057
  }
816
1058
  if (name === undefined && level.path.length > 1) {
817
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
1059
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
818
1060
  return 2;
819
1061
  }
820
1062
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
821
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
1063
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
822
1064
  return 0;
823
1065
  }
824
1066
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -874,24 +1116,24 @@ function candidateLine(candidate) {
874
1116
  }
875
1117
  function positionalBeingTyped(before, { options, positionals }) {
876
1118
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
877
- let index = 0;
1119
+ const typed = [];
878
1120
  let at = 0;
879
1121
  while (at < before.length) {
880
1122
  const word = before[at];
881
1123
  if (word === "--") {
882
- index += before.length - at - 1;
1124
+ typed.push(...before.slice(at + 1));
883
1125
  break;
884
1126
  }
885
1127
  if (!word.startsWith("-"))
886
- index++;
1128
+ typed.push(word);
887
1129
  else if (takesValue(word))
888
1130
  at++;
889
1131
  at++;
890
1132
  }
891
1133
  const last = positionals.at(-1);
892
- if (index < positionals.length)
893
- return positionals[index];
894
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1134
+ if (typed.length < positionals.length)
1135
+ return { name: positionals[typed.length], typed };
1136
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
895
1137
  }
896
1138
  async function leafCandidates(run, words) {
897
1139
  const completing = await completingOf(run);
@@ -899,12 +1141,12 @@ async function leafCandidates(run, words) {
899
1141
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
900
1142
  const flag = words.at(-2);
901
1143
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1144
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
902
1145
  if (option?.type === "string") {
903
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1146
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
904
1147
  return values === undefined ? [FILES] : values.map(candidateLine);
905
1148
  }
906
- const name = positionalBeingTyped(words.slice(0, -1), completing);
907
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1149
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
908
1150
  return values === undefined ? [FILES] : values.map(candidateLine);
909
1151
  }
910
1152
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -935,17 +1177,21 @@ async function printCandidates(found) {
935
1177
  return 0;
936
1178
  }
937
1179
  function packageVersion(entry = Bun.main) {
938
- for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1180
+ let resolved = entry;
1181
+ try {
1182
+ resolved = realpathSync2(entry);
1183
+ } catch {}
1184
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
939
1185
  try {
940
- const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
1186
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
941
1187
  if (typeof version === "string")
942
1188
  return version;
943
1189
  } catch {}
944
- if (dirname2(dir) === dir)
1190
+ if (dirname3(dir) === dir)
945
1191
  return "0.0.0";
946
1192
  }
947
1193
  }
948
- async function runCli(cli, argv = process9.argv.slice(2)) {
1194
+ async function runCli(cli, argv = scriptArgs()) {
949
1195
  const version = cli.version ?? packageVersion();
950
1196
  if (argv[0] === COMPLETE)
951
1197
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -972,7 +1218,7 @@ function commandPath(scope, argv) {
972
1218
  }
973
1219
  return path.length === 0 ? undefined : path.join(" ");
974
1220
  }
975
- async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
1221
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
976
1222
  if (argv[0] === COMPLETE)
977
1223
  return printCandidates(leafCandidates(run, argv.slice(1)));
978
1224
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1016,7 +1262,7 @@ function parseSize(text, bareUnit = 1) {
1016
1262
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1017
1263
  }
1018
1264
  // ../kit/src/watch.ts
1019
- import process10 from "process";
1265
+ import process14 from "process";
1020
1266
  import { format } from "util";
1021
1267
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1022
1268
  var DEFAULT_SECONDS = 2;
@@ -1038,7 +1284,7 @@ function withoutWatch(args) {
1038
1284
  }
1039
1285
  return rest;
1040
1286
  }
1041
- async function watching(value, step, stream = process10.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1287
+ async function watching(value, step, stream = process14.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1042
1288
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1043
1289
  if (!takesControlCodes(stream))
1044
1290
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1046,12 +1292,12 @@ async function watching(value, step, stream = process10.stdout, sleep = Bun.slee
1046
1292
  for (let round = 0;round < rounds; round++) {
1047
1293
  const held = [];
1048
1294
  const { log, info } = console;
1049
- const write = process10.stdout.write.bind(process10.stdout);
1295
+ const write = process14.stdout.write.bind(process14.stdout);
1050
1296
  const hold = (...parts) => void held.push(`${format(...parts)}
1051
1297
  `);
1052
1298
  console.log = hold;
1053
1299
  console.info = hold;
1054
- process10.stdout.write = (text) => {
1300
+ process14.stdout.write = (text) => {
1055
1301
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1056
1302
  return true;
1057
1303
  };
@@ -1060,7 +1306,7 @@ async function watching(value, step, stream = process10.stdout, sleep = Bun.slee
1060
1306
  } finally {
1061
1307
  console.log = log;
1062
1308
  console.info = info;
1063
- process10.stdout.write = write;
1309
+ process14.stdout.write = write;
1064
1310
  }
1065
1311
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1066
1312
  await sleep(interval);
@@ -1068,9 +1314,9 @@ async function watching(value, step, stream = process10.stdout, sleep = Bun.slee
1068
1314
  return code;
1069
1315
  }
1070
1316
  // src/procs.ts
1071
- import { existsSync } from "fs";
1072
- import { homedir as homedir2 } from "os";
1073
- import process12 from "process";
1317
+ import { existsSync as existsSync3 } from "fs";
1318
+ import { homedir as homedir4 } from "os";
1319
+ import process16 from "process";
1074
1320
 
1075
1321
  // src/read.ts
1076
1322
  import { readdir, readFile, readlink } from "fs/promises";
@@ -1448,7 +1694,7 @@ function maskArgs(args) {
1448
1694
  }
1449
1695
 
1450
1696
  // src/select.ts
1451
- import { basename as basename2, join as join3, relative } from "path";
1697
+ import { basename as basename2, join as join6, relative } from "path";
1452
1698
  var BROWSERS = /^(?:chrom(?:e|ium)(?:-browser)?|google-chrome(?:-stable|-beta|-unstable)?|chrome_crashpad_handler|chrome-headless-shell|headless_shell|chromium-headless-shell|brave|brave-browser|msedge|microsoft-edge|webkitwebprocess|webkitnetworkprocess|webkitgpuprocess|minibrowser|webkitwebdriver|wpewebprocess|wpenetworkprocess|bun-webview.*)$/i;
1453
1699
  var NATIVE = new Set(["rust-analyzer", "gopls", "clangd", "lua-language-server", "pyright-langserver", "pylsp", "intelephense", "phpactor", "tsgo", "esbuild", "biome", "ruff", "phpunit", "pytest", "vitest", "jest"]);
1454
1700
  var RUNTIMES = new Set(["node", "bun", "bunx", "deno", "nodejs"]);
@@ -1485,9 +1731,9 @@ function projectOf(cwd, exists, home) {
1485
1731
  if (cwd === undefined || !cwd.startsWith(`${home}/`))
1486
1732
  return;
1487
1733
  const folders = [];
1488
- for (let dir = cwd;dir.startsWith(`${home}/`); dir = join3(dir, ".."))
1734
+ for (let dir = cwd;dir.startsWith(`${home}/`); dir = join6(dir, ".."))
1489
1735
  folders.push(dir);
1490
- return folders.find((dir) => exists(join3(dir, ".git"))) ?? folders.find((dir) => MARKERS.some((marker) => exists(join3(dir, marker))));
1736
+ return folders.find((dir) => exists(join6(dir, ".git"))) ?? folders.find((dir) => MARKERS.some((marker) => exists(join6(dir, marker))));
1491
1737
  }
1492
1738
  function isOrphan(proc, byPid) {
1493
1739
  if (proc.unit?.endsWith(".service") === true)
@@ -1565,14 +1811,14 @@ var usage2 = `procs
1565
1811
 
1566
1812
  Lists the leftover or heavy processes of the calling user that are worth cleaning, grouped by origin: the project folder their working directory is in, a browser profile for a chromium and its helpers, else their command. Each group shows its process count, total resident memory and oldest age.
1567
1813
  A process is listed when it is a dev tool (bun, node, vite, nuxt, next, chromium and chrome, playwright and webview browsers and their helpers, language servers, test runners) and either an orphan, reparented to init or to the user's systemd, or heavy (500M resident by default). The processes below a listed one, and those sharing a browser profile with it, are listed too, so a chromium whose main process was killed groups with its leftover helpers.
1568
- \`--kill\` is a dry run that names what it would stop unless --yes is given; it sends SIGTERM, then SIGKILL after --grace to what is still there. It never signals pid 1, shells, terminals, this command and its ancestors, or processes of other users.
1569
-
1570
- Exits 0 when it listed or stopped everything, 1 when a process survived SIGKILL, 2 on a usage error.`;
1814
+ \`--kill\` is a dry run that names what it would stop unless --yes is given; it sends SIGTERM, then SIGKILL after --grace to what is still there. It never signals pid 1, shells, terminals, this command and its ancestors, or processes of other users.`;
1815
+ var EXITS = [[0, "it listed or stopped everything"], [1, "a process survived SIGKILL"], [2, "a usage error"]];
1571
1816
  var options = {
1572
1817
  json: jsonOption("{ groups: [{ origin, kind, count, rss, oldestSeconds, tools, orphans, pids, processes }], skipped }"),
1573
1818
  kill: { type: "boolean", conflicts: ["watch"], description: "stop the listed processes: a dry run without --yes" },
1574
1819
  watch: watchOption("the processes"),
1575
1820
  yes: { type: "boolean", short: "y", description: "with --kill, really stop them, without asking" },
1821
+ quiet: { type: "boolean", short: "q", description: "with --kill --yes, print nothing about what was stopped" },
1576
1822
  "min-mem": { type: "string", description: "heavy from this resident size (500M), and the least a left over process must use to be listed; a bare number counts megabytes" },
1577
1823
  older: { type: "string", description: "only processes at least this old: 30m, 2h, 1d" },
1578
1824
  grace: { type: "string", description: "how long SIGTERM gets before SIGKILL (5s)" }
@@ -1594,11 +1840,11 @@ function summary(group) {
1594
1840
  };
1595
1841
  }
1596
1842
  function render(groups) {
1597
- const colors = paint(process12.stdout);
1843
+ const colors = paint(process16.stdout);
1598
1844
  const rows = groups.map((group) => [
1599
1845
  group.origin,
1600
1846
  String(group.members.length),
1601
- tt2(group.rss),
1847
+ tt(group.rss),
1602
1848
  formatSeconds(group.oldestMs / 1000),
1603
1849
  colors.dim(truncate(Object.entries(Object.groupBy(group.members, ({ tool }) => tool)).map(([tool, list]) => `${tool}${list.length > 1 ? ` x${list.length}` : ""}`).join(", "), 50)),
1604
1850
  group.orphans === 0 ? "" : colors.yellow(`${group.orphans} orphaned`)
@@ -1607,6 +1853,7 @@ function render(groups) {
1607
1853
  }
1608
1854
  async function procs(args) {
1609
1855
  const { values } = parse(args, usage2, options, {
1856
+ exits: EXITS,
1610
1857
  replaces: "pkill -f and pgrep -f one-liners (which match their own shell), ps aux | grep for leftover chromium, bun or vite processes",
1611
1858
  examples: [
1612
1859
  ["procs", "leftover and heavy dev processes, by origin"],
@@ -1621,10 +1868,10 @@ async function procs(args) {
1621
1868
  if (values.watch !== undefined)
1622
1869
  return watching(values.watch, async () => procs(withoutWatch(args)));
1623
1870
  const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0, "m");
1624
- const uid = process12.getuid?.() ?? -1;
1871
+ const uid = process16.getuid?.() ?? -1;
1625
1872
  const all = await snapshot("/proc", (owner) => owner === uid);
1626
- const mine = new Set(ancestry(process12.pid, new Map(all.map((proc) => [proc.pid, proc]))));
1627
- const { groups, protectedCount } = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir2(), exists: existsSync, minMem, olderMs });
1873
+ const mine = new Set(ancestry(process16.pid, new Map(all.map((proc) => [proc.pid, proc]))));
1874
+ const { groups, protectedCount } = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir4(), exists: existsSync3, minMem, olderMs });
1628
1875
  const pids = groups.flatMap((group) => group.members.map(({ proc }) => proc.pid));
1629
1876
  const show = (extra = {}) => {
1630
1877
  if (values.json === true) {
@@ -1636,19 +1883,20 @@ async function procs(args) {
1636
1883
  if (values.kill !== true || pids.length === 0 || values.yes !== true) {
1637
1884
  show();
1638
1885
  if (values.json !== true && protectedCount > 0)
1639
- console.error(paint(process12.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`));
1886
+ console.error(paint(process16.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`));
1640
1887
  if (values.kill === true && pids.length > 0)
1641
1888
  console.error(`dry run: would stop ${pids.length} ${pids.length === 1 ? "process" : "processes"} (${pids.join(" ")}), pass --yes to do it`);
1642
1889
  return 0;
1643
1890
  }
1644
1891
  const outcome = await terminate(pids, { escalate: true, graceMs: duration(values.grace, "grace", 5000) });
1645
- show({ stopped: [...outcome.terminated, ...outcome.killed], killed: outcome.killed, survived: outcome.survived });
1646
- if (values.json !== true)
1892
+ if (values.quiet !== true || values.json === true)
1893
+ show({ stopped: [...outcome.terminated, ...outcome.killed], killed: outcome.killed, survived: outcome.survived });
1894
+ if (values.json !== true && values.quiet !== true)
1647
1895
  console.log(`stopped ${outcome.terminated.length + outcome.killed.length} of ${pids.length}${outcome.killed.length === 0 ? "" : `, ${outcome.killed.length} needed SIGKILL`}`);
1648
1896
  if (outcome.survived.length > 0)
1649
- console.error(`still running: ${outcome.survived.join(" ")}`);
1897
+ problem(`still running: ${outcome.survived.join(" ")}`);
1650
1898
  return outcome.survived.length === 0 ? 0 : 1;
1651
1899
  }
1652
1900
 
1653
1901
  // src/procs-cli.ts
1654
- process13.exitCode = await runMain({ name: "procs", run: procs });
1902
+ process17.exitCode = await runMain({ name: "procs", run: procs });