@kaynooo/cli-db 0.10.0 → 0.11.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.
Files changed (2) hide show
  1. package/dist/cli.js +306 -90
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -2,16 +2,34 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process13 from "process";
5
+ import process16 from "process";
6
6
  // ../kit/src/args.ts
7
- import process6 from "process";
7
+ import process10 from "process";
8
8
  import { parseArgs } from "util";
9
9
 
10
10
  // ../kit/src/format.ts
11
- import process3 from "process";
11
+ import process7 from "process";
12
12
 
13
- // ../kit/src/style.ts
13
+ // ../kit/src/mode.ts
14
14
  import process2 from "process";
15
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
16
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
17
+ function isSet(value) {
18
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
19
+ }
20
+ function outputMode(stream = process2.stdout, env = process2.env) {
21
+ const chosen = env.KIT_MODE;
22
+ if (chosen !== undefined && MODES.has(chosen))
23
+ return chosen;
24
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
25
+ return "agent";
26
+ if (stream.isTTY === true)
27
+ return "terminal";
28
+ return isSet(env.CI) ? "ci" : "pipe";
29
+ }
30
+
31
+ // ../kit/src/style.ts
32
+ import process6 from "process";
15
33
 
16
34
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
17
35
  function x(s) {
@@ -274,36 +292,246 @@ function le(i = {}) {
274
292
  }
275
293
  var t = le();
276
294
 
277
- // ../kit/src/style.ts
278
- var MARKS = {
279
- ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
280
- warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
281
- problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
282
- note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
295
+ // ../kit/src/theme.ts
296
+ import { existsSync as existsSync3, readFileSync, statSync } from "fs";
297
+ import { homedir as homedir2 } from "os";
298
+ import { join as join3, resolve as resolve2 } from "path";
299
+ import process5 from "process";
300
+
301
+ // ../kit/src/config.ts
302
+ import { existsSync } from "fs";
303
+ import { dirname, join, resolve } from "path";
304
+ import process3 from "process";
305
+ function findUp(names, from = process3.cwd(), stop = () => false) {
306
+ const wanted = typeof names === "string" ? [names] : names;
307
+ for (let dir = resolve(from);; dir = dirname(dir)) {
308
+ const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
309
+ if (found !== undefined)
310
+ return found;
311
+ if (stop(dir) || dirname(dir) === dir)
312
+ return;
313
+ }
314
+ }
315
+
316
+ // ../kit/src/user-config.ts
317
+ import { existsSync as existsSync2 } from "fs";
318
+ import { homedir } from "os";
319
+ import { join as join2 } from "path";
320
+ import process4 from "process";
321
+ function configBase(where = {}) {
322
+ const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
323
+ return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
324
+ }
325
+ function userConfigPath(bin, where = {}) {
326
+ return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
327
+ }
328
+ function userConfigReadPath(bin, legacy = [], where = {}) {
329
+ const current = userConfigPath(bin, where);
330
+ if (existsSync2(current))
331
+ return current;
332
+ const base = configBase(where);
333
+ return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
334
+ }
335
+
336
+ // ../kit/src/theme.ts
337
+ var DEFAULT = {
338
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
339
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501" },
340
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
341
+ bins: {}
283
342
  };
284
- function takesControlCodes(stream, env = process2.env) {
285
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
343
+ var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
344
+ var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
345
+ var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#" };
346
+ var PRESETS = {
347
+ default: {},
348
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"] },
349
+ mono: { colors: MONO, accents: ["bold"] },
350
+ ascii: { glyphs: ASCII }
351
+ };
352
+ 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"]);
353
+ var HEX = /^#[0-9a-f]{6}$/i;
354
+ var CONTROL = /\p{Cc}/u;
355
+ var MAX_FILE_BYTES = 64 * 1024;
356
+ var SPACES = /\s+/;
357
+ function isColorSpec(spec) {
358
+ if (typeof spec === "number")
359
+ return Number.isInteger(spec) && spec >= 0 && spec <= 255;
360
+ return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
361
+ }
362
+ var CUBE = [0, 95, 135, 175, 215, 255];
363
+ function cubeLevel(channel) {
364
+ return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
365
+ }
366
+ function nearest256(hex) {
367
+ const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
368
+ const levels = rgb.map(cubeLevel);
369
+ const cube = levels.map((level) => CUBE[level]);
370
+ const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
371
+ const greyValue = 8 + grey * 10;
372
+ const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
373
+ return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
374
+ }
375
+ function hasTrueColor(env) {
376
+ return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
377
+ }
378
+ function tinted(colors, spec, env = process5.env) {
379
+ if (typeof spec === "number")
380
+ return colors.ansi256(spec);
381
+ return spec.trim().split(SPACES).reduce((chain, token) => {
382
+ if (HEX.test(token))
383
+ return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
384
+ return chain[token] ?? chain;
385
+ }, colors);
386
+ }
387
+ function isRecord(value) {
388
+ return typeof value === "object" && value !== null && !Array.isArray(value);
389
+ }
390
+ function readThemeFile(path, warn) {
391
+ try {
392
+ const stat = statSync(path, { throwIfNoEntry: false });
393
+ if (stat === undefined)
394
+ return;
395
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
396
+ warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
397
+ return;
398
+ }
399
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
400
+ if (isRecord(parsed))
401
+ return parsed;
402
+ warn(`${path} is not a JSON object, theme ignored`);
403
+ } catch (error) {
404
+ warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
405
+ }
406
+ return;
286
407
  }
287
- function paint(stream, env = process2.env) {
408
+ function applyPreset(theme, name, warn, where) {
409
+ if (name === undefined)
410
+ return;
411
+ if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
412
+ warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
413
+ return;
414
+ }
415
+ const preset = PRESETS[name];
416
+ Object.assign(theme.colors, preset.colors);
417
+ Object.assign(theme.glyphs, preset.glyphs);
418
+ if (preset.accents !== undefined)
419
+ theme.accents = [...preset.accents];
420
+ return name;
421
+ }
422
+ function applyFile(theme, file, where, warn) {
423
+ if (isRecord(file.colors)) {
424
+ for (const [key, value] of Object.entries(file.colors)) {
425
+ if (!Object.hasOwn(DEFAULT.colors, key))
426
+ warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
427
+ else if (!isColorSpec(value))
428
+ warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
429
+ else
430
+ theme.colors[key] = value;
431
+ }
432
+ }
433
+ if (isRecord(file.glyphs)) {
434
+ for (const [key, value] of Object.entries(file.glyphs)) {
435
+ if (!Object.hasOwn(DEFAULT.glyphs, key))
436
+ warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
437
+ else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
438
+ warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
439
+ else
440
+ theme.glyphs[key] = value;
441
+ }
442
+ }
443
+ if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
444
+ theme.accents = [...file.accents];
445
+ else if (file.accents !== undefined)
446
+ warn(`${where}: accents must be a non-empty list of colours`);
447
+ if (isRecord(file.bins)) {
448
+ for (const [bin, value] of Object.entries(file.bins)) {
449
+ if (isColorSpec(value))
450
+ theme.bins[bin] = value;
451
+ else
452
+ warn(`${where}: bin ${bin} has no valid colour`);
453
+ }
454
+ }
455
+ }
456
+ function endsWalk(home) {
457
+ return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
458
+ }
459
+ var warned = new Set;
460
+ function warnOnce(message) {
461
+ if (warned.has(message))
462
+ return;
463
+ warned.add(message);
464
+ console.error(`warning: theme ${message}`);
465
+ }
466
+ function isPath(chosen) {
467
+ return chosen.includes("/") || chosen.endsWith(".json");
468
+ }
469
+ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
470
+ const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
471
+ const sources = [];
472
+ const chosen = env.KIT_THEME ?? "";
473
+ const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
474
+ if (isPath(chosen))
475
+ wanted.push(resolve2(from, chosen));
476
+ const files = [];
477
+ for (const path of wanted) {
478
+ const file = path === undefined ? undefined : readThemeFile(path, warn);
479
+ if (path !== undefined && file !== undefined)
480
+ files.push({ path, file });
481
+ }
482
+ let preset = "default";
483
+ if (chosen !== "" && !isPath(chosen)) {
484
+ preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
485
+ } else {
486
+ const named = files.findLast(({ file }) => file.preset !== undefined);
487
+ if (named !== undefined)
488
+ preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
489
+ }
490
+ for (const { path, file } of files) {
491
+ applyFile(theme, file, path, warn);
492
+ sources.push(path);
493
+ }
494
+ return { theme, sources, preset };
495
+ }
496
+ var current;
497
+ var currentKey = "";
498
+ function activeTheme() {
499
+ const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
500
+ if (current === undefined || key !== currentKey) {
501
+ current = loadTheme();
502
+ currentKey = key;
503
+ }
504
+ return current;
505
+ }
506
+
507
+ // ../kit/src/style.ts
508
+ var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:" };
509
+ function takesControlCodes(stream, env = process6.env) {
510
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
511
+ }
512
+ function paint(stream, env = process6.env) {
288
513
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
289
514
  }
290
- function marked(mark, text, stream, detail, env = process2.env) {
515
+ function marked(mark, text, stream, detail, env = process6.env) {
291
516
  const colors = paint(stream, env);
292
- const { symbol, word, paint: tint } = MARKS[mark];
293
- const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
517
+ let head = MARK_WORDS[mark];
518
+ if (takesControlCodes(stream, env)) {
519
+ const { theme } = activeTheme();
520
+ head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
521
+ }
294
522
  return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
295
523
  }
296
524
  function warn(text, detail) {
297
- console.error(marked("warn", text, process2.stderr, detail));
298
- }
299
- var STATUSES = {
300
- passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
301
- failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
302
- running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
303
- queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
304
- skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
525
+ console.error(marked("warn", text, process6.stderr, detail));
526
+ }
527
+ var STATUS_WORDS = {
528
+ passed: ["passed", "success", "succeeded", "ok"],
529
+ failed: ["failed", "failure", "error", "errored"],
530
+ running: ["running", "in_progress", "started", "holding"],
531
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
532
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
305
533
  };
306
- var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
534
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
307
535
 
308
536
  // ../kit/src/format.ts
309
537
  function upTo(text, separator) {
@@ -318,15 +546,18 @@ var ESCAPE = String.fromCharCode(27);
318
546
  function textWidth(text) {
319
547
  return Bun.stringWidth(text);
320
548
  }
321
- function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
549
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
322
550
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
551
+ if (outputMode(stream, env) === "agent")
552
+ return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
553
+ `);
323
554
  const widths = [];
324
555
  for (const row of cells) {
325
556
  for (const [index, cell] of row.entries())
326
557
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
327
558
  }
328
559
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
329
- const colors = paint(process3.stdout);
560
+ const colors = paint(stream);
330
561
  const lines = shown.map((row) => row.map((cell, index) => {
331
562
  const width = widths[index] ?? 0;
332
563
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -334,7 +565,8 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
334
565
  return `${gap}${cell}`;
335
566
  return index === row.length - 1 ? cell : `${cell}${gap}`;
336
567
  }).join(" ").trimEnd());
337
- return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
568
+ const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
569
+ return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
338
570
  `);
339
571
  }
340
572
  function narrow(rows, widths, limit) {
@@ -353,29 +585,32 @@ function narrow(rows, widths, limit) {
353
585
  }
354
586
  return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
355
587
  }
588
+ function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
589
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
590
+ }
356
591
 
357
592
  // ../kit/src/help.ts
358
- import process4 from "process";
593
+ import process8 from "process";
359
594
  var OPTIONAL = /\[[^\]]+\]/g;
360
595
  var USAGE_PREFIX = /^usage:\s*/i;
361
596
  var FULL_STOP = /\.$/;
362
- function usageLine(usage, colors = paint(process4.stdout)) {
597
+ function usageLine(usage, colors = paint(process8.stdout)) {
363
598
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
364
599
  }
365
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
600
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
366
601
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
367
602
  `);
368
603
  }
369
- function exitRows(exits, colors = paint(process4.stdout)) {
604
+ function exitRows(exits, colors = paint(process8.stdout)) {
370
605
  if (exits.length === 0)
371
606
  return [];
372
607
  const width = Math.max(...exits.map(([code]) => String(code).length));
373
608
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
374
609
  }
375
- function replacesRows(replaces, colors = paint(process4.stdout)) {
376
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
610
+ function replacesRows(replaces, colors = paint(process8.stdout)) {
611
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
377
612
  }
378
- function wantsHelpJson(env = process4.env) {
613
+ function wantsHelpJson(env = process8.env) {
379
614
  return env.KIT_HELP === "json";
380
615
  }
381
616
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -394,12 +629,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
394
629
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
395
630
  };
396
631
  }
397
- function exampleRows(examples, colors = paint(process4.stdout)) {
398
- if (examples.length === 0)
632
+ function exampleRows(examples, colors = paint(process8.stdout)) {
633
+ if (examples.length === 0 || outputMode() === "agent")
399
634
  return [];
400
635
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
401
636
  }
402
- function optionRows(options, colors = paint(process4.stdout)) {
637
+ function optionRows(options, colors = paint(process8.stdout)) {
403
638
  const rows = Object.entries(options).map(([name, option]) => {
404
639
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
405
640
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -431,7 +666,7 @@ function closest(name, names) {
431
666
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
432
667
  }
433
668
  // ../kit/src/input.ts
434
- import process5 from "process";
669
+ import process9 from "process";
435
670
  var WHOLE = /^\d+$/;
436
671
  function wholeNumber(value, name, fallback, min = 1) {
437
672
  if (value === undefined)
@@ -443,7 +678,7 @@ function wholeNumber(value, name, fallback, min = 1) {
443
678
  }
444
679
  async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
445
680
  if (path === "-") {
446
- if (process5.stdin.isTTY)
681
+ if (process9.stdin.isTTY)
447
682
  fail(noStdin);
448
683
  return Bun.stdin.text();
449
684
  }
@@ -502,7 +737,7 @@ var OUTPUT_OPTIONS = {
502
737
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
503
738
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
504
739
  };
505
- function applyOutput(color, plain, env = process6.env) {
740
+ function applyOutput(color, plain, env = process10.env) {
506
741
  const when = plain === true ? "never" : color ?? "auto";
507
742
  if (when === "auto")
508
743
  return;
@@ -673,7 +908,7 @@ function nearestOption(message, options, allowNegative) {
673
908
  }
674
909
  // ../kit/src/process.ts
675
910
  import { constants } from "os";
676
- import process7 from "process";
911
+ import process11 from "process";
677
912
  var KILL_GRACE_MS = 2000;
678
913
  function exitCodeOf(code, signal) {
679
914
  if (code !== null)
@@ -693,7 +928,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
693
928
  return;
694
929
  try {
695
930
  if (grouped)
696
- process7.kill(-proc.pid, killing);
931
+ process11.kill(-proc.pid, killing);
697
932
  else
698
933
  proc.kill(killing);
699
934
  } catch {}
@@ -767,15 +1002,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
767
1002
  var RESET_STYLE = `${ESC}[0m`;
768
1003
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
769
1004
  // ../kit/src/cli.ts
770
- import { readFileSync, realpathSync } from "fs";
771
- import { dirname as dirname2, join as join2 } from "path";
772
- import process9 from "process";
1005
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
1006
+ import { dirname as dirname3, join as join5 } from "path";
1007
+ import process13 from "process";
773
1008
 
774
1009
  // ../kit/src/usage.ts
775
1010
  import { appendFileSync, mkdirSync } from "fs";
776
- import { homedir } from "os";
777
- import { dirname, isAbsolute, join } from "path";
778
- import process8 from "process";
1011
+ import { homedir as homedir3 } from "os";
1012
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1013
+ import process12 from "process";
779
1014
 
780
1015
  // ../kit/src/logs.ts
781
1016
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -789,14 +1024,14 @@ var usageError;
789
1024
  function noteUsageError(message) {
790
1025
  usageError = message;
791
1026
  }
792
- function stateHome(env = process8.env) {
1027
+ function stateHome(env = process12.env) {
793
1028
  const dir = env.XDG_STATE_HOME;
794
- return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
1029
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
795
1030
  }
796
- function usagePath(env = process8.env) {
797
- return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
1031
+ function usagePath(env = process12.env) {
1032
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
798
1033
  }
799
- function usageRecorded(env = process8.env) {
1034
+ function usageRecorded(env = process12.env) {
800
1035
  const off = env.KAYNOOO_CLI_NO_USAGE;
801
1036
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
802
1037
  }
@@ -810,12 +1045,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
810
1045
  usageError = undefined;
811
1046
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
812
1047
  }
813
- function recordUsage(entry, env = process8.env) {
1048
+ function recordUsage(entry, env = process12.env) {
814
1049
  if (!usageRecorded(env))
815
1050
  return;
816
1051
  try {
817
1052
  const path = usagePath(env);
818
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
1053
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
819
1054
  appendFileSync(path, `${JSON.stringify(entry)}
820
1055
  `, { mode: 384 });
821
1056
  } catch {}
@@ -901,8 +1136,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
901
1136
  `);
902
1137
  }
903
1138
  function printError(prefix, message, hint, cause) {
904
- const colors = paint(process9.stderr);
905
- const styled = takesControlCodes(process9.stderr);
1139
+ const colors = paint(process13.stderr);
1140
+ const styled = takesControlCodes(process13.stderr);
906
1141
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
907
1142
  const under = (label, text, tint) => text === undefined ? "" : `
908
1143
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -921,7 +1156,7 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
921
1156
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
922
1157
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
923
1158
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
924
- if (error instanceof UsageError)
1159
+ if (error instanceof Exit && error.code === 2)
925
1160
  noteUsageError(error.message);
926
1161
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
927
1162
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
@@ -945,11 +1180,11 @@ async function dispatch(level, typed, { version, redact }) {
945
1180
  }
946
1181
  }
947
1182
  if (name === undefined && level.path.length > 1) {
948
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
1183
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
949
1184
  return 2;
950
1185
  }
951
1186
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
952
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
1187
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
953
1188
  return 0;
954
1189
  }
955
1190
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1066,17 +1301,17 @@ async function printCandidates(found) {
1066
1301
  return 0;
1067
1302
  }
1068
1303
  function packageVersion(entry = Bun.main) {
1069
- for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1304
+ for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1070
1305
  try {
1071
- const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
1306
+ const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
1072
1307
  if (typeof version === "string")
1073
1308
  return version;
1074
1309
  } catch {}
1075
- if (dirname2(dir) === dir)
1310
+ if (dirname3(dir) === dir)
1076
1311
  return "0.0.0";
1077
1312
  }
1078
1313
  }
1079
- async function runCli(cli, argv = process9.argv.slice(2)) {
1314
+ async function runCli(cli, argv = process13.argv.slice(2)) {
1080
1315
  const version = cli.version ?? packageVersion();
1081
1316
  if (argv[0] === COMPLETE)
1082
1317
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -1130,25 +1365,6 @@ function isSecretName(name) {
1130
1365
  var {Glob } = globalThis.Bun;
1131
1366
  var SESSION_FILES = new Glob("*.json");
1132
1367
  var ACCOUNT_DIRS = new Glob("*/sessions");
1133
- // ../kit/src/user-config.ts
1134
- import { existsSync } from "fs";
1135
- import { homedir as homedir2 } from "os";
1136
- import { join as join3 } from "path";
1137
- import process10 from "process";
1138
- function configBase(where = {}) {
1139
- const xdg = where.xdg ?? (where.home === undefined ? process10.env.XDG_CONFIG_HOME : undefined);
1140
- return xdg !== undefined && xdg !== "" ? xdg : join3(where.home ?? homedir2(), ".config");
1141
- }
1142
- function userConfigPath(bin, where = {}) {
1143
- return join3(configBase(where), "kaynooo-cli", `${bin}.json`);
1144
- }
1145
- function userConfigReadPath(bin, legacy = [], where = {}) {
1146
- const current = userConfigPath(bin, where);
1147
- if (existsSync(current))
1148
- return current;
1149
- const base = configBase(where);
1150
- return legacy.map((parts) => join3(base, ...parts)).find((path) => existsSync(path)) ?? current;
1151
- }
1152
1368
  // src/args.ts
1153
1369
  var DEFAULT_ENV = "DATABASE_URL";
1154
1370
  var DEFAULT_LIMIT = 20;
@@ -1515,7 +1731,7 @@ function shape(rows, limit, raw, exact = true) {
1515
1731
  }
1516
1732
  function render(shown, json) {
1517
1733
  if (json)
1518
- return JSON.stringify({ columns: shown.columns, rows: shown.rows, ...shown.exact ? { total: shown.total, omitted: shown.omitted } : {}, truncated: shown.truncated, masked: shown.masked }, jsonValue, 2);
1734
+ return jsonText({ columns: shown.columns, rows: shown.rows, ...shown.exact ? { total: shown.total, omitted: shown.omitted } : {}, truncated: shown.truncated, masked: shown.masked }, jsonValue);
1519
1735
  if (shown.total === 0)
1520
1736
  return "no rows";
1521
1737
  const lines = [table([
@@ -1534,7 +1750,7 @@ function render(shown, json) {
1534
1750
 
1535
1751
  // src/run.ts
1536
1752
  import { isIP } from "net";
1537
- import process12 from "process";
1753
+ import process15 from "process";
1538
1754
  var {SQL } = globalThis.Bun;
1539
1755
 
1540
1756
  // src/compose.ts
@@ -1789,7 +2005,7 @@ async function connectionUrl({ env, service, container, database }, home) {
1789
2005
  if (service !== undefined && container !== undefined)
1790
2006
  fail("--service and --container name two databases: pick one");
1791
2007
  const isNamed = service !== undefined || container !== undefined;
1792
- const value = isNamed ? undefined : process12.env[env ?? DEFAULT_ENV];
2008
+ const value = isNamed ? undefined : process15.env[env ?? DEFAULT_ENV];
1793
2009
  let url;
1794
2010
  if (value !== undefined && value !== "")
1795
2011
  url = await reachable(value, home);
@@ -1985,7 +2201,7 @@ async function query(args) {
1985
2201
  return handBack(sql, verdict.reasons, databaseOfUrl(url).endsWith(TEST_SUFFIX) ? `; not run on this ${TEST_SUFFIX} database either: ${written.reasons.join("; ")}` : "");
1986
2202
  const shown = shape(written.rows, limit, values.raw === true, false);
1987
2203
  if (values.json === true)
1988
- console.log(JSON.stringify({ database: written.database, affected: written.affected, columns: shown.columns, rows: shown.rows, truncated: shown.truncated, masked: shown.masked }, jsonValue, 2));
2204
+ console.log(jsonText({ database: written.database, affected: written.affected, columns: shown.columns, rows: shown.rows, truncated: shown.truncated, masked: shown.masked }, jsonValue));
1989
2205
  else
1990
2206
  console.log(`ran on ${written.database}, ${written.affected} ${written.affected === 1 ? "row" : "rows"} affected${written.rows.length === 0 ? "" : `
1991
2207
  ${render(shown, false)}`}`);
@@ -2190,7 +2406,7 @@ ${HOSTS_NOTE}`;
2190
2406
  const indexes = await ask(plans.indexes);
2191
2407
  const foreignKeys = await ask(plans.foreignKeys);
2192
2408
  if (values.json === true)
2193
- console.log(JSON.stringify({ columns: columns.columns, rows: columns.rows, truncated: columns.truncated, masked: columns.masked, indexes, foreignKeys }, jsonValue, 2));
2409
+ console.log(jsonText({ columns: columns.columns, rows: columns.rows, truncated: columns.truncated, masked: columns.masked, indexes, foreignKeys }, jsonValue));
2194
2410
  else
2195
2411
  console.log(`${render(columns, false)}
2196
2412
 
@@ -2253,7 +2469,7 @@ ${HOSTS_NOTE}`, countOptions, (target, dialect, { where }) => countSql(target, d
2253
2469
  }
2254
2470
 
2255
2471
  // src/cli.ts
2256
- process13.exitCode = await runCli({
2472
+ process16.exitCode = await runCli({
2257
2473
  name: "db",
2258
2474
  about: "read-only SQL against Postgres, MySQL and MariaDB, credentials never shown, writes only on a _test database",
2259
2475
  replaces: "psql or mysql with the connection string on the command line, docker exec <container> psql -U ...",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-db",
3
3
  "type": "module",
4
- "version": "0.10.0",
4
+ "version": "0.11.0",
5
5
  "description": "db: run read-only SQL against Postgres, MySQL and MariaDB from the terminal without ever showing the connection credentials.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -28,6 +28,6 @@
28
28
  "db": "$npm_execpath src/cli.ts"
29
29
  },
30
30
  "devDependencies": {
31
- "@kaynooo/cli-kit": "0.20.0"
31
+ "@kaynooo/cli-kit": "0.22.0"
32
32
  }
33
33
  }