@kaynooo/cli-db 0.13.0 → 0.13.3

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 (3) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +422 -151
  3. package/package.json +5 -5
package/README.md CHANGED
@@ -36,7 +36,7 @@ Options: `-n <rows>` (`--rows`, once `--limit`) caps the rows shown (20) and say
36
36
  - Postgres: the session opens with `default_transaction_read_only=on`, `lock_timeout=5s` and `idle_in_transaction_session_timeout=60s`, then the statement runs after `SET LOCAL statement_timeout = '30s'` (`--timeout` changes it) in `BEGIN READ ONLY`, and the transaction is rolled back, so Postgres itself refuses a write the checks below miss. The transaction does not stop side effects outside it (`pg_terminate_backend`, `COPY ... TO PROGRAM`, `dblink`), which the checks below do.
37
37
  - MySQL and MariaDB: the statement runs in `START TRANSACTION READ ONLY` on one reserved connection, under a 30 second statement timeout (`--timeout` changes it) (`max_execution_time`, or `max_statement_time` on MariaDB), and the transaction is rolled back. A select is wrapped in `select * from (...) limit n + 1` to stop one row past `-n`, and read whole only when the wrapping does not parse or repeats a column name (errors 1064 and 1060); any other error is reported as is.
38
38
  - A Postgres select is read through a cursor that stops at one row past `-n`, so a huge table is never loaded whole.
39
- - Before running, the SQL is tokenized the way its engine reads it (Postgres: nested comments, dollar-quoted bodies, `E'...'` escapes; MySQL: `#` comments, `--` only before a blank, backslash escapes, double quotes as strings, comments that do not nest, `/*! ... */` and `/*M! ... */` run). A quoted identifier is read as a name, so `"nextval"('s')` is caught, and a NUL byte or a `U&"..."` identifier is refused. The allowed starts, the refused keywords and the refused functions are in `db query --help`.
39
+ - Before running, the SQL is tokenized the way its engine reads it (Postgres: nested comments, dollar-quoted bodies, `E'...'` escapes; MySQL: `#` comments, `--` only before a blank, backslash escapes, double quotes as strings, comments that do not nest, `/*! ... */` and `/*M! ... */` run). A quoted identifier is read as a name, so `"nextval"('s')` is caught, and a NUL byte or a `U&"..."` identifier is refused. The statement must start with `SELECT`, `WITH`, `VALUES`, `TABLE`, `SHOW`, `EXPLAIN`, `DESCRIBE` or `DESC` and use no `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `INTO`, `SET` or `FOR UPDATE` anywhere (a write hidden in a CTE is caught), nor a function with side effects (`nextval`, `setval`, `set_config`, `pg_terminate_backend`, `pg_sleep`, `dblink`, `sleep`, `load_file`...).
40
40
  - Such a statement is printed as a `sql` block with the reasons and `db` exits 1 without running it. Several statements in one string are refused (exit 2) even when each reads: one statement at a time.
41
41
  - Columns named like emails, phones, tokens, secrets, passwords or hashes show `***` unless `--raw` (`NULL` stays `NULL`), and every message, errors included, is scrubbed of the URL and the password (raw and decoded).
42
42
 
package/dist/cli.js CHANGED
@@ -1,20 +1,19 @@
1
1
  #!/usr/bin/env -S bun --config=/dev/null
2
2
  // @bun
3
+ var __esm = (fn, res, err) => () => {
4
+ if (fn)
5
+ try {
6
+ res = fn(fn = 0);
7
+ } catch (e) {
8
+ err = [e];
9
+ }
10
+ if (err)
11
+ throw err[0];
12
+ return res;
13
+ };
3
14
 
4
- // src/cli.ts
5
- import process18 from "process";
6
- // ../kit/src/args.ts
7
- import process10 from "process";
8
- import { parseArgs } from "util";
9
-
10
- // ../kit/src/format.ts
11
- import process7 from "process";
12
-
13
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
14
- var N = new Map;
15
- var Nt = /\s+\S*$/;
16
- var Y = /\s/;
17
- function ko(t, e, r = "...") {
15
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
16
+ function Ao(t, e, r = "...") {
18
17
  let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
19
18
  if (t.length <= e)
20
19
  return t;
@@ -25,13 +24,22 @@ function ko(t, e, r = "...") {
25
24
  c = c.trimEnd();
26
25
  return s ? (c + n).slice(0, l) : c + n;
27
26
  }
28
- 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));
29
- var z = new Map;
27
+ var N, Nt, Y, be, W;
28
+ var init_chunk_rkhsft4a = __esm(() => {
29
+ N = new Map;
30
+ Nt = /\s+\S*$/;
31
+ Y = /\s/;
32
+ 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));
33
+ W = new Map;
34
+ });
35
+
36
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
37
+ var init_text = __esm(() => {
38
+ init_chunk_rkhsft4a();
39
+ });
30
40
 
31
41
  // ../kit/src/mode.ts
32
42
  import process2 from "process";
33
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
34
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
35
43
  function isSet(value) {
36
44
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
37
45
  }
@@ -45,12 +53,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
45
53
  return "terminal";
46
54
  return isSet(env.CI) ? "ci" : "pipe";
47
55
  }
56
+ var MODES, AGENT_VARIABLES;
57
+ var init_mode = __esm(() => {
58
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
59
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
60
+ });
48
61
 
49
- // ../kit/src/style.ts
50
- import process6 from "process";
51
-
52
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
53
- var G2 = /^[a-f0-9]+$/i;
62
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
54
63
  function b(r) {
55
64
  let e = r.startsWith("#") ? r.slice(1) : r;
56
65
  if (!G2.test(e))
@@ -61,11 +70,6 @@ function b(r) {
61
70
  throw Error(`Invalid hex color length: ${e.length}`);
62
71
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
63
72
  }
64
- var B2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
65
- let [l, n, c] = b(r);
66
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
67
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
68
- var h = new Set(["", "1", "2", "3", "true"]);
69
73
  function C(r, e = globalThis.process?.env ?? {}) {
70
74
  if (e.FORCE_COLOR !== undefined)
71
75
  return h.has(e.FORCE_COLOR);
@@ -79,7 +83,7 @@ function f(r, e = []) {
79
83
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
80
84
  let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
81
85
  return new Proxy(c, { get(t, i) {
82
- let a = B2[i];
86
+ let a = B[i];
83
87
  if (Array.isArray(a)) {
84
88
  let s = g.get(i);
85
89
  if (s === undefined)
@@ -102,13 +106,21 @@ function f(r, e = []) {
102
106
  function Fe(r = {}) {
103
107
  return f(r);
104
108
  }
105
- var o = Fe();
109
+ var G2, B, h, o;
110
+ var init_chunk_x450vn3m = __esm(() => {
111
+ G2 = /^[a-f0-9]+$/i;
112
+ B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
113
+ let [l, n, c] = b(r);
114
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
115
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
116
+ h = new Set(["", "1", "2", "3", "true"]);
117
+ o = Fe();
118
+ });
106
119
 
107
- // ../kit/src/theme.ts
108
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
109
- import { homedir as homedir2 } from "os";
110
- import { join as join3, resolve as resolve2 } from "path";
111
- import process5 from "process";
120
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
121
+ var init_colors = __esm(() => {
122
+ init_chunk_x450vn3m();
123
+ });
112
124
 
113
125
  // ../kit/src/config.ts
114
126
  import { existsSync } from "fs";
@@ -124,6 +136,9 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
124
136
  return;
125
137
  }
126
138
  }
139
+ var init_config = __esm(() => {
140
+ init_args();
141
+ });
127
142
 
128
143
  // ../kit/src/user-config.ts
129
144
  import { existsSync as existsSync2, readFileSync } from "fs";
@@ -144,36 +159,18 @@ function userConfigReadPath(bin, legacy = [], where = {}) {
144
159
  const base = configBase(where);
145
160
  return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
146
161
  }
162
+ var init_user_config = () => {};
147
163
 
148
164
  // ../kit/src/theme.ts
149
- var ENDS = new Map;
150
- var DEFAULT = {
151
- 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" },
152
- 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" },
153
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
154
- bins: {},
155
- gradient: ["#c084fc", "#67e8f9"]
156
- };
157
- 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" };
158
- 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" };
159
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
160
- var PRESETS = {
161
- default: {},
162
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
163
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
164
- ascii: { glyphs: ASCII }
165
- };
166
- 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"]);
167
- var HEX = /^#[0-9a-f]{6}$/i;
168
- var CONTROL = /\p{Cc}/u;
169
- var MAX_FILE_BYTES = 64 * 1024;
170
- var SPACES = /\s+/;
165
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
166
+ import { homedir as homedir2 } from "os";
167
+ import { join as join3, resolve as resolve2 } from "path";
168
+ import process5 from "process";
171
169
  function isColorSpec(spec) {
172
170
  if (typeof spec === "number")
173
171
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
174
172
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
175
173
  }
176
- var CUBE = [0, 95, 135, 175, 215, 255];
177
174
  function cubeLevel(channel) {
178
175
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
179
176
  }
@@ -278,7 +275,6 @@ function applyFile(theme, file, where, warn) {
278
275
  function endsWalk(home) {
279
276
  return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
280
277
  }
281
- var warned = new Set;
282
278
  function warnOnce(message) {
283
279
  if (warned.has(message))
284
280
  return;
@@ -315,8 +311,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
315
311
  }
316
312
  return { theme, sources, preset };
317
313
  }
318
- var current;
319
- var currentKey = "";
320
314
  function activeTheme() {
321
315
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
322
316
  if (current === undefined || key !== currentKey) {
@@ -325,9 +319,38 @@ function activeTheme() {
325
319
  }
326
320
  return current;
327
321
  }
322
+ var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
323
+ var init_theme = __esm(() => {
324
+ init_config();
325
+ init_user_config();
326
+ ENDS = new Map;
327
+ DEFAULT = {
328
+ 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" },
329
+ 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" },
330
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
331
+ bins: {},
332
+ gradient: ["#c084fc", "#67e8f9"]
333
+ };
334
+ 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" };
335
+ 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" };
336
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
337
+ PRESETS = {
338
+ default: {},
339
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
340
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
341
+ ascii: { glyphs: ASCII }
342
+ };
343
+ 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"]);
344
+ HEX = /^#[0-9a-f]{6}$/i;
345
+ CONTROL = /\p{Cc}/u;
346
+ MAX_FILE_BYTES = 64 * 1024;
347
+ SPACES = /\s+/;
348
+ CUBE = [0, 95, 135, 175, 215, 255];
349
+ warned = new Set;
350
+ });
328
351
 
329
352
  // ../kit/src/style.ts
330
- var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
353
+ import process6 from "process";
331
354
  function takesControlCodes(stream, env = process6.env) {
332
355
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
333
356
  }
@@ -349,17 +372,24 @@ function warn(text, detail) {
349
372
  function problem(text, detail) {
350
373
  console.error(marked("problem", text, process6.stderr, detail));
351
374
  }
352
- var STATUS_WORDS = {
353
- passed: ["passed", "success", "succeeded", "ok"],
354
- failed: ["failed", "failure", "error", "errored"],
355
- running: ["running", "in_progress", "started", "holding"],
356
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
357
- skipped: ["skipped", "cancelled", "canceled", "manual"]
358
- };
359
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
375
+ var MARK_WORDS, STATUS_WORDS, STATUS_OF;
376
+ var init_style = __esm(() => {
377
+ init_colors();
378
+ init_mode();
379
+ init_theme();
380
+ MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
381
+ STATUS_WORDS = {
382
+ passed: ["passed", "success", "succeeded", "ok"],
383
+ failed: ["failed", "failure", "error", "errored"],
384
+ running: ["running", "in_progress", "started", "holding"],
385
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
386
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
387
+ };
388
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
389
+ });
360
390
 
361
391
  // ../kit/src/format.ts
362
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
392
+ import process7 from "process";
363
393
  function formatSeconds(total) {
364
394
  let rest = Math.max(0, Math.round(total));
365
395
  const amounts = UNITS.map(([unit, size]) => {
@@ -381,10 +411,8 @@ function upTo(text, separator) {
381
411
  return end === -1 ? text : text.slice(0, end);
382
412
  }
383
413
  function truncate(text, width) {
384
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
414
+ return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
385
415
  }
386
- var LINE_BREAKS = /\s*\n\s*/g;
387
- var ESCAPE = String.fromCharCode(27);
388
416
  function textWidth(text) {
389
417
  return Bun.stringWidth(text);
390
418
  }
@@ -430,14 +458,40 @@ function narrow(rows, widths, limit) {
430
458
  function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
431
459
  return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
432
460
  }
461
+ var UNITS, LINE_BREAKS, ESCAPE;
462
+ var init_format = __esm(() => {
463
+ init_text();
464
+ init_mode();
465
+ init_style();
466
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
467
+ LINE_BREAKS = /\s*\n\s*/g;
468
+ ESCAPE = String.fromCharCode(27);
469
+ });
433
470
 
434
471
  // ../kit/src/help.ts
435
472
  import process8 from "process";
436
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
437
- var USAGE_PREFIX = /^usage:\s*/i;
438
- var FULL_STOP = /\.$/;
439
473
  function usageLine(usage, colors = paint(process8.stdout)) {
440
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
474
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
475
+ `);
476
+ const blank = lines.indexOf("");
477
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
478
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
479
+ const colon = synopses[0].indexOf(": ");
480
+ const inline = synopses[0].slice(colon + 2);
481
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
482
+ if (colon !== -1)
483
+ synopses[0] = synopses[0].slice(0, colon);
484
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
485
+ `)}`;
486
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
487
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
488
+ return [head, ...lead, ...rest].join(`
489
+ `);
490
+ }
491
+ function prose(line, colors) {
492
+ if (colors.cyan("x") === "x")
493
+ return line;
494
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
441
495
  }
442
496
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
443
497
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -472,7 +526,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
472
526
  return [];
473
527
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
474
528
  }
475
- var MAX_INLINE_CHOICES = 24;
476
529
  function optionRows(options, colors = paint(process8.stdout)) {
477
530
  const rows = Object.entries(options).map(([name, option]) => {
478
531
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -487,6 +540,15 @@ function optionRows(options, colors = paint(process8.stdout)) {
487
540
  const width = Math.max(0, ...rows.map((row) => row.width));
488
541
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
489
542
  }
543
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
544
+ var init_help = __esm(() => {
545
+ init_mode();
546
+ init_style();
547
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
548
+ USAGE_PREFIX = /^usage:\s*/i;
549
+ FULL_STOP = /\.$/;
550
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
551
+ });
490
552
 
491
553
  // ../kit/src/text.ts
492
554
  function distance(a, b) {
@@ -514,9 +576,10 @@ function closest(name, names) {
514
576
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
515
577
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
516
578
  }
579
+ var init_text2 = () => {};
580
+
517
581
  // ../kit/src/input.ts
518
582
  import process9 from "process";
519
- var WHOLE = /^\d+$/;
520
583
  function wholeNumber(value, name, fallback, min = 1) {
521
584
  if (value === undefined)
522
585
  return fallback;
@@ -525,8 +588,6 @@ function wholeNumber(value, name, fallback, min = 1) {
525
588
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
526
589
  return number;
527
590
  }
528
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
529
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
530
591
  function duration(value, name, fallback, unit = "s") {
531
592
  if (value === undefined)
532
593
  return fallback;
@@ -547,40 +608,27 @@ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
547
608
  fail(`no file ${path}`);
548
609
  return file.text();
549
610
  }
611
+ var WHOLE, DURATION, UNIT_MS;
612
+ var init_input = __esm(() => {
613
+ init_args();
614
+ WHOLE = /^\d+$/;
615
+ DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
616
+ UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
617
+ });
550
618
 
551
619
  // ../kit/src/args.ts
552
- var DASHES = /^-+/;
620
+ import process10 from "process";
621
+ import { parseArgs } from "util";
553
622
  function jsonOption(holds) {
554
623
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
555
624
  }
556
- class Exit extends Error {
557
- code;
558
- hint;
559
- constructor(message, code, hint) {
560
- super(message);
561
- this.code = code;
562
- this.hint = hint;
563
- }
564
- }
565
625
  function fail(message, code = 2, hint) {
566
626
  throw new Exit(message, code, hint);
567
627
  }
568
-
569
- class UsageError extends Exit {
570
- constructor(message, hint) {
571
- super(message, 2, hint);
572
- }
573
- }
574
628
  function badUsage(message) {
575
629
  throw new UsageError(message);
576
630
  }
577
631
 
578
- class HelpShown extends Exit {
579
- constructor() {
580
- super("help shown", 0);
581
- }
582
- }
583
-
584
632
  class Completing {
585
633
  options;
586
634
  positionals;
@@ -591,11 +639,6 @@ class Completing {
591
639
  this.candidates = candidates;
592
640
  }
593
641
  }
594
- var completion = { active: false };
595
- var OUTPUT_OPTIONS = {
596
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
597
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
598
- };
599
642
  function applyOutput(color, plain, env = process10.env) {
600
643
  const when = plain === true ? "never" : color ?? "auto";
601
644
  if (when === "auto")
@@ -749,7 +792,6 @@ function parseError(error) {
749
792
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
750
793
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
751
794
  }
752
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
753
795
  function nearestOption(message, options, allowNegative) {
754
796
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
755
797
  if (typed === undefined)
@@ -765,6 +807,61 @@ function nearestOption(message, options, allowNegative) {
765
807
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
766
808
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
767
809
  }
810
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
811
+ var init_args = __esm(() => {
812
+ init_format();
813
+ init_help();
814
+ init_text2();
815
+ init_help();
816
+ init_input();
817
+ DASHES = /^-+/;
818
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
819
+ Exit = class Exit extends Error {
820
+ code;
821
+ hint;
822
+ [EXIT] = true;
823
+ constructor(message, code, hint) {
824
+ super(message);
825
+ this.code = code;
826
+ this.hint = hint;
827
+ }
828
+ static [Symbol.hasInstance](value) {
829
+ if (this !== Exit)
830
+ return Function.prototype[Symbol.hasInstance].call(this, value);
831
+ return typeof value === "object" && value !== null && value[EXIT] === true;
832
+ }
833
+ };
834
+ UsageError = class UsageError extends Exit {
835
+ constructor(message, hint) {
836
+ super(message, 2, hint);
837
+ }
838
+ };
839
+ HelpShown = class HelpShown extends Exit {
840
+ constructor() {
841
+ super("help shown", 0);
842
+ }
843
+ };
844
+ completion = { active: false };
845
+ OUTPUT_OPTIONS = {
846
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
847
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
848
+ };
849
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
850
+ });
851
+
852
+ // ../kit/src/folders.ts
853
+ var SKIPPED_FOLDERS;
854
+ var init_folders = __esm(() => {
855
+ init_user_config();
856
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
857
+ });
858
+
859
+ // src/cli.ts
860
+ import process19 from "process";
861
+
862
+ // ../kit/src/index.ts
863
+ init_args();
864
+
768
865
  // ../kit/src/argv.ts
769
866
  import { readFileSync as readFileSync3, realpathSync } from "fs";
770
867
  import { resolve as resolve3 } from "path";
@@ -789,6 +886,18 @@ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), scr
789
886
  const after = at === -1 ? [] : cmdline.slice(at + 1);
790
887
  return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
791
888
  }
889
+ // ../kit/src/chart.ts
890
+ init_format();
891
+ init_mode();
892
+ init_style();
893
+ init_theme();
894
+ // ../kit/src/ci.ts
895
+ init_args();
896
+ init_format();
897
+
898
+ // ../kit/src/progress.ts
899
+ init_format();
900
+
792
901
  // ../kit/src/process.ts
793
902
  import { constants } from "os";
794
903
  import process12 from "process";
@@ -800,10 +909,10 @@ function exitCodeOf(code, signal) {
800
909
  return 128 + signal;
801
910
  return signal === null ? 129 : 128 + constants.signals[signal];
802
911
  }
803
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
912
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
804
913
  const chunks = [];
805
914
  const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
806
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
915
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin: input === undefined ? stdin : new TextEncoder().encode(input), stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
807
916
  const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
808
917
  const timers = [];
809
918
  const killGroup = (killing) => {
@@ -880,38 +989,152 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
880
989
  }
881
990
 
882
991
  // ../kit/src/progress.ts
992
+ init_style();
993
+ init_theme();
883
994
  var ESC = String.fromCharCode(27);
884
995
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
885
996
  var RESET_STYLE = `${ESC}[0m`;
886
997
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
998
+
999
+ // ../kit/src/ci.ts
1000
+ init_style();
1001
+
1002
+ // ../kit/src/tool.ts
1003
+ init_format();
887
1004
  // ../kit/src/cli.ts
1005
+ init_args();
888
1006
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
889
1007
  import { dirname as dirname3, join as join5 } from "path";
890
- import process15 from "process";
1008
+ import process16 from "process";
891
1009
 
892
- // ../kit/src/notify.ts
1010
+ // ../kit/src/askpass.ts
893
1011
  import process13 from "process";
1012
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1013
+ async function askpassClient(argv) {
1014
+ const socketPath = process13.env[SOCKET_VARIABLE];
1015
+ if (socketPath === undefined)
1016
+ return;
1017
+ const request = { prompt: argv[0] ?? "", ...process13.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1018
+ const { promise, resolve } = Promise.withResolvers();
1019
+ let received = "";
1020
+ try {
1021
+ await Bun.connect({
1022
+ unix: socketPath,
1023
+ socket: {
1024
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1025
+ `),
1026
+ data: (_, chunk) => {
1027
+ received += chunk.toString();
1028
+ },
1029
+ close: () => resolve(received),
1030
+ error: () => resolve("")
1031
+ }
1032
+ });
1033
+ } catch {
1034
+ return 1;
1035
+ }
1036
+ const reply = await promise;
1037
+ if (reply === "")
1038
+ return 1;
1039
+ const { answer } = JSON.parse(reply);
1040
+ if (request.notice === true)
1041
+ return 0;
1042
+ if (answer === undefined)
1043
+ return 1;
1044
+ process13.stdout.write(`${answer}
1045
+ `);
1046
+ return 0;
1047
+ }
1048
+
1049
+ // ../kit/src/completions.ts
1050
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1051
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
1052
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1053
+ set -l current (commandline -ct)
1054
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1055
+ if test "$line" = __files__
1056
+ __fish_complete_path $current
1057
+ else
1058
+ echo $line
1059
+ end
1060
+ end
1061
+ end`;
1062
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1063
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1064
+ local -a lines
1065
+ COMPREPLY=()
1066
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1067
+ for line in "\${lines[@]}"; do
1068
+ if [[ $line == __files__ ]]; then
1069
+ COMPREPLY+=($(compgen -f -- "$cur"))
1070
+ else
1071
+ words+="\${line%%$'\\t'*}"$'\\n'
1072
+ fi
1073
+ done
1074
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1075
+ }`;
1076
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1077
+ local line
1078
+ local -a described plain
1079
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1080
+ if [[ $line == __files__ ]]; then
1081
+ _files
1082
+ elif [[ $line == *$'\\t'* ]]; then
1083
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1084
+ else
1085
+ plain+=("$line")
1086
+ fi
1087
+ done
1088
+ (( \${#described} )) && _describe -V value described
1089
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1090
+ return 0
1091
+ }`;
1092
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1093
+ if (shell === "fish")
1094
+ return `${header}
1095
+ ${FISH_FUNCTION}
1096
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1097
+ `).join("")}`;
1098
+ if (shell === "bash")
1099
+ return `${header}
1100
+ ${BASH_FUNCTION}
1101
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1102
+ `;
1103
+ return `${header}
1104
+ ${ZSH_FUNCTION}
1105
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1106
+ `;
1107
+ }
1108
+
1109
+ // ../kit/src/notify.ts
1110
+ init_format();
1111
+ init_mode();
1112
+ import process14 from "process";
894
1113
  var NOTIFY_AFTER_MS = 1e4;
895
1114
  var CANCELLED = 130;
896
1115
  function base64(text) {
897
1116
  return Buffer.from(text).toString("base64");
898
1117
  }
899
- function notification(title, body, env = process13.env) {
900
- const id = `kit${process13.pid}`;
1118
+ function notification(title, body, env = process14.env) {
1119
+ const id = `kit${process14.pid}`;
901
1120
  const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
902
1121
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
903
1122
  }
904
- function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1123
+ function notifyEnd(command, code, ms, { stream = process14.stderr, env = process14.env } = {}) {
905
1124
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
906
1125
  return;
907
1126
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
908
1127
  }
909
1128
 
1129
+ // ../kit/src/cli.ts
1130
+ init_style();
1131
+ init_text2();
1132
+
910
1133
  // ../kit/src/usage.ts
911
1134
  import { appendFileSync, mkdirSync } from "fs";
912
1135
  import { homedir as homedir3 } from "os";
913
1136
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
914
- import process14 from "process";
1137
+ import process15 from "process";
915
1138
 
916
1139
  // ../kit/src/logs.ts
917
1140
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -925,14 +1148,14 @@ var usageError;
925
1148
  function noteUsageError(message) {
926
1149
  usageError = message;
927
1150
  }
928
- function stateHome(env = process14.env) {
1151
+ function stateHome(env = process15.env) {
929
1152
  const dir = env.XDG_STATE_HOME;
930
1153
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
931
1154
  }
932
- function usagePath(env = process14.env) {
1155
+ function usagePath(env = process15.env) {
933
1156
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
934
1157
  }
935
- function usageRecorded(env = process14.env) {
1158
+ function usageRecorded(env = process15.env) {
936
1159
  const off = env.KAYNOOO_CLI_NO_USAGE;
937
1160
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
938
1161
  }
@@ -941,12 +1164,12 @@ function flagNames(argv) {
941
1164
  const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
942
1165
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
943
1166
  }
944
- function usageEntry(bin, command, argv, code, now = new Date) {
1167
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
945
1168
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
946
1169
  usageError = undefined;
947
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1170
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
948
1171
  }
949
- function recordUsage(entry, env = process14.env) {
1172
+ function recordUsage(entry, env = process15.env) {
950
1173
  if (!usageRecorded(env))
951
1174
  return;
952
1175
  try {
@@ -962,7 +1185,11 @@ var LEVEL_OPTIONS = {
962
1185
  ...OUTPUT_OPTIONS,
963
1186
  help: { type: "boolean", short: "h", description: "show this help" }
964
1187
  };
965
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1188
+ var TOP_OPTIONS = {
1189
+ ...LEVEL_OPTIONS,
1190
+ version: { type: "boolean", short: "v", description: "print the version" },
1191
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1192
+ };
966
1193
  async function commandRows(all, colors) {
967
1194
  const commands = shown(all);
968
1195
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -1036,8 +1263,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1036
1263
  `);
1037
1264
  }
1038
1265
  function printError(prefix, message, hint, cause) {
1039
- const colors = paint(process15.stderr);
1040
- const styled = takesControlCodes(process15.stderr);
1266
+ const colors = paint(process16.stderr);
1267
+ const styled = takesControlCodes(process16.stderr);
1041
1268
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1042
1269
  const under = (label, text, tint) => text === undefined ? "" : `
1043
1270
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1080,11 +1307,11 @@ async function dispatch(level, typed, { version, redact }) {
1080
1307
  }
1081
1308
  }
1082
1309
  if (name === undefined && level.path.length > 1) {
1083
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
1310
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process16.stderr));
1084
1311
  return 2;
1085
1312
  }
1086
1313
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1087
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
1314
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process16.stdout));
1088
1315
  return 0;
1089
1316
  }
1090
1317
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1195,6 +1422,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1195
1422
  }
1196
1423
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1197
1424
  }
1425
+ var COMPLETIONS = "--completions";
1426
+ function flagValue([flag = "", ...rest]) {
1427
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1428
+ }
1429
+ function printCompletionScript(name, args) {
1430
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1431
+ if (shell === undefined || args.length !== 1) {
1432
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1433
+ return 2;
1434
+ }
1435
+ console.log(completionScript(shell, [name]).trimEnd());
1436
+ return 0;
1437
+ }
1198
1438
  async function printCandidates(found) {
1199
1439
  for (const line of await found)
1200
1440
  console.log(line);
@@ -1217,15 +1457,20 @@ function packageVersion(entry = Bun.main) {
1217
1457
  }
1218
1458
  async function runCli(cli, argv = scriptArgs()) {
1219
1459
  const version = cli.version ?? packageVersion();
1460
+ const answered = await askpassClient(argv);
1461
+ if (answered !== undefined)
1462
+ return answered;
1220
1463
  if (argv[0] === COMPLETE)
1221
1464
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1465
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1466
+ return printCompletionScript(cli.name, flagValue(argv));
1222
1467
  const started = performance.now();
1223
1468
  const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1224
1469
  const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1225
1470
  notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1226
1471
  if (cli.usage !== false) {
1227
1472
  try {
1228
- recordUsage(usageEntry(cli.name, command, argv, code));
1473
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
1229
1474
  } catch {}
1230
1475
  }
1231
1476
  return code;
@@ -1261,8 +1506,28 @@ function jsonLines(text) {
1261
1506
  return trimmed.startsWith("[") ? JSON.parse(trimmed) : trimmed.split(`
1262
1507
  `).map((line) => JSON.parse(line));
1263
1508
  }
1264
- // ../kit/src/folders.ts
1265
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1509
+
1510
+ // ../kit/src/index.ts
1511
+ init_config();
1512
+
1513
+ // ../kit/src/excerpt.ts
1514
+ init_text2();
1515
+
1516
+ // ../kit/src/index.ts
1517
+ init_folders();
1518
+ init_format();
1519
+
1520
+ // ../kit/src/git.ts
1521
+ init_args();
1522
+ // ../kit/src/limit.ts
1523
+ init_args();
1524
+
1525
+ // ../kit/src/index.ts
1526
+ init_mode();
1527
+
1528
+ // ../kit/src/report.ts
1529
+ init_style();
1530
+ init_text2();
1266
1531
  // ../kit/src/secrets.ts
1267
1532
  var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
1268
1533
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
@@ -1274,6 +1539,19 @@ function isSecretName(name) {
1274
1539
  var {Glob } = globalThis.Bun;
1275
1540
  var SESSION_FILES = new Glob("*.json");
1276
1541
  var ACCOUNT_DIRS = new Glob("*/sessions");
1542
+
1543
+ // ../kit/src/index.ts
1544
+ init_style();
1545
+ init_text2();
1546
+ init_theme();
1547
+ init_user_config();
1548
+
1549
+ // ../kit/src/watch.ts
1550
+ init_args();
1551
+ init_input();
1552
+ init_style();
1553
+ // ../kit/src/workspace-root.ts
1554
+ init_user_config();
1277
1555
  // src/args.ts
1278
1556
  var DEFAULT_ENV = "DATABASE_URL";
1279
1557
  var DEFAULT_LIMIT = 20;
@@ -1282,7 +1560,7 @@ var ALL_LIMIT = 100;
1282
1560
  var WRITE_EXIT = 1;
1283
1561
  var EXITS = [[0, "it ran"], [1, "the database refused it, was unreachable, or the statement would write and was not run"], [2, "a usage error or a host that is not allowed"]];
1284
1562
  var HOSTS_NOTE = 'db connects to a local host (localhost, 127.0.0.1, ::1) or a compose service only: any other host is refused (exit 2) unless it is listed under "allowedHosts" in ~/.config/kaynooo-cli/db.json.';
1285
- var WRITE_NOTE = "A write runs only when the database actually connected to has a name ending in _test (checked on the server, and a statement that names another database, or uses USE, SET, files or server objects, is not run); any other write is printed for you to run.";
1563
+ var WRITE_NOTE = "A write is printed for you to run (exit 1), and runs only on a database whose name ends in _test, checked on the server.";
1286
1564
  var connectionOptions = {
1287
1565
  env: { type: "string", short: "e", description: `environment key holding the connection URL (${DEFAULT_ENV}, postgres:// or mysql://), a compose service's host in it reached from here` },
1288
1566
  service: { type: "string", short: "s", description: "read the running Postgres, MySQL or MariaDB service of this name in the compose project, credentials from its environment" },
@@ -1697,7 +1975,7 @@ function render(shown, json, format) {
1697
1975
 
1698
1976
  // src/run.ts
1699
1977
  import { isIP } from "net";
1700
- import process17 from "process";
1978
+ import process18 from "process";
1701
1979
  var {SQL } = globalThis.Bun;
1702
1980
 
1703
1981
  // src/compose.ts
@@ -1951,7 +2229,7 @@ async function connectionUrl({ env, service, container, database }, home) {
1951
2229
  if (service !== undefined && container !== undefined)
1952
2230
  fail("--service and --container name two databases: pick one");
1953
2231
  const isNamed = service !== undefined || container !== undefined;
1954
- const value = isNamed ? undefined : process17.env[env ?? DEFAULT_ENV];
2232
+ const value = isNamed ? undefined : process18.env[env ?? DEFAULT_ENV];
1955
2233
  let url;
1956
2234
  if (value !== undefined && value !== "")
1957
2235
  url = await reachable(value, home);
@@ -2098,10 +2376,9 @@ async function closeQuietly(session, url) {
2098
2376
  // src/commands/query.ts
2099
2377
  var usage2 = `db query "<sql>"
2100
2378
 
2101
- Runs one read-only statement (the SQL as an argument, or on stdin) in a READ ONLY transaction that is rolled back, on Postgres, MySQL or MariaDB. A statement that would write is printed for you to run instead, and exits 1 without running.
2102
-
2103
- The SQL is tokenized the way its engine reads it and refused unless it starts with SELECT, WITH, VALUES, TABLE, SHOW, EXPLAIN, DESCRIBE or DESC and uses no INSERT, UPDATE, DELETE, MERGE, INTO, SET or FOR UPDATE anywhere (a write hidden in a CTE is caught), nor a function with side effects (nextval, setval, set_config, pg_terminate_backend, pg_sleep, dblink, sleep, load_file...). Several statements are refused (exit 2) even when each reads.
2104
- Statements time out after 30 seconds (--timeout changes it) and show at most -n rows (${DEFAULT_LIMIT}, --all for 100), a Postgres select being read through a cursor that stops one row past it. Columns named like emails, phones, tokens, secrets, passwords or hashes show *** unless --raw, and every message is scrubbed of the URL and password.
2379
+ Runs one read-only statement (the SQL as an argument, or on stdin) in a READ ONLY transaction that is rolled back, on Postgres, MySQL or MariaDB.
2380
+ Only a single statement starting with SELECT, WITH, VALUES, TABLE, SHOW, EXPLAIN, DESCRIBE or DESC, with no write or side-effect function in it, runs; several statements are refused (exit 2).
2381
+ Sensitive columns (emails, tokens, passwords...) show *** unless --raw.
2105
2382
 
2106
2383
  ${WRITE_NOTE}
2107
2384
 
@@ -2161,8 +2438,8 @@ ${render(shown, false, values.format)}`}`);
2161
2438
  // src/commands/explain.ts
2162
2439
  var usage3 = `db explain "<sql>" [--analyze]
2163
2440
 
2164
- Prints the plan the engine would run for one read (the SQL as an argument, or on stdin) without running it: EXPLAIN alone. The statement must start with SELECT, WITH, VALUES or TABLE and passes the same read-only guard as a query; EXPLAIN and ANALYZE written by hand are refused.
2165
- --analyze runs the read for real to time it, inside the READ ONLY transaction that is rolled back: EXPLAIN ANALYZE on Postgres and MySQL 8.0.18 or later, ANALYZE on MariaDB, refused on an older MySQL.
2441
+ Prints the plan the engine would run for one read (the SQL as an argument, or on stdin) without running it.
2442
+ The statement must start with SELECT, WITH, VALUES or TABLE and passes the query's read-only guard, so a hand-written EXPLAIN or ANALYZE is refused. --analyze runs the read to time it, inside the rolled-back READ ONLY transaction (refused on a MySQL before 8.0.18).
2166
2443
 
2167
2444
  ${HOSTS_NOTE}`;
2168
2445
  var options2 = { ...connectionOptions, json: jsonOption(), analyze: { type: "boolean", description: "run the read to time it, in the transaction that is rolled back" } };
@@ -2195,11 +2472,8 @@ async function explain(args) {
2195
2472
  prefix = dialect === "postgres" ? "EXPLAIN ANALYZE" : analyzePrefix(String((await readRows(url, "select version() as version", [], undefined, undefined, timeout))[0]?.version));
2196
2473
  const rows = await readRows(url, explainSql(sql, dialect, prefix), [], undefined, undefined, timeout);
2197
2474
  const [only, ...others] = Object.keys(rows[0] ?? {});
2198
- if (values.json !== true && only !== undefined && others.length === 0)
2199
- console.log(rows.map((row) => String(row[only])).join(`
2200
- `));
2201
- else
2202
- console.log(render(shape(rows, rows.length, true), values.json === true));
2475
+ console.log(values.json !== true && only !== undefined && others.length === 0 ? rows.map((row) => String(row[only])).join(`
2476
+ `) : render(shape(rows, rows.length, true), values.json === true));
2203
2477
  return 0;
2204
2478
  }
2205
2479
 
@@ -2365,10 +2639,7 @@ ${HOSTS_NOTE}`;
2365
2639
  const columns = shape(await ask(plans.columns, limit), limit, true, false);
2366
2640
  const indexes = await ask(plans.indexes);
2367
2641
  const foreignKeys = await ask(plans.foreignKeys);
2368
- if (values.json === true)
2369
- console.log(jsonText({ columns: columns.columns, rows: columns.rows, truncated: columns.truncated, masked: columns.masked, indexes, foreignKeys }, jsonValue));
2370
- else
2371
- console.log(`${render(columns, false, values.format)}
2642
+ console.log(values.json === true ? jsonText({ columns: columns.columns, rows: columns.rows, truncated: columns.truncated, masked: columns.masked, indexes, foreignKeys }, jsonValue) : `${render(columns, false, values.format)}
2372
2643
 
2373
2644
  indexes
2374
2645
  ${render(shape(indexes, indexes.length, true), false, values.format)}
@@ -2429,7 +2700,7 @@ ${HOSTS_NOTE}`, countOptions, (target, dialect, { where }) => countSql(target, d
2429
2700
  }
2430
2701
 
2431
2702
  // src/cli.ts
2432
- process18.exitCode = await runCli({
2703
+ process19.exitCode = await runCli({
2433
2704
  name: "db",
2434
2705
  about: "read-only SQL against Postgres, MySQL and MariaDB, credentials never shown, writes only on a _test database",
2435
2706
  replaces: "psql or mysql with the connection string on the command line, docker exec <container> psql -U ...",
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-db",
3
3
  "type": "module",
4
- "version": "0.13.0",
4
+ "version": "0.13.3",
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",
8
- "homepage": "https://git.kaynooo.fr/kaynooo/cli/src/branch/main/packages/db#readme",
8
+ "homepage": "https://github.com/Kayno0o/cli/tree/main/packages/db#readme",
9
9
  "repository": {
10
10
  "type": "git",
11
- "url": "git+https://git.kaynooo.fr/kaynooo/cli.git",
11
+ "url": "git+https://github.com/Kayno0o/cli.git",
12
12
  "directory": "packages/db"
13
13
  },
14
- "bugs": "https://git.kaynooo.fr/kaynooo/cli/issues",
14
+ "bugs": "https://github.com/Kayno0o/cli/issues",
15
15
  "keywords": ["postgres", "mysql", "mariadb", "sql", "read-only", "cli", "bun"],
16
16
  "bin": {
17
17
  "db": "./dist/cli.js"
@@ -28,6 +28,6 @@
28
28
  "db": "$npm_execpath src/cli.ts"
29
29
  },
30
30
  "devDependencies": {
31
- "@kaynooo/cli-kit": "0.39.0"
31
+ "@kaynooo/cli-kit": "0.45.1"
32
32
  }
33
33
  }