@kaynooo/cli-db 0.13.0 → 0.13.4

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 +486 -185
  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,15 +136,21 @@ 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";
130
145
  import { homedir } from "os";
131
- import { join as join2 } from "path";
146
+ import { isAbsolute, join as join2 } from "path";
132
147
  import process4 from "process";
148
+ function xdgFolder(value, fallback) {
149
+ return value !== undefined && isAbsolute(value) ? value : fallback;
150
+ }
133
151
  function configBase(where = {}) {
134
152
  const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
135
- return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
153
+ return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
136
154
  }
137
155
  function userConfigPath(bin, where = {}) {
138
156
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
@@ -144,36 +162,18 @@ function userConfigReadPath(bin, legacy = [], where = {}) {
144
162
  const base = configBase(where);
145
163
  return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
146
164
  }
165
+ var init_user_config = () => {};
147
166
 
148
167
  // ../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+/;
168
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
169
+ import { homedir as homedir2 } from "os";
170
+ import { join as join3, resolve as resolve2 } from "path";
171
+ import process5 from "process";
171
172
  function isColorSpec(spec) {
172
173
  if (typeof spec === "number")
173
174
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
174
175
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
175
176
  }
176
- var CUBE = [0, 95, 135, 175, 215, 255];
177
177
  function cubeLevel(channel) {
178
178
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
179
179
  }
@@ -278,7 +278,6 @@ function applyFile(theme, file, where, warn) {
278
278
  function endsWalk(home) {
279
279
  return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
280
280
  }
281
- var warned = new Set;
282
281
  function warnOnce(message) {
283
282
  if (warned.has(message))
284
283
  return;
@@ -315,8 +314,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
315
314
  }
316
315
  return { theme, sources, preset };
317
316
  }
318
- var current;
319
- var currentKey = "";
320
317
  function activeTheme() {
321
318
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
322
319
  if (current === undefined || key !== currentKey) {
@@ -325,9 +322,38 @@ function activeTheme() {
325
322
  }
326
323
  return current;
327
324
  }
325
+ var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
326
+ var init_theme = __esm(() => {
327
+ init_config();
328
+ init_user_config();
329
+ ENDS = new Map;
330
+ DEFAULT = {
331
+ 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" },
332
+ 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" },
333
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
334
+ bins: {},
335
+ gradient: ["#c084fc", "#67e8f9"]
336
+ };
337
+ 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" };
338
+ 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" };
339
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
340
+ PRESETS = {
341
+ default: {},
342
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
343
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
344
+ ascii: { glyphs: ASCII }
345
+ };
346
+ 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"]);
347
+ HEX = /^#[0-9a-f]{6}$/i;
348
+ CONTROL = /\p{Cc}/u;
349
+ MAX_FILE_BYTES = 64 * 1024;
350
+ SPACES = /\s+/;
351
+ CUBE = [0, 95, 135, 175, 215, 255];
352
+ warned = new Set;
353
+ });
328
354
 
329
355
  // ../kit/src/style.ts
330
- var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
356
+ import process6 from "process";
331
357
  function takesControlCodes(stream, env = process6.env) {
332
358
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
333
359
  }
@@ -349,17 +375,24 @@ function warn(text, detail) {
349
375
  function problem(text, detail) {
350
376
  console.error(marked("problem", text, process6.stderr, detail));
351
377
  }
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])));
378
+ var MARK_WORDS, STATUS_WORDS, STATUS_OF;
379
+ var init_style = __esm(() => {
380
+ init_colors();
381
+ init_mode();
382
+ init_theme();
383
+ MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
384
+ STATUS_WORDS = {
385
+ passed: ["passed", "success", "succeeded", "ok"],
386
+ failed: ["failed", "failure", "error", "errored"],
387
+ running: ["running", "in_progress", "started", "holding"],
388
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
389
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
390
+ };
391
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
392
+ });
360
393
 
361
394
  // ../kit/src/format.ts
362
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
395
+ import process7 from "process";
363
396
  function formatSeconds(total) {
364
397
  let rest = Math.max(0, Math.round(total));
365
398
  const amounts = UNITS.map(([unit, size]) => {
@@ -381,10 +414,8 @@ function upTo(text, separator) {
381
414
  return end === -1 ? text : text.slice(0, end);
382
415
  }
383
416
  function truncate(text, width) {
384
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
417
+ return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
385
418
  }
386
- var LINE_BREAKS = /\s*\n\s*/g;
387
- var ESCAPE = String.fromCharCode(27);
388
419
  function textWidth(text) {
389
420
  return Bun.stringWidth(text);
390
421
  }
@@ -430,14 +461,40 @@ function narrow(rows, widths, limit) {
430
461
  function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
431
462
  return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
432
463
  }
464
+ var UNITS, LINE_BREAKS, ESCAPE;
465
+ var init_format = __esm(() => {
466
+ init_text();
467
+ init_mode();
468
+ init_style();
469
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
470
+ LINE_BREAKS = /\s*\n\s*/g;
471
+ ESCAPE = String.fromCharCode(27);
472
+ });
433
473
 
434
474
  // ../kit/src/help.ts
435
475
  import process8 from "process";
436
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
437
- var USAGE_PREFIX = /^usage:\s*/i;
438
- var FULL_STOP = /\.$/;
439
476
  function usageLine(usage, colors = paint(process8.stdout)) {
440
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
477
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
478
+ `);
479
+ const blank = lines.indexOf("");
480
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
481
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
482
+ const colon = synopses[0].indexOf(": ");
483
+ const inline = synopses[0].slice(colon + 2);
484
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
485
+ if (colon !== -1)
486
+ synopses[0] = synopses[0].slice(0, colon);
487
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
488
+ `)}`;
489
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
490
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
491
+ return [head, ...lead, ...rest].join(`
492
+ `);
493
+ }
494
+ function prose(line, colors) {
495
+ if (colors.cyan("x") === "x")
496
+ return line;
497
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
441
498
  }
442
499
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
443
500
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -472,7 +529,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
472
529
  return [];
473
530
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
474
531
  }
475
- var MAX_INLINE_CHOICES = 24;
476
532
  function optionRows(options, colors = paint(process8.stdout)) {
477
533
  const rows = Object.entries(options).map(([name, option]) => {
478
534
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -487,6 +543,15 @@ function optionRows(options, colors = paint(process8.stdout)) {
487
543
  const width = Math.max(0, ...rows.map((row) => row.width));
488
544
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
489
545
  }
546
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
547
+ var init_help = __esm(() => {
548
+ init_mode();
549
+ init_style();
550
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
551
+ USAGE_PREFIX = /^usage:\s*/i;
552
+ FULL_STOP = /\.$/;
553
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
554
+ });
490
555
 
491
556
  // ../kit/src/text.ts
492
557
  function distance(a, b) {
@@ -514,9 +579,10 @@ function closest(name, names) {
514
579
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
515
580
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
516
581
  }
582
+ var init_text2 = () => {};
583
+
517
584
  // ../kit/src/input.ts
518
585
  import process9 from "process";
519
- var WHOLE = /^\d+$/;
520
586
  function wholeNumber(value, name, fallback, min = 1) {
521
587
  if (value === undefined)
522
588
  return fallback;
@@ -525,8 +591,6 @@ function wholeNumber(value, name, fallback, min = 1) {
525
591
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
526
592
  return number;
527
593
  }
528
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
529
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
530
594
  function duration(value, name, fallback, unit = "s") {
531
595
  if (value === undefined)
532
596
  return fallback;
@@ -547,40 +611,27 @@ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
547
611
  fail(`no file ${path}`);
548
612
  return file.text();
549
613
  }
614
+ var WHOLE, DURATION, UNIT_MS;
615
+ var init_input = __esm(() => {
616
+ init_args();
617
+ WHOLE = /^\d+$/;
618
+ DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
619
+ UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
620
+ });
550
621
 
551
622
  // ../kit/src/args.ts
552
- var DASHES = /^-+/;
623
+ import process10 from "process";
624
+ import { parseArgs } from "util";
553
625
  function jsonOption(holds) {
554
626
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
555
627
  }
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
628
  function fail(message, code = 2, hint) {
566
629
  throw new Exit(message, code, hint);
567
630
  }
568
-
569
- class UsageError extends Exit {
570
- constructor(message, hint) {
571
- super(message, 2, hint);
572
- }
573
- }
574
631
  function badUsage(message) {
575
632
  throw new UsageError(message);
576
633
  }
577
634
 
578
- class HelpShown extends Exit {
579
- constructor() {
580
- super("help shown", 0);
581
- }
582
- }
583
-
584
635
  class Completing {
585
636
  options;
586
637
  positionals;
@@ -591,11 +642,6 @@ class Completing {
591
642
  this.candidates = candidates;
592
643
  }
593
644
  }
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
645
  function applyOutput(color, plain, env = process10.env) {
600
646
  const when = plain === true ? "never" : color ?? "auto";
601
647
  if (when === "auto")
@@ -749,7 +795,6 @@ function parseError(error) {
749
795
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
750
796
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
751
797
  }
752
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
753
798
  function nearestOption(message, options, allowNegative) {
754
799
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
755
800
  if (typed === undefined)
@@ -765,6 +810,61 @@ function nearestOption(message, options, allowNegative) {
765
810
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
766
811
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
767
812
  }
813
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
814
+ var init_args = __esm(() => {
815
+ init_format();
816
+ init_help();
817
+ init_text2();
818
+ init_help();
819
+ init_input();
820
+ DASHES = /^-+/;
821
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
822
+ Exit = class Exit extends Error {
823
+ code;
824
+ hint;
825
+ [EXIT] = true;
826
+ constructor(message, code, hint) {
827
+ super(message);
828
+ this.code = code;
829
+ this.hint = hint;
830
+ }
831
+ static [Symbol.hasInstance](value) {
832
+ if (this !== Exit)
833
+ return Function.prototype[Symbol.hasInstance].call(this, value);
834
+ return typeof value === "object" && value !== null && value[EXIT] === true;
835
+ }
836
+ };
837
+ UsageError = class UsageError extends Exit {
838
+ constructor(message, hint) {
839
+ super(message, 2, hint);
840
+ }
841
+ };
842
+ HelpShown = class HelpShown extends Exit {
843
+ constructor() {
844
+ super("help shown", 0);
845
+ }
846
+ };
847
+ completion = { active: false };
848
+ OUTPUT_OPTIONS = {
849
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
850
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
851
+ };
852
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
853
+ });
854
+
855
+ // ../kit/src/folders.ts
856
+ var SKIPPED_FOLDERS;
857
+ var init_folders = __esm(() => {
858
+ init_user_config();
859
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
860
+ });
861
+
862
+ // src/cli.ts
863
+ import process19 from "process";
864
+
865
+ // ../kit/src/index.ts
866
+ init_args();
867
+
768
868
  // ../kit/src/argv.ts
769
869
  import { readFileSync as readFileSync3, realpathSync } from "fs";
770
870
  import { resolve as resolve3 } from "path";
@@ -789,10 +889,23 @@ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), scr
789
889
  const after = at === -1 ? [] : cmdline.slice(at + 1);
790
890
  return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
791
891
  }
892
+ // ../kit/src/chart.ts
893
+ init_format();
894
+ init_mode();
895
+ init_style();
896
+ init_theme();
897
+ // ../kit/src/ci.ts
898
+ init_args();
899
+ init_format();
900
+
901
+ // ../kit/src/progress.ts
902
+ init_format();
903
+
792
904
  // ../kit/src/process.ts
793
905
  import { constants } from "os";
794
906
  import process12 from "process";
795
907
  var KILL_GRACE_MS = 2000;
908
+ var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
796
909
  function exitCodeOf(code, signal) {
797
910
  if (code !== null)
798
911
  return code;
@@ -800,10 +913,10 @@ function exitCodeOf(code, signal) {
800
913
  return 128 + signal;
801
914
  return signal === null ? 129 : 128 + constants.signals[signal];
802
915
  }
803
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
916
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
804
917
  const chunks = [];
805
918
  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 } : {} });
919
+ 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
920
  const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
808
921
  const timers = [];
809
922
  const killGroup = (killing) => {
@@ -843,12 +956,19 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
843
956
  stop();
844
957
  continue;
845
958
  }
959
+ if (state.truncated)
960
+ continue;
961
+ let kept = data;
846
962
  if (state.kept + data.length > maxBytes) {
963
+ let cut = maxBytes - state.kept;
964
+ while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
965
+ cut--;
966
+ kept = data.subarray(0, cut);
847
967
  state.truncated = true;
848
- continue;
849
968
  }
850
- state.kept += data.length;
851
- chunks.push({ stream: name, data });
969
+ state.kept += kept.length;
970
+ if (kept.length > 0)
971
+ chunks.push({ stream: name, data: kept });
852
972
  }
853
973
  };
854
974
  try {
@@ -865,6 +985,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
865
985
  const joined = () => Buffer.concat(chunks.map(({ data }) => data));
866
986
  let output;
867
987
  let text;
988
+ let stdout;
868
989
  return {
869
990
  code: exitCodeOf(proc.exitCode, proc.signalCode),
870
991
  chunks,
@@ -875,49 +996,168 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
875
996
  },
876
997
  get text() {
877
998
  return text ??= (output ??= joined()).toString();
999
+ },
1000
+ get stdout() {
1001
+ return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
878
1002
  }
879
1003
  };
880
1004
  }
881
1005
 
882
1006
  // ../kit/src/progress.ts
1007
+ init_style();
1008
+ init_theme();
883
1009
  var ESC = String.fromCharCode(27);
884
1010
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
885
1011
  var RESET_STYLE = `${ESC}[0m`;
886
1012
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1013
+
1014
+ // ../kit/src/ci.ts
1015
+ init_style();
1016
+
1017
+ // ../kit/src/tool.ts
1018
+ init_format();
887
1019
  // ../kit/src/cli.ts
1020
+ init_args();
888
1021
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
889
1022
  import { dirname as dirname3, join as join5 } from "path";
890
- import process15 from "process";
1023
+ import process16 from "process";
891
1024
 
892
- // ../kit/src/notify.ts
1025
+ // ../kit/src/askpass.ts
893
1026
  import process13 from "process";
1027
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1028
+ async function askpassClient(argv) {
1029
+ const socketPath = process13.env[SOCKET_VARIABLE];
1030
+ if (socketPath === undefined)
1031
+ return;
1032
+ const request = { prompt: argv[0] ?? "", ...process13.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1033
+ const { promise, resolve } = Promise.withResolvers();
1034
+ let received = "";
1035
+ try {
1036
+ await Bun.connect({
1037
+ unix: socketPath,
1038
+ socket: {
1039
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1040
+ `),
1041
+ data: (_, chunk) => {
1042
+ received += chunk.toString();
1043
+ },
1044
+ close: () => resolve(received),
1045
+ error: () => resolve("")
1046
+ }
1047
+ });
1048
+ } catch {
1049
+ return 1;
1050
+ }
1051
+ const reply = await promise;
1052
+ if (reply === "")
1053
+ return 1;
1054
+ const { answer } = JSON.parse(reply);
1055
+ if (request.notice === true)
1056
+ return 0;
1057
+ if (answer === undefined)
1058
+ return 1;
1059
+ process13.stdout.write(`${answer}
1060
+ `);
1061
+ return 0;
1062
+ }
1063
+
1064
+ // ../kit/src/completions.ts
1065
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1066
+ 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'
1067
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1068
+ set -l current (commandline -ct)
1069
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1070
+ if test "$line" = __files__
1071
+ __fish_complete_path $current
1072
+ else
1073
+ echo $line
1074
+ end
1075
+ end
1076
+ end`;
1077
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1078
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1079
+ local -a lines
1080
+ COMPREPLY=()
1081
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1082
+ for line in "\${lines[@]}"; do
1083
+ if [[ $line == __files__ ]]; then
1084
+ COMPREPLY+=($(compgen -f -- "$cur"))
1085
+ else
1086
+ words+="\${line%%$'\\t'*}"$'\\n'
1087
+ fi
1088
+ done
1089
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1090
+ }`;
1091
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1092
+ local line
1093
+ local -a described plain
1094
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1095
+ if [[ $line == __files__ ]]; then
1096
+ _files
1097
+ elif [[ $line == *$'\\t'* ]]; then
1098
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1099
+ else
1100
+ plain+=("$line")
1101
+ fi
1102
+ done
1103
+ (( \${#described} )) && _describe -V value described
1104
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1105
+ return 0
1106
+ }`;
1107
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1108
+ if (shell === "fish")
1109
+ return `${header}
1110
+ ${FISH_FUNCTION}
1111
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1112
+ `).join("")}`;
1113
+ if (shell === "bash")
1114
+ return `${header}
1115
+ ${BASH_FUNCTION}
1116
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1117
+ `;
1118
+ return `${header}
1119
+ ${ZSH_FUNCTION}
1120
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1121
+ `;
1122
+ }
1123
+
1124
+ // ../kit/src/notify.ts
1125
+ init_format();
1126
+ init_mode();
1127
+ import process14 from "process";
894
1128
  var NOTIFY_AFTER_MS = 1e4;
895
1129
  var CANCELLED = 130;
896
1130
  function base64(text) {
897
1131
  return Buffer.from(text).toString("base64");
898
1132
  }
899
- function notification(title, body, env = process13.env) {
900
- const id = `kit${process13.pid}`;
1133
+ function notification(title, body, env = process14.env) {
1134
+ const id = `kit${process14.pid}`;
901
1135
  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
1136
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
903
1137
  }
904
- function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1138
+ function notifyEnd(command, code, ms, { stream = process14.stderr, env = process14.env } = {}) {
905
1139
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
906
1140
  return;
907
1141
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
908
1142
  }
909
1143
 
1144
+ // ../kit/src/cli.ts
1145
+ init_style();
1146
+ init_text2();
1147
+
910
1148
  // ../kit/src/usage.ts
911
1149
  import { appendFileSync, mkdirSync } from "fs";
912
1150
  import { homedir as homedir3 } from "os";
913
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
914
- import process14 from "process";
1151
+ import { dirname as dirname2, join as join4 } from "path";
1152
+ import process15 from "process";
915
1153
 
916
1154
  // ../kit/src/logs.ts
1155
+ init_user_config();
917
1156
  var DAY_MS = 24 * 60 * 60 * 1000;
918
1157
  var CLI_FOLDER = "kaynooo-cli";
919
1158
 
920
1159
  // ../kit/src/usage.ts
1160
+ init_user_config();
921
1161
  var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
922
1162
  var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
923
1163
  var LONGEST_NAME = 40;
@@ -925,14 +1165,13 @@ var usageError;
925
1165
  function noteUsageError(message) {
926
1166
  usageError = message;
927
1167
  }
928
- function stateHome(env = process14.env) {
929
- const dir = env.XDG_STATE_HOME;
930
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1168
+ function stateHome(env = process15.env) {
1169
+ return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
931
1170
  }
932
- function usagePath(env = process14.env) {
1171
+ function usagePath(env = process15.env) {
933
1172
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
934
1173
  }
935
- function usageRecorded(env = process14.env) {
1174
+ function usageRecorded(env = process15.env) {
936
1175
  const off = env.KAYNOOO_CLI_NO_USAGE;
937
1176
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
938
1177
  }
@@ -941,12 +1180,12 @@ function flagNames(argv) {
941
1180
  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
1181
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
943
1182
  }
944
- function usageEntry(bin, command, argv, code, now = new Date) {
1183
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
945
1184
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
946
1185
  usageError = undefined;
947
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1186
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
948
1187
  }
949
- function recordUsage(entry, env = process14.env) {
1188
+ function recordUsage(entry, env = process15.env) {
950
1189
  if (!usageRecorded(env))
951
1190
  return;
952
1191
  try {
@@ -962,7 +1201,11 @@ var LEVEL_OPTIONS = {
962
1201
  ...OUTPUT_OPTIONS,
963
1202
  help: { type: "boolean", short: "h", description: "show this help" }
964
1203
  };
965
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1204
+ var TOP_OPTIONS = {
1205
+ ...LEVEL_OPTIONS,
1206
+ version: { type: "boolean", short: "v", description: "print the version" },
1207
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1208
+ };
966
1209
  async function commandRows(all, colors) {
967
1210
  const commands = shown(all);
968
1211
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -997,6 +1240,10 @@ function takeOutputFlags(argv) {
997
1240
  async function resolveSummary(summary) {
998
1241
  return typeof summary === "string" ? summary : summary();
999
1242
  }
1243
+ function lookup({ commands, aliases }, word) {
1244
+ const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
1245
+ return Object.hasOwn(commands, name) ? commands[name] : undefined;
1246
+ }
1000
1247
  function scopeOf(commands, extra, aliases) {
1001
1248
  return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
1002
1249
  }
@@ -1036,8 +1283,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1036
1283
  `);
1037
1284
  }
1038
1285
  function printError(prefix, message, hint, cause) {
1039
- const colors = paint(process15.stderr);
1040
- const styled = takesControlCodes(process15.stderr);
1286
+ const colors = paint(process16.stderr);
1287
+ const styled = takesControlCodes(process16.stderr);
1041
1288
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1042
1289
  const under = (label, text, tint) => text === undefined ? "" : `
1043
1290
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1080,23 +1327,23 @@ async function dispatch(level, typed, { version, redact }) {
1080
1327
  }
1081
1328
  }
1082
1329
  if (name === undefined && level.path.length > 1) {
1083
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
1330
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process16.stderr));
1084
1331
  return 2;
1085
1332
  }
1086
1333
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1087
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
1334
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process16.stdout));
1088
1335
  return 0;
1089
1336
  }
1090
1337
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
1091
1338
  console.log(version);
1092
1339
  return 0;
1093
1340
  }
1094
- let command = level.commands[level.aliases?.[name] ?? name];
1341
+ let command = lookup(level, name);
1095
1342
  let rest = args;
1096
1343
  let ran = name;
1097
1344
  if (command === undefined && level.lazy.length > 0) {
1098
1345
  level = await expand(level, [...level.path.slice(1), ...argv]);
1099
- command = level.commands[level.aliases?.[name] ?? name];
1346
+ command = lookup(level, name);
1100
1347
  }
1101
1348
  if (command === undefined && level.defaultCommand !== undefined) {
1102
1349
  command = level.commands[level.defaultCommand];
@@ -1176,18 +1423,19 @@ async function leafCandidates(run, words) {
1176
1423
  async function candidates(scope, defaultCommand, words, before = []) {
1177
1424
  const [word = "", ...rest] = words;
1178
1425
  const listing = rest.length === 0 && !word.startsWith("-");
1179
- let { commands, aliases } = scope;
1180
- let command = commands[aliases?.[word] ?? word];
1426
+ let { commands } = scope;
1427
+ let command = lookup(scope, word);
1181
1428
  if (listing || command === undefined) {
1182
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
1183
- command = commands[aliases?.[word] ?? word];
1429
+ const expanded = await expand(scope, [...before, ...words]);
1430
+ commands = expanded.commands;
1431
+ command = lookup(expanded, word);
1184
1432
  }
1185
1433
  if (listing) {
1186
1434
  const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1187
1435
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1188
1436
  const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1189
1437
  const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1190
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1438
+ return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
1191
1439
  }
1192
1440
  if (command === undefined) {
1193
1441
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
@@ -1195,6 +1443,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1195
1443
  }
1196
1444
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1197
1445
  }
1446
+ var COMPLETIONS = "--completions";
1447
+ function flagValue([flag = "", ...rest]) {
1448
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1449
+ }
1450
+ function printCompletionScript(name, args) {
1451
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1452
+ if (shell === undefined || args.length !== 1) {
1453
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1454
+ return 2;
1455
+ }
1456
+ console.log(completionScript(shell, [name]).trimEnd());
1457
+ return 0;
1458
+ }
1198
1459
  async function printCandidates(found) {
1199
1460
  for (const line of await found)
1200
1461
  console.log(line);
@@ -1217,15 +1478,20 @@ function packageVersion(entry = Bun.main) {
1217
1478
  }
1218
1479
  async function runCli(cli, argv = scriptArgs()) {
1219
1480
  const version = cli.version ?? packageVersion();
1481
+ const answered = await askpassClient(argv);
1482
+ if (answered !== undefined)
1483
+ return answered;
1220
1484
  if (argv[0] === COMPLETE)
1221
1485
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1486
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1487
+ return printCompletionScript(cli.name, flagValue(argv));
1222
1488
  const started = performance.now();
1223
1489
  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
1490
  const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1225
1491
  notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1226
1492
  if (cli.usage !== false) {
1227
1493
  try {
1228
- recordUsage(usageEntry(cli.name, command, argv, code));
1494
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
1229
1495
  } catch {}
1230
1496
  }
1231
1497
  return code;
@@ -1234,8 +1500,7 @@ function commandPath(scope, argv) {
1234
1500
  const path = [];
1235
1501
  let level = scope;
1236
1502
  for (const word of argv.filter((each) => !each.startsWith("-"))) {
1237
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1238
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1503
+ const command = lookup(level, word);
1239
1504
  if (command === undefined)
1240
1505
  break;
1241
1506
  path.push(word);
@@ -1261,19 +1526,57 @@ function jsonLines(text) {
1261
1526
  return trimmed.startsWith("[") ? JSON.parse(trimmed) : trimmed.split(`
1262
1527
  `).map((line) => JSON.parse(line));
1263
1528
  }
1264
- // ../kit/src/folders.ts
1265
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1529
+
1530
+ // ../kit/src/index.ts
1531
+ init_config();
1532
+
1533
+ // ../kit/src/excerpt.ts
1534
+ init_text2();
1535
+
1536
+ // ../kit/src/index.ts
1537
+ init_folders();
1538
+ init_format();
1539
+
1540
+ // ../kit/src/git.ts
1541
+ init_args();
1542
+ // ../kit/src/limit.ts
1543
+ init_args();
1544
+
1545
+ // ../kit/src/index.ts
1546
+ init_mode();
1547
+
1548
+ // ../kit/src/report.ts
1549
+ init_style();
1550
+ init_text2();
1266
1551
  // ../kit/src/secrets.ts
1267
- var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
1552
+ var SECRET_PART = /token|secret|passw|passphrase|credential|private|dsn|apikey|accesskey|authorization|sess(?:ion)?id|connectionstring|key$/i;
1268
1553
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1269
1554
  var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
1555
+ var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1556
+ function isSecretWord(word) {
1557
+ const lower = word.toLowerCase();
1558
+ return SECRET_WORDS.has(lower) || lower.endsWith("pass") && !NOT_PASSWORDS.has(lower);
1559
+ }
1270
1560
  function isSecretName(name) {
1271
- return SECRET_PART.test(name) || name.split(WORD_BREAKS).some((word) => SECRET_WORDS.has(word.toLowerCase()));
1561
+ return SECRET_PART.test(name) || name.split(WORD_BREAKS).some(isSecretWord);
1272
1562
  }
1273
1563
  // ../kit/src/sessions.ts
1274
1564
  var {Glob } = globalThis.Bun;
1275
1565
  var SESSION_FILES = new Glob("*.json");
1276
1566
  var ACCOUNT_DIRS = new Glob("*/sessions");
1567
+
1568
+ // ../kit/src/index.ts
1569
+ init_style();
1570
+ init_text2();
1571
+ init_theme();
1572
+ init_user_config();
1573
+
1574
+ // ../kit/src/watch.ts
1575
+ init_args();
1576
+ init_input();
1577
+ init_style();
1578
+ // ../kit/src/workspace-root.ts
1579
+ init_user_config();
1277
1580
  // src/args.ts
1278
1581
  var DEFAULT_ENV = "DATABASE_URL";
1279
1582
  var DEFAULT_LIMIT = 20;
@@ -1282,7 +1585,7 @@ var ALL_LIMIT = 100;
1282
1585
  var WRITE_EXIT = 1;
1283
1586
  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
1587
  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.";
1588
+ 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
1589
  var connectionOptions = {
1287
1590
  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
1591
  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" },
@@ -1440,6 +1743,7 @@ function foreignDatabases(statement, database) {
1440
1743
  }
1441
1744
  return found;
1442
1745
  }
1746
+ var EXISTENCE_WORDS = new Set(["if", "not", "exists"]);
1443
1747
  function definesServerObject(statement, dialect) {
1444
1748
  if (!DEFINITION_STARTS.has(statement[0]?.text ?? ""))
1445
1749
  return null;
@@ -1697,7 +2001,7 @@ function render(shown, json, format) {
1697
2001
 
1698
2002
  // src/run.ts
1699
2003
  import { isIP } from "net";
1700
- import process17 from "process";
2004
+ import process18 from "process";
1701
2005
  var {SQL } = globalThis.Bun;
1702
2006
 
1703
2007
  // src/compose.ts
@@ -1775,16 +2079,13 @@ async function containerService(wanted) {
1775
2079
  if (inspect.code !== 0)
1776
2080
  fail(`no container ${wanted}`);
1777
2081
  try {
1778
- return describeNamedContainer(wanted, JSON.parse(stdoutOf(inspect.chunks)));
2082
+ return describeNamedContainer(wanted, JSON.parse(inspect.stdout));
1779
2083
  } catch (error) {
1780
2084
  if (error instanceof SyntaxError)
1781
2085
  fail(`docker inspect ${wanted} did not print JSON`);
1782
2086
  throw error;
1783
2087
  }
1784
2088
  }
1785
- function stdoutOf(chunks) {
1786
- return Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
1787
- }
1788
2089
  async function composeServices() {
1789
2090
  let ps;
1790
2091
  try {
@@ -1797,7 +2098,7 @@ async function composeServices() {
1797
2098
  if (rows.length === 0)
1798
2099
  return [];
1799
2100
  const inspect = await runCommand(["docker", "inspect", ...rows.map((row) => row.ID ?? "")]);
1800
- return inspect.code === 0 ? describeServices(rows, JSON.parse(stdoutOf(inspect.chunks))) : [];
2101
+ return inspect.code === 0 ? describeServices(rows, JSON.parse(inspect.stdout)) : [];
1801
2102
  } catch {
1802
2103
  return [];
1803
2104
  }
@@ -1902,16 +2203,18 @@ function dialectOf(url) {
1902
2203
  return "mysql";
1903
2204
  return fail(`the connection URL is ${url.protocol.replace(":", "")}://, but db reads Postgres (postgres://), MySQL and MariaDB (mysql://, mariadb://) only`);
1904
2205
  }
1905
- function hostOf(url) {
1906
- const host = url.hostname === "" ? url.searchParams.get("host") ?? "" : url.hostname;
1907
- return host.replace(BRACKETS, "").toLowerCase();
2206
+ function paramValues(url, name) {
2207
+ return [...url.searchParams].filter(([key, value]) => key.toLowerCase() === name && value !== "").map(([, value]) => value);
2208
+ }
2209
+ function hostsOf(url) {
2210
+ const named = paramValues(url, "host");
2211
+ return [...named.length === 0 ? [url.hostname] : named, ...paramValues(url, "hostaddr")].map((host) => host.replace(BRACKETS, "").toLowerCase());
1908
2212
  }
1909
2213
  var isLocal = (host) => host === "" || host.startsWith("/") || LOCAL_HOSTS.has(host);
1910
2214
  var DOCKER_NETWORK = /^172\.(?:1[6-9]|2\d|3[01])\./;
1911
2215
  function allowsKeyRetrieval(url) {
1912
2216
  try {
1913
- const host = hostOf(new URL(url));
1914
- return isLocal(host) || isIP(host) !== 0 && DOCKER_NETWORK.test(host);
2217
+ return hostsOf(new URL(url)).every((host) => isLocal(host) || isIP(host) !== 0 && DOCKER_NETWORK.test(host));
1915
2218
  } catch {
1916
2219
  return false;
1917
2220
  }
@@ -1934,24 +2237,29 @@ async function reachable(value, home) {
1934
2237
  fail("the connection URL does not parse");
1935
2238
  }
1936
2239
  const dialect = dialectOf(url);
1937
- const host = hostOf(url);
1938
- if (isLocal(host))
2240
+ const hosts = hostsOf(url);
2241
+ const [host = ""] = hosts;
2242
+ if (hosts.every(isLocal))
1939
2243
  return url;
1940
- const service = isIP(host) === 0 ? serviceNamed(await composeServices(), host, dialect) : undefined;
2244
+ const service = hosts.length === 1 && isIP(host) === 0 ? serviceNamed(await composeServices(), host, dialect) : undefined;
1941
2245
  if (service !== undefined) {
2246
+ for (const key of [...url.searchParams.keys()].filter((each) => ["host", "port"].includes(each.toLowerCase())))
2247
+ url.searchParams.delete(key);
1942
2248
  url.hostname = service.host.includes(":") ? `[${service.host}]` : service.host;
1943
2249
  url.port = String(service.port);
1944
2250
  return url;
1945
2251
  }
1946
- if (!((await loadSettings(home)).allowedHosts ?? []).some((allowed) => allowed.toLowerCase().replace(BRACKETS, "") === host))
1947
- fail(`${host} is neither local nor a compose service, so db does not connect to it: list it in "allowedHosts" in ${settingsPath(home)} to allow it`);
2252
+ const allowed = new Set(((await loadSettings(home)).allowedHosts ?? []).map((each) => each.toLowerCase().replace(BRACKETS, "")));
2253
+ const refused = hosts.find((each) => !isLocal(each) && !allowed.has(each));
2254
+ if (refused !== undefined)
2255
+ fail(`${refused} is neither local nor a compose service, so db does not connect to it: list it in "allowedHosts" in ${settingsPath(home)} to allow it`);
1948
2256
  return url;
1949
2257
  }
1950
2258
  async function connectionUrl({ env, service, container, database }, home) {
1951
2259
  if (service !== undefined && container !== undefined)
1952
2260
  fail("--service and --container name two databases: pick one");
1953
2261
  const isNamed = service !== undefined || container !== undefined;
1954
- const value = isNamed ? undefined : process17.env[env ?? DEFAULT_ENV];
2262
+ const value = isNamed ? undefined : process18.env[env ?? DEFAULT_ENV];
1955
2263
  let url;
1956
2264
  if (value !== undefined && value !== "")
1957
2265
  url = await reachable(value, home);
@@ -2098,10 +2406,9 @@ async function closeQuietly(session, url) {
2098
2406
  // src/commands/query.ts
2099
2407
  var usage2 = `db query "<sql>"
2100
2408
 
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.
2409
+ 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.
2410
+ 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).
2411
+ Sensitive columns (emails, tokens, passwords...) show *** unless --raw.
2105
2412
 
2106
2413
  ${WRITE_NOTE}
2107
2414
 
@@ -2161,8 +2468,8 @@ ${render(shown, false, values.format)}`}`);
2161
2468
  // src/commands/explain.ts
2162
2469
  var usage3 = `db explain "<sql>" [--analyze]
2163
2470
 
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.
2471
+ Prints the plan the engine would run for one read (the SQL as an argument, or on stdin) without running it.
2472
+ 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
2473
 
2167
2474
  ${HOSTS_NOTE}`;
2168
2475
  var options2 = { ...connectionOptions, json: jsonOption(), analyze: { type: "boolean", description: "run the read to time it, in the transaction that is rolled back" } };
@@ -2195,11 +2502,8 @@ async function explain(args) {
2195
2502
  prefix = dialect === "postgres" ? "EXPLAIN ANALYZE" : analyzePrefix(String((await readRows(url, "select version() as version", [], undefined, undefined, timeout))[0]?.version));
2196
2503
  const rows = await readRows(url, explainSql(sql, dialect, prefix), [], undefined, undefined, timeout);
2197
2504
  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));
2505
+ console.log(values.json !== true && only !== undefined && others.length === 0 ? rows.map((row) => String(row[only])).join(`
2506
+ `) : render(shape(rows, rows.length, true), values.json === true));
2203
2507
  return 0;
2204
2508
  }
2205
2509
 
@@ -2365,10 +2669,7 @@ ${HOSTS_NOTE}`;
2365
2669
  const columns = shape(await ask(plans.columns, limit), limit, true, false);
2366
2670
  const indexes = await ask(plans.indexes);
2367
2671
  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)}
2672
+ 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
2673
 
2373
2674
  indexes
2374
2675
  ${render(shape(indexes, indexes.length, true), false, values.format)}
@@ -2429,7 +2730,7 @@ ${HOSTS_NOTE}`, countOptions, (target, dialect, { where }) => countSql(target, d
2429
2730
  }
2430
2731
 
2431
2732
  // src/cli.ts
2432
- process18.exitCode = await runCli({
2733
+ process19.exitCode = await runCli({
2433
2734
  name: "db",
2434
2735
  about: "read-only SQL against Postgres, MySQL and MariaDB, credentials never shown, writes only on a _test database",
2435
2736
  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.4",
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.46.0"
32
32
  }
33
33
  }