@kaynooo/cli-forgejo 0.30.1 → 0.30.6

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 +6 -5
  2. package/dist/cli.js +1483 -488
  3. package/package.json +6 -6
package/dist/cli.js CHANGED
@@ -1,21 +1,19 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --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 process31 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 ct = /[aeiou]y$/;
15
- var N = new Map;
16
- var Ot = /(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/;
17
- var Gt = /(?:knife|life|wife)$/;
18
- function K(t, e, { plural: r, zero: n = "singular" } = {}) {
15
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
16
+ function G(t, e, { plural: r, zero: n = "singular" } = {}) {
19
17
  if (e === 1 || e === 0 && n === "singular")
20
18
  return t;
21
19
  if (r !== undefined)
@@ -28,12 +26,10 @@ function K(t, e, { plural: r, zero: n = "singular" } = {}) {
28
26
  return `${t.slice(0, -1)}ves`;
29
27
  return Gt.test(t) ? `${t.slice(0, -2)}ves` : `${t}s`;
30
28
  }
31
- function go(t, e, { zero: r = "plural", ...n } = {}) {
32
- return `${t} ${K(e, t, { ...n, zero: r })}`;
29
+ function bo(t, e, { zero: r = "plural", ...n } = {}) {
30
+ return `${t} ${G(e, t, { ...n, zero: r })}`;
33
31
  }
34
- var Nt = /\s+\S*$/;
35
- var Y = /\s/;
36
- function ko(t, e, r = "...") {
32
+ function Ao(t, e, r = "...") {
37
33
  let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
38
34
  if (t.length <= e)
39
35
  return t;
@@ -44,13 +40,25 @@ function ko(t, e, r = "...") {
44
40
  c = c.trimEnd();
45
41
  return s ? (c + n).slice(0, l) : c + n;
46
42
  }
47
- 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));
48
- var z = new Map;
43
+ var ct, N, Ot, Gt, Nt, Y, be, W;
44
+ var init_chunk_rkhsft4a = __esm(() => {
45
+ ct = /[aeiou]y$/;
46
+ N = new Map;
47
+ Ot = /(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/;
48
+ Gt = /(?:knife|life|wife)$/;
49
+ Nt = /\s+\S*$/;
50
+ Y = /\s/;
51
+ 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));
52
+ W = new Map;
53
+ });
54
+
55
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
56
+ var init_text = __esm(() => {
57
+ init_chunk_rkhsft4a();
58
+ });
49
59
 
50
60
  // ../kit/src/mode.ts
51
61
  import process2 from "process";
52
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
53
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
54
62
  function isSet(value) {
55
63
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
56
64
  }
@@ -64,12 +72,16 @@ function outputMode(stream = process2.stdout, env = process2.env) {
64
72
  return "terminal";
65
73
  return isSet(env.CI) ? "ci" : "pipe";
66
74
  }
75
+ function isInteractive(streams = process2) {
76
+ return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
77
+ }
78
+ var MODES, AGENT_VARIABLES;
79
+ var init_mode = __esm(() => {
80
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
81
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
82
+ });
67
83
 
68
- // ../kit/src/style.ts
69
- import process6 from "process";
70
-
71
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
72
- var G2 = /^[a-f0-9]+$/i;
84
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
73
85
  function b(r) {
74
86
  let e = r.startsWith("#") ? r.slice(1) : r;
75
87
  if (!G2.test(e))
@@ -80,11 +92,6 @@ function b(r) {
80
92
  throw Error(`Invalid hex color length: ${e.length}`);
81
93
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
82
94
  }
83
- 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") => {
84
- let [l, n, c] = b(r);
85
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
86
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
87
- var h = new Set(["", "1", "2", "3", "true"]);
88
95
  function C(r, e = globalThis.process?.env ?? {}) {
89
96
  if (e.FORCE_COLOR !== undefined)
90
97
  return h.has(e.FORCE_COLOR);
@@ -98,7 +105,7 @@ function f(r, e = []) {
98
105
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
99
106
  let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
100
107
  return new Proxy(c, { get(t, i) {
101
- let a = B2[i];
108
+ let a = B[i];
102
109
  if (Array.isArray(a)) {
103
110
  let s = g.get(i);
104
111
  if (s === undefined)
@@ -121,13 +128,21 @@ function f(r, e = []) {
121
128
  function Fe(r = {}) {
122
129
  return f(r);
123
130
  }
124
- var o = Fe();
131
+ var G2, B, h, o;
132
+ var init_chunk_x450vn3m = __esm(() => {
133
+ G2 = /^[a-f0-9]+$/i;
134
+ 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") => {
135
+ let [l, n, c] = b(r);
136
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
137
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
138
+ h = new Set(["", "1", "2", "3", "true"]);
139
+ o = Fe();
140
+ });
125
141
 
126
- // ../kit/src/theme.ts
127
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
128
- import { homedir as homedir2 } from "os";
129
- import { join as join3, resolve as resolve2 } from "path";
130
- import process5 from "process";
142
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
143
+ var init_colors = __esm(() => {
144
+ init_chunk_x450vn3m();
145
+ });
131
146
 
132
147
  // ../kit/src/config.ts
133
148
  import { existsSync } from "fs";
@@ -143,15 +158,21 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
143
158
  return;
144
159
  }
145
160
  }
161
+ var init_config = __esm(() => {
162
+ init_args();
163
+ });
146
164
 
147
165
  // ../kit/src/user-config.ts
148
166
  import { existsSync as existsSync2, readFileSync } from "fs";
149
167
  import { homedir } from "os";
150
- import { join as join2 } from "path";
168
+ import { isAbsolute, join as join2 } from "path";
151
169
  import process4 from "process";
170
+ function xdgFolder(value, fallback) {
171
+ return value !== undefined && isAbsolute(value) ? value : fallback;
172
+ }
152
173
  function configBase(where = {}) {
153
174
  const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
154
- return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
175
+ return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
155
176
  }
156
177
  function userConfigPath(bin, where = {}) {
157
178
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
@@ -178,13 +199,17 @@ function configuredNumber(bin, key, fallback, where = {}, legacy = []) {
178
199
  const value = readUserConfig(bin, where, legacy)[key];
179
200
  return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
180
201
  }
202
+ var init_user_config = () => {};
181
203
 
182
204
  // ../kit/src/theme.ts
205
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
206
+ import { homedir as homedir2 } from "os";
207
+ import { join as join3, resolve as resolve2 } from "path";
208
+ import process5 from "process";
183
209
  function toLinear(channel) {
184
210
  const value = channel / 255;
185
211
  return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
186
212
  }
187
- var fromLinear = (value) => Math.round(255 * Math.min(1, Math.max(0, value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055)));
188
213
  function toOklab(hex) {
189
214
  const [r, g, b] = [1, 3, 5].map((at) => toLinear(Number.parseInt(hex.slice(at, at + 2), 16)));
190
215
  const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
@@ -199,7 +224,6 @@ function fromOklab([lightness, a, b]) {
199
224
  const channels = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s];
200
225
  return `#${channels.map((channel) => fromLinear(channel).toString(16).padStart(2, "0")).join("")}`;
201
226
  }
202
- var ENDS = new Map;
203
227
  function gradientAt(theme, ratio) {
204
228
  if (theme.gradient === undefined)
205
229
  return;
@@ -213,33 +237,11 @@ function gradientAt(theme, ratio) {
213
237
  const [from, to] = ends;
214
238
  return fromOklab(from.map((start, index) => start + (to[index] - start) * at));
215
239
  }
216
- var DEFAULT = {
217
- 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" },
218
- 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" },
219
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
220
- bins: {},
221
- gradient: ["#c084fc", "#67e8f9"]
222
- };
223
- 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" };
224
- 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" };
225
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
226
- var PRESETS = {
227
- default: {},
228
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
229
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
230
- ascii: { glyphs: ASCII }
231
- };
232
- 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"]);
233
- var HEX = /^#[0-9a-f]{6}$/i;
234
- var CONTROL = /\p{Cc}/u;
235
- var MAX_FILE_BYTES = 64 * 1024;
236
- var SPACES = /\s+/;
237
240
  function isColorSpec(spec) {
238
241
  if (typeof spec === "number")
239
242
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
240
243
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
241
244
  }
242
- var CUBE = [0, 95, 135, 175, 215, 255];
243
245
  function cubeLevel(channel) {
244
246
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
245
247
  }
@@ -347,7 +349,6 @@ function applyFile(theme, file, where, warn) {
347
349
  function endsWalk(home) {
348
350
  return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
349
351
  }
350
- var warned = new Set;
351
352
  function warnOnce(message) {
352
353
  if (warned.has(message))
353
354
  return;
@@ -384,8 +385,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
384
385
  }
385
386
  return { theme, sources, preset };
386
387
  }
387
- var current;
388
- var currentKey = "";
389
388
  function activeTheme() {
390
389
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
391
390
  if (current === undefined || key !== currentKey) {
@@ -394,9 +393,38 @@ function activeTheme() {
394
393
  }
395
394
  return current;
396
395
  }
396
+ var fromLinear = (value) => Math.round(255 * Math.min(1, Math.max(0, value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055))), ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
397
+ var init_theme = __esm(() => {
398
+ init_config();
399
+ init_user_config();
400
+ ENDS = new Map;
401
+ DEFAULT = {
402
+ 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" },
403
+ 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" },
404
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
405
+ bins: {},
406
+ gradient: ["#c084fc", "#67e8f9"]
407
+ };
408
+ 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" };
409
+ 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" };
410
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
411
+ PRESETS = {
412
+ default: {},
413
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
414
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
415
+ ascii: { glyphs: ASCII }
416
+ };
417
+ 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"]);
418
+ HEX = /^#[0-9a-f]{6}$/i;
419
+ CONTROL = /\p{Cc}/u;
420
+ MAX_FILE_BYTES = 64 * 1024;
421
+ SPACES = /\s+/;
422
+ CUBE = [0, 95, 135, 175, 215, 255];
423
+ warned = new Set;
424
+ });
397
425
 
398
426
  // ../kit/src/style.ts
399
- var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
427
+ import process6 from "process";
400
428
  function takesControlCodes(stream, env = process6.env) {
401
429
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
402
430
  }
@@ -425,14 +453,6 @@ function role(name, stream, env = process6.env) {
425
453
  const colors = paint(stream, env);
426
454
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
427
455
  }
428
- var STATUS_WORDS = {
429
- passed: ["passed", "success", "succeeded", "ok"],
430
- failed: ["failed", "failure", "error", "errored"],
431
- running: ["running", "in_progress", "started", "holding"],
432
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
433
- skipped: ["skipped", "cancelled", "canceled", "manual"]
434
- };
435
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
436
456
  function statusOf(word) {
437
457
  return STATUS_OF.get(word.toLowerCase());
438
458
  }
@@ -476,9 +496,24 @@ function section(title, count, stream = process6.stdout, env = process6.env, ton
476
496
  function hyperlink(text, url, stream, env = process6.env) {
477
497
  return takesControlCodes(stream, env) ? paint(stream, env).underline(link(text, url, stream, env)) : text;
478
498
  }
499
+ var MARK_WORDS, STATUS_WORDS, STATUS_OF;
500
+ var init_style = __esm(() => {
501
+ init_colors();
502
+ init_mode();
503
+ init_theme();
504
+ MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
505
+ STATUS_WORDS = {
506
+ passed: ["passed", "success", "succeeded", "ok"],
507
+ failed: ["failed", "failure", "error", "errored"],
508
+ running: ["running", "in_progress", "started", "holding"],
509
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
510
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
511
+ };
512
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
513
+ });
479
514
 
480
515
  // ../kit/src/format.ts
481
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
516
+ import process7 from "process";
482
517
  function formatSeconds(total) {
483
518
  let rest = Math.max(0, Math.round(total));
484
519
  const amounts = UNITS.map(([unit, size]) => {
@@ -510,10 +545,8 @@ function formatAge(date, now = Date.now()) {
510
545
  return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
511
546
  }
512
547
  function truncate(text, width) {
513
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
548
+ return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
514
549
  }
515
- var LINE_BREAKS = /\s*\n\s*/g;
516
- var ESCAPE = String.fromCharCode(27);
517
550
  function textWidth(text) {
518
551
  return Bun.stringWidth(text);
519
552
  }
@@ -565,14 +598,40 @@ function printJson(value) {
565
598
  function formatPercent(ratio, digits = 0) {
566
599
  return `${(ratio * 100).toFixed(digits)}%`;
567
600
  }
601
+ var UNITS, LINE_BREAKS, ESCAPE;
602
+ var init_format = __esm(() => {
603
+ init_text();
604
+ init_mode();
605
+ init_style();
606
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
607
+ LINE_BREAKS = /\s*\n\s*/g;
608
+ ESCAPE = String.fromCharCode(27);
609
+ });
568
610
 
569
611
  // ../kit/src/help.ts
570
612
  import process8 from "process";
571
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
572
- var USAGE_PREFIX = /^usage:\s*/i;
573
- var FULL_STOP = /\.$/;
574
613
  function usageLine(usage, colors = paint(process8.stdout)) {
575
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
614
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
615
+ `);
616
+ const blank = lines.indexOf("");
617
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
618
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
619
+ const colon = synopses[0].indexOf(": ");
620
+ const inline = synopses[0].slice(colon + 2);
621
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
622
+ if (colon !== -1)
623
+ synopses[0] = synopses[0].slice(0, colon);
624
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
625
+ `)}`;
626
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
627
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
628
+ return [head, ...lead, ...rest].join(`
629
+ `);
630
+ }
631
+ function prose(line, colors) {
632
+ if (colors.cyan("x") === "x")
633
+ return line;
634
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
576
635
  }
577
636
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
578
637
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -607,7 +666,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
607
666
  return [];
608
667
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
609
668
  }
610
- var MAX_INLINE_CHOICES = 24;
611
669
  function optionRows(options, colors = paint(process8.stdout)) {
612
670
  const rows = Object.entries(options).map(([name, option]) => {
613
671
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -622,9 +680,17 @@ function optionRows(options, colors = paint(process8.stdout)) {
622
680
  const width = Math.max(0, ...rows.map((row) => row.width));
623
681
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
624
682
  }
683
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
684
+ var init_help = __esm(() => {
685
+ init_mode();
686
+ init_style();
687
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
688
+ USAGE_PREFIX = /^usage:\s*/i;
689
+ FULL_STOP = /\.$/;
690
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
691
+ });
625
692
 
626
693
  // ../kit/src/text.ts
627
- var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
628
694
  function stripAnsi(text) {
629
695
  return text.replace(ANSI, "");
630
696
  }
@@ -653,9 +719,13 @@ function closest(name, names) {
653
719
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
654
720
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
655
721
  }
722
+ var ANSI;
723
+ var init_text2 = __esm(() => {
724
+ ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
725
+ });
726
+
656
727
  // ../kit/src/input.ts
657
728
  import process9 from "process";
658
- var WHOLE = /^\d+$/;
659
729
  function wholeNumber(value, name, fallback, min = 1) {
660
730
  if (value === undefined)
661
731
  return fallback;
@@ -664,8 +734,6 @@ function wholeNumber(value, name, fallback, min = 1) {
664
734
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
665
735
  return number;
666
736
  }
667
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
668
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
669
737
  function duration(value, name, fallback, unit = "s") {
670
738
  if (value === undefined)
671
739
  return fallback;
@@ -686,44 +754,30 @@ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
686
754
  fail(`no file ${path}`);
687
755
  return file.text();
688
756
  }
757
+ var WHOLE, DURATION, UNIT_MS;
758
+ var init_input = __esm(() => {
759
+ init_args();
760
+ WHOLE = /^\d+$/;
761
+ DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
762
+ UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
763
+ });
689
764
 
690
765
  // ../kit/src/args.ts
691
- var DASHES = /^-+/;
766
+ import process10 from "process";
767
+ import { parseArgs } from "util";
692
768
  function jsonOption(holds) {
693
769
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
694
770
  }
695
771
  function copyOption(what) {
696
772
  return { type: "boolean", description: `also copy ${what} to the clipboard` };
697
773
  }
698
-
699
- class Exit extends Error {
700
- code;
701
- hint;
702
- constructor(message, code, hint) {
703
- super(message);
704
- this.code = code;
705
- this.hint = hint;
706
- }
707
- }
708
774
  function fail(message, code = 2, hint) {
709
775
  throw new Exit(message, code, hint);
710
776
  }
711
-
712
- class UsageError extends Exit {
713
- constructor(message, hint) {
714
- super(message, 2, hint);
715
- }
716
- }
717
777
  function badUsage(message) {
718
778
  throw new UsageError(message);
719
779
  }
720
780
 
721
- class HelpShown extends Exit {
722
- constructor() {
723
- super("help shown", 0);
724
- }
725
- }
726
-
727
781
  class Completing {
728
782
  options;
729
783
  positionals;
@@ -734,11 +788,6 @@ class Completing {
734
788
  this.candidates = candidates;
735
789
  }
736
790
  }
737
- var completion = { active: false };
738
- var OUTPUT_OPTIONS = {
739
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
740
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
741
- };
742
791
  function applyOutput(color, plain, env = process10.env) {
743
792
  const when = plain === true ? "never" : color ?? "auto";
744
793
  if (when === "auto")
@@ -892,7 +941,6 @@ function parseError(error) {
892
941
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
893
942
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
894
943
  }
895
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
896
944
  function nearestOption(message, options, allowNegative) {
897
945
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
898
946
  if (typed === undefined)
@@ -908,6 +956,495 @@ function nearestOption(message, options, allowNegative) {
908
956
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
909
957
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
910
958
  }
959
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
960
+ var init_args = __esm(() => {
961
+ init_format();
962
+ init_help();
963
+ init_text2();
964
+ init_help();
965
+ init_input();
966
+ DASHES = /^-+/;
967
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
968
+ Exit = class Exit extends Error {
969
+ code;
970
+ hint;
971
+ [EXIT] = true;
972
+ constructor(message, code, hint) {
973
+ super(message);
974
+ this.code = code;
975
+ this.hint = hint;
976
+ }
977
+ static [Symbol.hasInstance](value) {
978
+ if (this !== Exit)
979
+ return Function.prototype[Symbol.hasInstance].call(this, value);
980
+ return typeof value === "object" && value !== null && value[EXIT] === true;
981
+ }
982
+ };
983
+ UsageError = class UsageError extends Exit {
984
+ constructor(message, hint) {
985
+ super(message, 2, hint);
986
+ }
987
+ };
988
+ HelpShown = class HelpShown extends Exit {
989
+ constructor() {
990
+ super("help shown", 0);
991
+ }
992
+ };
993
+ completion = { active: false };
994
+ OUTPUT_OPTIONS = {
995
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
996
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
997
+ };
998
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
999
+ });
1000
+
1001
+ // ../kit/src/folders.ts
1002
+ import { homedir as homedir3 } from "os";
1003
+ import { join as join4 } from "path";
1004
+ import process16 from "process";
1005
+ function cacheFolder({ home = homedir3(), env = process16.env } = {}) {
1006
+ return xdgFolder(env.XDG_CACHE_HOME, join4(home, ".cache"));
1007
+ }
1008
+ var SKIPPED_FOLDERS;
1009
+ var init_folders = __esm(() => {
1010
+ init_user_config();
1011
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1012
+ });
1013
+
1014
+ // ../kit/src/answers.ts
1015
+ import { mkdirSync, readFileSync as readFileSync5, writeFileSync } from "fs";
1016
+ import { dirname as dirname2, join as join5 } from "path";
1017
+ function answersFile() {
1018
+ return join5(cacheFolder(), "kaynooo-cli", "answers.json");
1019
+ }
1020
+ function stored() {
1021
+ try {
1022
+ const parsed = JSON.parse(readFileSync5(answersFile(), "utf-8"));
1023
+ if (typeof parsed !== "object" || parsed === null)
1024
+ return {};
1025
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
1026
+ } catch {
1027
+ return {};
1028
+ }
1029
+ }
1030
+ function earlierAnswers(key) {
1031
+ return stored()[key] ?? [];
1032
+ }
1033
+ function rememberAnswer(key, answer) {
1034
+ const all = stored();
1035
+ const file = answersFile();
1036
+ all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
1037
+ try {
1038
+ mkdirSync(dirname2(file), { recursive: true });
1039
+ writeFileSync(file, JSON.stringify(all));
1040
+ } catch {}
1041
+ }
1042
+ var KEPT = 50;
1043
+ var init_answers = __esm(() => {
1044
+ init_folders();
1045
+ });
1046
+
1047
+ // ../kit/src/job.ts
1048
+ import process17 from "process";
1049
+ function stopJob() {
1050
+ process17.kill(0, "SIGTSTP");
1051
+ }
1052
+ var init_job = () => {};
1053
+
1054
+ // ../kit/src/picker/line.ts
1055
+ function isEditKey(key) {
1056
+ return EDIT_KEYS.has(key);
1057
+ }
1058
+ function endsKills(key) {
1059
+ return typeof key !== "object" && !isEditKey(key);
1060
+ }
1061
+ function isWord(char) {
1062
+ return char !== undefined && WORD_CHARACTER.test(char);
1063
+ }
1064
+ function wordStart(chars, from) {
1065
+ let at = from;
1066
+ while (at > 0 && !isWord(chars[at - 1]))
1067
+ at--;
1068
+ while (at > 0 && isWord(chars[at - 1]))
1069
+ at--;
1070
+ return at;
1071
+ }
1072
+ function wordEnd(chars, from) {
1073
+ let at = from;
1074
+ while (at < chars.length && !isWord(chars[at]))
1075
+ at++;
1076
+ while (at < chars.length && isWord(chars[at]))
1077
+ at++;
1078
+ return at;
1079
+ }
1080
+ function spacedStart(chars, from) {
1081
+ let at = from;
1082
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
1083
+ at--;
1084
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
1085
+ at--;
1086
+ return at;
1087
+ }
1088
+ function cut(chars, from, to) {
1089
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
1090
+ }
1091
+ function insert(chars, at, text) {
1092
+ const typed = [...text];
1093
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
1094
+ }
1095
+ function editLine(line, key) {
1096
+ const { killed = "", chained = false } = line;
1097
+ const chars = [...line.text];
1098
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
1099
+ const edited = edit(chars, at, key, killed);
1100
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
1101
+ return line.killed === undefined ? edited : { ...edited, killed };
1102
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1103
+ if (taken === "")
1104
+ return { ...edited, killed, chained };
1105
+ if (!chained)
1106
+ return { ...edited, killed: taken, chained: true };
1107
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
1108
+ }
1109
+ function edit(chars, at, key, killed) {
1110
+ const text = chars.join("");
1111
+ if (typeof key === "object")
1112
+ return insert(chars, at, key.text);
1113
+ switch (key) {
1114
+ case "left":
1115
+ return { text, caret: Math.max(at - 1, 0) };
1116
+ case "right":
1117
+ return { text, caret: Math.min(at + 1, chars.length) };
1118
+ case "wordleft":
1119
+ return { text, caret: wordStart(chars, at) };
1120
+ case "wordright":
1121
+ return { text, caret: wordEnd(chars, at) };
1122
+ case "linestart":
1123
+ return { text, caret: 0 };
1124
+ case "lineend":
1125
+ return { text, caret: chars.length };
1126
+ case "erase":
1127
+ return cut(chars, Math.max(at - 1, 0), at);
1128
+ case "delete":
1129
+ return cut(chars, at, Math.min(at + 1, chars.length));
1130
+ case "word":
1131
+ return cut(chars, spacedStart(chars, at), at);
1132
+ case "killword":
1133
+ return cut(chars, wordStart(chars, at), at);
1134
+ case "killnext":
1135
+ return cut(chars, at, wordEnd(chars, at));
1136
+ case "clear":
1137
+ return cut(chars, 0, at);
1138
+ case "killend":
1139
+ return cut(chars, at, chars.length);
1140
+ case "yank":
1141
+ return insert(chars, at, killed);
1142
+ }
1143
+ }
1144
+ function visible({ text, caret }, room) {
1145
+ const chars = [...text];
1146
+ const at = Math.min(Math.max(caret, 0), chars.length);
1147
+ const cells = at === chars.length ? [...chars, " "] : chars;
1148
+ const widths = cells.map((char) => Bun.stringWidth(char));
1149
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
1150
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
1151
+ let start = at;
1152
+ let end = at + 1;
1153
+ while (start > 0 && fits(start - 1, end))
1154
+ start--;
1155
+ while (end < cells.length && fits(start, end + 1))
1156
+ end++;
1157
+ const left = start > 0 ? "\u2026" : "";
1158
+ const right = end < cells.length ? "\u2026" : "";
1159
+ return { before: left + chars.slice(start, at).join(""), at: chars[at], after: chars.slice(at + 1, end).join("") + right, column: left.length + width(start, at) };
1160
+ }
1161
+ var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS, WORD_CHARACTER, SPACE;
1162
+ var init_line = __esm(() => {
1163
+ EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1164
+ BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1165
+ FORWARD_KILLS = new Set(["killnext", "killend"]);
1166
+ WORD_CHARACTER = /[\p{L}\p{N}_]/u;
1167
+ SPACE = /\s/;
1168
+ });
1169
+
1170
+ // ../kit/src/picker/score.ts
1171
+ var BOUNDARY_AFTER, NONE;
1172
+ var init_score = __esm(() => {
1173
+ BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1174
+ NONE = Number.NEGATIVE_INFINITY;
1175
+ });
1176
+
1177
+ // ../kit/src/picker/state.ts
1178
+ function repeat(value, count) {
1179
+ return Array.from({ length: count }).fill(value);
1180
+ }
1181
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
1182
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1183
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1184
+ const wheel = MOUSE.exec(sequence)?.[1];
1185
+ if (wheel !== undefined)
1186
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1187
+ const named = codes.get(sequence);
1188
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1189
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1190
+ paste.active = sequence === PASTE_START;
1191
+ return [];
1192
+ }
1193
+ if (paste.active && (sequence === "\r" || sequence === `
1194
+ `))
1195
+ return [];
1196
+ if (key !== undefined)
1197
+ return [key];
1198
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1199
+ });
1200
+ }
1201
+ var IS_CONTROL, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
1202
+ var init_state = __esm(() => {
1203
+ init_text2();
1204
+ init_line();
1205
+ init_score();
1206
+ IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1207
+ KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1208
+ MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1209
+ KEYS = {
1210
+ "\x1B[A": "up",
1211
+ "\x1BOA": "up",
1212
+ "\x10": "up",
1213
+ "\x1B[B": "down",
1214
+ "\x1BOB": "down",
1215
+ "\x0E": "down",
1216
+ "\x1B[5~": "pageup",
1217
+ "\x1B[6~": "pagedown",
1218
+ "\x1B[H": "home",
1219
+ "\x1B[1~": "home",
1220
+ "\x1BOH": "home",
1221
+ "\x1B[F": "end",
1222
+ "\x1B[4~": "end",
1223
+ "\x1BOF": "end",
1224
+ "\r": "enter",
1225
+ "\n": "enter",
1226
+ "\x03": "cancel",
1227
+ "\x1B": "cancel",
1228
+ "\x1B[D": "left",
1229
+ "\x1BOD": "left",
1230
+ "\x1B[C": "right",
1231
+ "\x1BOC": "right",
1232
+ "\x1B[1;5D": "wordleft",
1233
+ "\x1B[1;3D": "wordleft",
1234
+ "\x1Bb": "wordleft",
1235
+ "\x1B[1;5C": "wordright",
1236
+ "\x1B[1;3C": "wordright",
1237
+ "\x1Bf": "wordright",
1238
+ "\x01": "linestart",
1239
+ "\x05": "lineend",
1240
+ "\x7F": "erase",
1241
+ "\x1B[3~": "delete",
1242
+ "\b": "killword",
1243
+ "\x1B\x7F": "killword",
1244
+ "\x1B[3;5~": "killnext",
1245
+ "\x1Bd": "killnext",
1246
+ "\x15": "clear",
1247
+ "\v": "killend",
1248
+ "\x17": "word",
1249
+ "\x19": "yank",
1250
+ "\x1A": "suspend",
1251
+ "\t": "tab",
1252
+ "\x1F": "help",
1253
+ "\x1BOP": "help",
1254
+ "\x1B[11~": "help"
1255
+ };
1256
+ });
1257
+
1258
+ // ../kit/src/redraw.ts
1259
+ function overwrite(lines, columns) {
1260
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1261
+ `);
1262
+ }
1263
+ function rowsTaken(lines, columns) {
1264
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1265
+ }
1266
+ var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
1267
+ var init_redraw = __esm(() => {
1268
+ init_format();
1269
+ });
1270
+
1271
+ // ../kit/src/prompt.ts
1272
+ import process18 from "process";
1273
+ function readKeys(input, paste = { active: false }) {
1274
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
1275
+ }
1276
+ function roomAfter(question, columns) {
1277
+ return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
1278
+ }
1279
+ function withCaret(colors, line, room, dim = false) {
1280
+ const { before, at, after } = visible(line, room);
1281
+ const tone = dim ? colors.dim : (text) => text;
1282
+ return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
1283
+ }
1284
+ function sharedStart(texts) {
1285
+ const [first = [], ...rest] = texts.map((text) => [...text]);
1286
+ let length = first.length;
1287
+ for (const chars of rest) {
1288
+ const differs = chars.findIndex((char, index) => char !== first[index]);
1289
+ length = Math.min(length, differs === -1 ? chars.length : differs);
1290
+ }
1291
+ return first.slice(0, length).join("");
1292
+ }
1293
+ function listed2(colors, found, columns) {
1294
+ const shared = sharedStart(found);
1295
+ const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
1296
+ const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
1297
+ const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
1298
+ return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
1299
+ }
1300
+ async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
1301
+ let line = { text: "", caret: 0 };
1302
+ let invalid;
1303
+ let completions = [];
1304
+ const remembered = history === undefined || mask ? undefined : history;
1305
+ const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
1306
+ let recalled = -1;
1307
+ let draft = line;
1308
+ const taken = () => line.text === "" ? fallback ?? "" : line.text;
1309
+ const shown = () => mask ? "*".repeat([...taken()].length) : taken();
1310
+ const accepted = await ask(question, settings, (colors, state, { columns }) => {
1311
+ if (state !== "asking")
1312
+ return [answer(colors, question, state, shown())];
1313
+ const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
1314
+ return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
1315
+ }, (key) => {
1316
+ if (key === "cancel")
1317
+ return "cancel";
1318
+ invalid = undefined;
1319
+ completions = [];
1320
+ if (line.chained === true && endsKills(key))
1321
+ line = { ...line, chained: false };
1322
+ if (key === "tab") {
1323
+ const chars = [...line.text];
1324
+ const before = chars.slice(0, line.caret).join("");
1325
+ const found = complete?.(before) ?? [];
1326
+ const filled = sharedStart(found);
1327
+ if ([...filled].length > [...before].length)
1328
+ line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
1329
+ else
1330
+ completions = found;
1331
+ return;
1332
+ }
1333
+ if (key === "enter") {
1334
+ invalid = validate?.(taken());
1335
+ return invalid === undefined ? "enter" : undefined;
1336
+ }
1337
+ if (key === "up" || key === "down") {
1338
+ const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
1339
+ if (recalled === -1)
1340
+ draft = line;
1341
+ recalled = to;
1342
+ const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
1343
+ line = { ...shown, killed: line.killed ?? "" };
1344
+ return;
1345
+ }
1346
+ const edit = { home: "linestart", end: "lineend" }[key] ?? key;
1347
+ if (typeof edit === "object" || isEditKey(edit))
1348
+ line = editLine(line, edit);
1349
+ return;
1350
+ });
1351
+ if (!accepted)
1352
+ return;
1353
+ if (remembered !== undefined && taken() !== "")
1354
+ rememberAnswer(remembered, taken());
1355
+ return taken();
1356
+ }
1357
+ function answer(colors, question, state, picked) {
1358
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1359
+ }
1360
+ async function ask(question, { hint, terminal = process18 }, render, press) {
1361
+ const { stdin, stderr } = terminal;
1362
+ if (!isInteractive(terminal))
1363
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
1364
+ const colors = paint(stderr);
1365
+ let current = "asking";
1366
+ let outcome;
1367
+ const columns = () => stderr.columns || 80;
1368
+ const draw = (state, last = false) => {
1369
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1370
+ const rows = rowsTaken(frame, columns());
1371
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
1372
+ current = state;
1373
+ };
1374
+ const redraw = () => draw(current);
1375
+ const paste = { active: false };
1376
+ const stop = terminal.stop ?? (terminal === process18 ? stopJob : undefined);
1377
+ const suspend = () => {
1378
+ if (stop === undefined)
1379
+ return;
1380
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
1381
+ stdin.setRawMode(false);
1382
+ stop();
1383
+ stdin.setRawMode(true);
1384
+ stderr.write("\x1B[?25l\x1B[?2004h");
1385
+ };
1386
+ try {
1387
+ stderr.on?.("resize", redraw);
1388
+ stdin.setRawMode(true);
1389
+ stdin.resume();
1390
+ stderr.write("\x1B[?25l\x1B[?2004h");
1391
+ draw("asking");
1392
+ return await new Promise((resolve) => {
1393
+ function onData(data) {
1394
+ for (const key of readKeys(data.toString(), paste)) {
1395
+ if (key === "suspend") {
1396
+ suspend();
1397
+ continue;
1398
+ }
1399
+ const pressed = press(key);
1400
+ if (pressed !== undefined) {
1401
+ settle(pressed);
1402
+ return;
1403
+ }
1404
+ }
1405
+ draw("asking");
1406
+ }
1407
+ function onEnd() {
1408
+ settle("cancel");
1409
+ }
1410
+ function settle(settled) {
1411
+ outcome = settled;
1412
+ stdin.off("data", onData);
1413
+ stdin.off("end", onEnd);
1414
+ resolve(settled === "enter");
1415
+ }
1416
+ stdin.on("data", onData);
1417
+ stdin.on("end", onEnd);
1418
+ });
1419
+ } finally {
1420
+ stderr.off?.("resize", redraw);
1421
+ draw(outcome ?? "cancel", true);
1422
+ stderr.write(`
1423
+ \x1B[?25h\x1B[?2004l`);
1424
+ stdin.setRawMode(false);
1425
+ stdin.pause();
1426
+ }
1427
+ }
1428
+ var PROMPT_KEYS, MAX_LISTED = 12;
1429
+ var init_prompt = __esm(() => {
1430
+ init_answers();
1431
+ init_args();
1432
+ init_format();
1433
+ init_job();
1434
+ init_mode();
1435
+ init_line();
1436
+ init_state();
1437
+ init_redraw();
1438
+ init_style();
1439
+ PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1440
+ });
1441
+
1442
+ // src/cli.ts
1443
+ import process35 from "process";
1444
+
1445
+ // ../kit/src/index.ts
1446
+ init_args();
1447
+
911
1448
  // ../kit/src/argv.ts
912
1449
  import { readFileSync as readFileSync3, realpathSync } from "fs";
913
1450
  import { resolve as resolve3 } from "path";
@@ -933,6 +1470,10 @@ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), scr
933
1470
  return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
934
1471
  }
935
1472
  // ../kit/src/chart.ts
1473
+ init_format();
1474
+ init_mode();
1475
+ init_style();
1476
+ init_theme();
936
1477
  import process12 from "process";
937
1478
  var FILLED = "\u2501";
938
1479
  var EMPTY = "\u2500";
@@ -946,15 +1487,22 @@ function bar(ratio, { width = 20, stream = process12.stdout, env = process12.env
946
1487
  const { theme } = activeTheme();
947
1488
  return `${shaded(theme, colors, theme.glyphs.bar, filled, width, env)}${colors.dim(theme.glyphs.bar.repeat(width - filled))}`;
948
1489
  }
1490
+ // ../kit/src/ci.ts
1491
+ init_args();
1492
+ init_format();
1493
+
949
1494
  // ../kit/src/progress.ts
1495
+ init_format();
950
1496
  import process14 from "process";
951
1497
 
952
1498
  // ../kit/src/process.ts
1499
+ import { readFileSync as readFileSync4 } from "fs";
953
1500
  import { constants } from "os";
954
1501
  import { resolve as resolve4 } from "path";
955
1502
  import process13 from "process";
956
1503
  var KILL_GRACE_MS = 2000;
957
1504
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1505
+ var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
958
1506
  var SCHEME = /^[a-z][\w+.-]+:/i;
959
1507
  var OPENERS = { darwin: ["open"], win32: ["cmd", "/c", "start", ""] };
960
1508
  function exitCodeOf(code, signal) {
@@ -964,6 +1512,21 @@ function exitCodeOf(code, signal) {
964
1512
  return 128 + signal;
965
1513
  return signal === null ? 129 : 128 + constants.signals[signal];
966
1514
  }
1515
+ function groupsOf(pid) {
1516
+ try {
1517
+ const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
1518
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
1519
+ return { group: Number(fields[2]), foreground: Number(fields[5]) };
1520
+ } catch {
1521
+ return;
1522
+ }
1523
+ }
1524
+ function heardTheTerminal(child) {
1525
+ if (child.pid === undefined)
1526
+ return false;
1527
+ const own = groupsOf("self");
1528
+ return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
1529
+ }
967
1530
  function holdSignals(cleanup) {
968
1531
  let received;
969
1532
  let child;
@@ -982,7 +1545,8 @@ function holdSignals(cleanup) {
982
1545
  function onSignal(signal) {
983
1546
  received = signal;
984
1547
  if (child !== undefined) {
985
- child.kill(signal);
1548
+ if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
1549
+ child.kill(signal);
986
1550
  return;
987
1551
  }
988
1552
  if (cleanup === undefined)
@@ -1021,10 +1585,10 @@ async function pipeInto(argv, text) {
1021
1585
  return false;
1022
1586
  }
1023
1587
  }
1024
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
1588
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
1025
1589
  const chunks = [];
1026
1590
  const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
1027
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
1591
+ 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 } : {} });
1028
1592
  const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
1029
1593
  const timers = [];
1030
1594
  const killGroup = (killing) => {
@@ -1064,12 +1628,19 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
1064
1628
  stop();
1065
1629
  continue;
1066
1630
  }
1631
+ if (state.truncated)
1632
+ continue;
1633
+ let kept = data;
1067
1634
  if (state.kept + data.length > maxBytes) {
1635
+ let cut = maxBytes - state.kept;
1636
+ while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
1637
+ cut--;
1638
+ kept = data.subarray(0, cut);
1068
1639
  state.truncated = true;
1069
- continue;
1070
1640
  }
1071
- state.kept += data.length;
1072
- chunks.push({ stream: name, data });
1641
+ state.kept += kept.length;
1642
+ if (kept.length > 0)
1643
+ chunks.push({ stream: name, data: kept });
1073
1644
  }
1074
1645
  };
1075
1646
  try {
@@ -1086,6 +1657,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
1086
1657
  const joined = () => Buffer.concat(chunks.map(({ data }) => data));
1087
1658
  let output;
1088
1659
  let text;
1660
+ let stdout;
1089
1661
  return {
1090
1662
  code: exitCodeOf(proc.exitCode, proc.signalCode),
1091
1663
  chunks,
@@ -1096,11 +1668,16 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
1096
1668
  },
1097
1669
  get text() {
1098
1670
  return text ??= (output ??= joined()).toString();
1671
+ },
1672
+ get stdout() {
1673
+ return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
1099
1674
  }
1100
1675
  };
1101
1676
  }
1102
1677
 
1103
1678
  // ../kit/src/progress.ts
1679
+ init_style();
1680
+ init_theme();
1104
1681
  var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1105
1682
  var FRAME_MS = 200;
1106
1683
  var CLEAR_BELOW = "\r\x1B[J";
@@ -1117,10 +1694,14 @@ function liveRegion(render, stream = process14.stderr, env = process14.env) {
1117
1694
  }, print: (text) => void stream.write(`${text}
1118
1695
  `), stop: () => {
1119
1696
  return;
1697
+ }, pause: () => () => {
1698
+ return;
1120
1699
  } };
1121
1700
  const write = stream.write.bind(stream);
1122
1701
  let frame = 0;
1123
1702
  let drawn = false;
1703
+ let paused = false;
1704
+ let stopped = false;
1124
1705
  const columns = () => {
1125
1706
  const now = stream.getWindowSize?.()[0] ?? stream.columns;
1126
1707
  return now === undefined || now === 0 ? 80 : now;
@@ -1131,6 +1712,8 @@ function liveRegion(render, stream = process14.stderr, env = process14.env) {
1131
1712
  drawn = false;
1132
1713
  };
1133
1714
  const draw = () => {
1715
+ if (paused)
1716
+ return;
1134
1717
  const width = columns() - 1;
1135
1718
  const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
1136
1719
  const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
@@ -1142,16 +1725,17 @@ function liveRegion(render, stream = process14.stderr, env = process14.env) {
1142
1725
  `)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
1143
1726
  drawn = true;
1144
1727
  };
1145
- const timer = setInterval(draw, FRAME_MS);
1728
+ let timer = setInterval(draw, FRAME_MS);
1146
1729
  stream.on?.("resize", draw);
1147
- const restore = interceptOutput(clear);
1148
- const release = swallowInput();
1730
+ let restore = interceptOutput(clear);
1731
+ let release = swallowInput();
1149
1732
  const onExit = () => {
1150
1733
  clear();
1151
1734
  release();
1152
1735
  };
1153
1736
  const signals = holdSignals(stop);
1154
1737
  function stop() {
1738
+ stopped = true;
1155
1739
  clearInterval(timer);
1156
1740
  stream.off?.("resize", draw);
1157
1741
  clear();
@@ -1160,6 +1744,29 @@ function liveRegion(render, stream = process14.stderr, env = process14.env) {
1160
1744
  process14.off("exit", onExit);
1161
1745
  signals.release();
1162
1746
  }
1747
+ function pause() {
1748
+ if (paused || stopped)
1749
+ return () => {
1750
+ return;
1751
+ };
1752
+ paused = true;
1753
+ clearInterval(timer);
1754
+ stream.off?.("resize", draw);
1755
+ clear();
1756
+ restore();
1757
+ release();
1758
+ return () => {
1759
+ if (!paused || stopped)
1760
+ return;
1761
+ paused = false;
1762
+ timer = setInterval(draw, FRAME_MS);
1763
+ timer.unref();
1764
+ stream.on?.("resize", draw);
1765
+ restore = interceptOutput(clear);
1766
+ release = swallowInput();
1767
+ draw();
1768
+ };
1769
+ }
1163
1770
  timer.unref();
1164
1771
  process14.on("exit", onExit);
1165
1772
  return {
@@ -1170,7 +1777,8 @@ function liveRegion(render, stream = process14.stderr, env = process14.env) {
1170
1777
  `);
1171
1778
  draw();
1172
1779
  },
1173
- stop
1780
+ stop,
1781
+ pause
1174
1782
  };
1175
1783
  }
1176
1784
  function cutToWidth(line, width) {
@@ -1241,7 +1849,11 @@ function interceptOutput(clear) {
1241
1849
  };
1242
1850
  }
1243
1851
 
1852
+ // ../kit/src/ci.ts
1853
+ init_style();
1854
+
1244
1855
  // ../kit/src/tool.ts
1856
+ init_format();
1245
1857
  import process15 from "process";
1246
1858
  var PERMANENT = /\bHTTP (?:401|403|404)\b|unauthorized|forbidden|not found|couldn't be found|token is required/i;
1247
1859
  function cwdGone() {
@@ -1270,10 +1882,10 @@ function isPermanentFailure(error) {
1270
1882
  return false;
1271
1883
  return error instanceof SpawnError && error.missing || PERMANENT.test(error.message);
1272
1884
  }
1273
- async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
1885
+ async function runTool(label, argv, { timeoutMs, cwd, onStart, env } = {}) {
1274
1886
  let ran;
1275
1887
  try {
1276
- ran = await runCommand(argv, { env: process15.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
1888
+ ran = await runCommand(argv, { env: { ...process15.env, ...env }, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
1277
1889
  } catch (error) {
1278
1890
  throw spawnFailure(label, error);
1279
1891
  }
@@ -1365,39 +1977,218 @@ function ciHeader(spinner, label, startedAt, out) {
1365
1977
  return `${spinner} ${label} ${paint(out).dim(formatElapsed(Date.now() - startedAt))}`;
1366
1978
  }
1367
1979
  // ../kit/src/cli.ts
1368
- import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
1369
- import { dirname as dirname3, join as join5 } from "path";
1370
- import process18 from "process";
1980
+ init_args();
1981
+ import { readFileSync as readFileSync6, realpathSync as realpathSync2 } from "fs";
1982
+ import { dirname as dirname4, join as join8 } from "path";
1983
+ import process22 from "process";
1984
+
1985
+ // ../kit/src/askpass.ts
1986
+ import { chmodSync, mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
1987
+ import { tmpdir } from "os";
1988
+ import { join as join6 } from "path";
1989
+ import process19 from "process";
1990
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1991
+ var ECHOED = /username|yes\/no/i;
1992
+ var quoted = (text) => `'${text.replaceAll("'", `'\\''`)}'`;
1993
+ function askpass(pause = () => () => {
1994
+ return;
1995
+ }) {
1996
+ if (process19.stdin.isTTY !== true || process19.stderr.isTTY !== true || process19.argv[1] === undefined)
1997
+ return;
1998
+ const dir = mkdtempSync(join6(tmpdir(), "kaynooo-askpass-"));
1999
+ const socketPath = join6(dir, "socket");
2000
+ const script = join6(dir, "askpass");
2001
+ let turn = Promise.resolve();
2002
+ const answer = async ({ prompt, notice }) => {
2003
+ const resume = pause();
2004
+ try {
2005
+ if (notice === true) {
2006
+ process19.stderr.write(`${prompt.trim()}
2007
+ `);
2008
+ return {};
2009
+ }
2010
+ await Promise.resolve().then(() => init_prompt());
2011
+ return { answer: await input2(prompt.trim(), { mask: !ECHOED.test(prompt) }) };
2012
+ } finally {
2013
+ resume();
2014
+ }
2015
+ };
2016
+ const respond = async (socket, request) => {
2017
+ const { promise, resolve } = Promise.withResolvers();
2018
+ const previous = turn;
2019
+ let reply = {};
2020
+ turn = promise;
2021
+ await previous;
2022
+ try {
2023
+ reply = await answer(request);
2024
+ } catch {} finally {
2025
+ socket.end(`${JSON.stringify(reply)}
2026
+ `);
2027
+ resolve();
2028
+ }
2029
+ };
2030
+ const server = Bun.listen({
2031
+ unix: socketPath,
2032
+ socket: {
2033
+ open: (socket) => {
2034
+ socket.data = { buffered: "" };
2035
+ },
2036
+ data: (socket, chunk) => {
2037
+ const before = socket.data.buffered;
2038
+ socket.data.buffered += chunk.toString();
2039
+ if (before.includes(`
2040
+ `) || !socket.data.buffered.includes(`
2041
+ `))
2042
+ return;
2043
+ respond(socket, JSON.parse(socket.data.buffered));
2044
+ }
2045
+ }
2046
+ });
2047
+ writeFileSync2(script, `#!/bin/sh
2048
+ ${SOCKET_VARIABLE}=${quoted(socketPath)} exec ${quoted(process19.execPath)} --no-env-file --config=/dev/null ${quoted(process19.argv[1])} "$@"
2049
+ `);
2050
+ chmodSync(script, 448);
2051
+ return {
2052
+ env: { GIT_ASKPASS: script, SSH_ASKPASS: script, SSH_ASKPASS_REQUIRE: "force" },
2053
+ close: () => {
2054
+ server.stop(true);
2055
+ rmSync(dir, { recursive: true, force: true });
2056
+ }
2057
+ };
2058
+ }
2059
+ async function askpassClient(argv) {
2060
+ const socketPath = process19.env[SOCKET_VARIABLE];
2061
+ if (socketPath === undefined)
2062
+ return;
2063
+ const request = { prompt: argv[0] ?? "", ...process19.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
2064
+ const { promise, resolve } = Promise.withResolvers();
2065
+ let received = "";
2066
+ try {
2067
+ await Bun.connect({
2068
+ unix: socketPath,
2069
+ socket: {
2070
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
2071
+ `),
2072
+ data: (_, chunk) => {
2073
+ received += chunk.toString();
2074
+ },
2075
+ close: () => resolve(received),
2076
+ error: () => resolve("")
2077
+ }
2078
+ });
2079
+ } catch {
2080
+ return 1;
2081
+ }
2082
+ const reply = await promise;
2083
+ if (reply === "")
2084
+ return 1;
2085
+ const { answer } = JSON.parse(reply);
2086
+ if (request.notice === true)
2087
+ return 0;
2088
+ if (answer === undefined)
2089
+ return 1;
2090
+ process19.stdout.write(`${answer}
2091
+ `);
2092
+ return 0;
2093
+ }
2094
+
2095
+ // ../kit/src/completions.ts
2096
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
2097
+ 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'
2098
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
2099
+ set -l current (commandline -ct)
2100
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
2101
+ if test "$line" = __files__
2102
+ __fish_complete_path $current
2103
+ else
2104
+ echo $line
2105
+ end
2106
+ end
2107
+ end`;
2108
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
2109
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
2110
+ local -a lines
2111
+ COMPREPLY=()
2112
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
2113
+ for line in "\${lines[@]}"; do
2114
+ if [[ $line == __files__ ]]; then
2115
+ COMPREPLY+=($(compgen -f -- "$cur"))
2116
+ else
2117
+ words+="\${line%%$'\\t'*}"$'\\n'
2118
+ fi
2119
+ done
2120
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
2121
+ }`;
2122
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
2123
+ local line
2124
+ local -a described plain
2125
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
2126
+ if [[ $line == __files__ ]]; then
2127
+ _files
2128
+ elif [[ $line == *$'\\t'* ]]; then
2129
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
2130
+ else
2131
+ plain+=("$line")
2132
+ fi
2133
+ done
2134
+ (( \${#described} )) && _describe -V value described
2135
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
2136
+ return 0
2137
+ }`;
2138
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
2139
+ if (shell === "fish")
2140
+ return `${header}
2141
+ ${FISH_FUNCTION}
2142
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
2143
+ `).join("")}`;
2144
+ if (shell === "bash")
2145
+ return `${header}
2146
+ ${BASH_FUNCTION}
2147
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
2148
+ `;
2149
+ return `${header}
2150
+ ${ZSH_FUNCTION}
2151
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
2152
+ `;
2153
+ }
1371
2154
 
1372
2155
  // ../kit/src/notify.ts
1373
- import process16 from "process";
2156
+ init_format();
2157
+ init_mode();
2158
+ import process20 from "process";
1374
2159
  var NOTIFY_AFTER_MS = 1e4;
1375
2160
  var CANCELLED = 130;
1376
2161
  function base64(text) {
1377
2162
  return Buffer.from(text).toString("base64");
1378
2163
  }
1379
- function notification(title, body, env = process16.env) {
1380
- const id = `kit${process16.pid}`;
2164
+ function notification(title, body, env = process20.env) {
2165
+ const id = `kit${process20.pid}`;
1381
2166
  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\\`];
1382
2167
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1383
2168
  }
1384
- function notifyEnd(command, code, ms, { stream = process16.stderr, env = process16.env } = {}) {
2169
+ function notifyEnd(command, code, ms, { stream = process20.stderr, env = process20.env } = {}) {
1385
2170
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1386
2171
  return;
1387
2172
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1388
2173
  }
1389
2174
 
2175
+ // ../kit/src/cli.ts
2176
+ init_style();
2177
+ init_text2();
2178
+
1390
2179
  // ../kit/src/usage.ts
1391
- import { appendFileSync, mkdirSync } from "fs";
1392
- import { homedir as homedir3 } from "os";
1393
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1394
- import process17 from "process";
2180
+ import { appendFileSync, mkdirSync as mkdirSync2 } from "fs";
2181
+ import { homedir as homedir4 } from "os";
2182
+ import { dirname as dirname3, join as join7 } from "path";
2183
+ import process21 from "process";
1395
2184
 
1396
2185
  // ../kit/src/logs.ts
2186
+ init_user_config();
1397
2187
  var DAY_MS = 24 * 60 * 60 * 1000;
1398
2188
  var CLI_FOLDER = "kaynooo-cli";
1399
2189
 
1400
2190
  // ../kit/src/usage.ts
2191
+ init_user_config();
1401
2192
  var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1402
2193
  var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1403
2194
  var LONGEST_NAME = 40;
@@ -1405,14 +2196,13 @@ var usageError;
1405
2196
  function noteUsageError(message) {
1406
2197
  usageError = message;
1407
2198
  }
1408
- function stateHome(env = process17.env) {
1409
- const dir = env.XDG_STATE_HOME;
1410
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
2199
+ function stateHome(env = process21.env) {
2200
+ return xdgFolder(env.XDG_STATE_HOME, join7(homedir4(), ".local", "state"));
1411
2201
  }
1412
- function usagePath(env = process17.env) {
1413
- return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
2202
+ function usagePath(env = process21.env) {
2203
+ return join7(stateHome(env), CLI_FOLDER, "usage.jsonl");
1414
2204
  }
1415
- function usageRecorded(env = process17.env) {
2205
+ function usageRecorded(env = process21.env) {
1416
2206
  const off = env.KAYNOOO_CLI_NO_USAGE;
1417
2207
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1418
2208
  }
@@ -1421,17 +2211,17 @@ function flagNames(argv) {
1421
2211
  const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1422
2212
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1423
2213
  }
1424
- function usageEntry(bin, command, argv, code, now = new Date) {
2214
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1425
2215
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1426
2216
  usageError = undefined;
1427
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
2217
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1428
2218
  }
1429
- function recordUsage(entry, env = process17.env) {
2219
+ function recordUsage(entry, env = process21.env) {
1430
2220
  if (!usageRecorded(env))
1431
2221
  return;
1432
2222
  try {
1433
2223
  const path = usagePath(env);
1434
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
2224
+ mkdirSync2(dirname3(path), { recursive: true, mode: 448 });
1435
2225
  appendFileSync(path, `${JSON.stringify(entry)}
1436
2226
  `, { mode: 384 });
1437
2227
  } catch {}
@@ -1442,7 +2232,11 @@ var LEVEL_OPTIONS = {
1442
2232
  ...OUTPUT_OPTIONS,
1443
2233
  help: { type: "boolean", short: "h", description: "show this help" }
1444
2234
  };
1445
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
2235
+ var TOP_OPTIONS = {
2236
+ ...LEVEL_OPTIONS,
2237
+ version: { type: "boolean", short: "v", description: "print the version" },
2238
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
2239
+ };
1446
2240
  async function commandRows(all, colors) {
1447
2241
  const commands = shown(all);
1448
2242
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -1477,6 +2271,10 @@ function takeOutputFlags(argv) {
1477
2271
  async function resolveSummary(summary) {
1478
2272
  return typeof summary === "string" ? summary : summary();
1479
2273
  }
2274
+ function lookup({ commands, aliases }, word) {
2275
+ const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
2276
+ return Object.hasOwn(commands, name) ? commands[name] : undefined;
2277
+ }
1480
2278
  function scopeOf(commands, extra, aliases) {
1481
2279
  return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
1482
2280
  }
@@ -1516,8 +2314,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1516
2314
  `);
1517
2315
  }
1518
2316
  function printError(prefix, message, hint, cause) {
1519
- const colors = paint(process18.stderr);
1520
- const styled = takesControlCodes(process18.stderr);
2317
+ const colors = paint(process22.stderr);
2318
+ const styled = takesControlCodes(process22.stderr);
1521
2319
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1522
2320
  const under = (label, text, tint) => text === undefined ? "" : `
1523
2321
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1527,8 +2325,8 @@ function runHint(command, effect) {
1527
2325
  return `run \`${command}\`${effect === undefined ? "" : ` to ${effect}`}`;
1528
2326
  }
1529
2327
  function printHint(hint) {
1530
- const colors = paint(process18.stderr);
1531
- console.error(` ${takesControlCodes(process18.stderr) ? colors.yellow("hint") : "hint:"} ${hint}`);
2328
+ const colors = paint(process22.stderr);
2329
+ console.error(` ${takesControlCodes(process22.stderr) ? colors.yellow("hint") : "hint:"} ${hint}`);
1532
2330
  }
1533
2331
  function printJsonError(message, hint, cause) {
1534
2332
  console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
@@ -1567,23 +2365,23 @@ async function dispatch(level, typed, { version, redact }) {
1567
2365
  }
1568
2366
  }
1569
2367
  if (name === undefined && level.path.length > 1) {
1570
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process18.stderr));
2368
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process22.stderr));
1571
2369
  return 2;
1572
2370
  }
1573
2371
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1574
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process18.stdout));
2372
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process22.stdout));
1575
2373
  return 0;
1576
2374
  }
1577
2375
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
1578
2376
  console.log(version);
1579
2377
  return 0;
1580
2378
  }
1581
- let command = level.commands[level.aliases?.[name] ?? name];
2379
+ let command = lookup(level, name);
1582
2380
  let rest = args;
1583
2381
  let ran = name;
1584
2382
  if (command === undefined && level.lazy.length > 0) {
1585
2383
  level = await expand(level, [...level.path.slice(1), ...argv]);
1586
- command = level.commands[level.aliases?.[name] ?? name];
2384
+ command = lookup(level, name);
1587
2385
  }
1588
2386
  if (command === undefined && level.defaultCommand !== undefined) {
1589
2387
  command = level.commands[level.defaultCommand];
@@ -1663,18 +2461,19 @@ async function leafCandidates(run, words) {
1663
2461
  async function candidates(scope, defaultCommand, words, before = []) {
1664
2462
  const [word = "", ...rest] = words;
1665
2463
  const listing = rest.length === 0 && !word.startsWith("-");
1666
- let { commands, aliases } = scope;
1667
- let command = commands[aliases?.[word] ?? word];
2464
+ let { commands } = scope;
2465
+ let command = lookup(scope, word);
1668
2466
  if (listing || command === undefined) {
1669
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
1670
- command = commands[aliases?.[word] ?? word];
2467
+ const expanded = await expand(scope, [...before, ...words]);
2468
+ commands = expanded.commands;
2469
+ command = lookup(expanded, word);
1671
2470
  }
1672
2471
  if (listing) {
1673
2472
  const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1674
2473
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1675
2474
  const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1676
2475
  const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1677
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
2476
+ return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
1678
2477
  }
1679
2478
  if (command === undefined) {
1680
2479
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
@@ -1682,6 +2481,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1682
2481
  }
1683
2482
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1684
2483
  }
2484
+ var COMPLETIONS = "--completions";
2485
+ function flagValue([flag = "", ...rest]) {
2486
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
2487
+ }
2488
+ function printCompletionScript(name, args) {
2489
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
2490
+ if (shell === undefined || args.length !== 1) {
2491
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
2492
+ return 2;
2493
+ }
2494
+ console.log(completionScript(shell, [name]).trimEnd());
2495
+ return 0;
2496
+ }
1685
2497
  async function printCandidates(found) {
1686
2498
  for (const line of await found)
1687
2499
  console.log(line);
@@ -1692,27 +2504,32 @@ function packageVersion(entry = Bun.main) {
1692
2504
  try {
1693
2505
  resolved = realpathSync2(entry);
1694
2506
  } catch {}
1695
- for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
2507
+ for (let dir = dirname4(resolved);; dir = dirname4(dir)) {
1696
2508
  try {
1697
- const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
2509
+ const { version } = JSON.parse(readFileSync6(join8(dir, "package.json"), "utf8"));
1698
2510
  if (typeof version === "string")
1699
2511
  return version;
1700
2512
  } catch {}
1701
- if (dirname3(dir) === dir)
2513
+ if (dirname4(dir) === dir)
1702
2514
  return "0.0.0";
1703
2515
  }
1704
2516
  }
1705
2517
  async function runCli(cli, argv = scriptArgs()) {
1706
2518
  const version = cli.version ?? packageVersion();
2519
+ const answered = await askpassClient(argv);
2520
+ if (answered !== undefined)
2521
+ return answered;
1707
2522
  if (argv[0] === COMPLETE)
1708
2523
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
2524
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
2525
+ return printCompletionScript(cli.name, flagValue(argv));
1709
2526
  const started = performance.now();
1710
2527
  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 });
1711
2528
  const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1712
2529
  notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1713
2530
  if (cli.usage !== false) {
1714
2531
  try {
1715
- recordUsage(usageEntry(cli.name, command, argv, code));
2532
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
1716
2533
  } catch {}
1717
2534
  }
1718
2535
  return code;
@@ -1721,8 +2538,7 @@ function commandPath(scope, argv) {
1721
2538
  const path = [];
1722
2539
  let level = scope;
1723
2540
  for (const word of argv.filter((each) => !each.startsWith("-"))) {
1724
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1725
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
2541
+ const command = lookup(level, word);
1726
2542
  if (command === undefined)
1727
2543
  break;
1728
2544
  path.push(word);
@@ -1732,7 +2548,12 @@ function commandPath(scope, argv) {
1732
2548
  }
1733
2549
  return path.length === 0 ? undefined : path.join(" ");
1734
2550
  }
2551
+
2552
+ // ../kit/src/index.ts
2553
+ init_config();
2554
+
1735
2555
  // ../kit/src/excerpt.ts
2556
+ init_text2();
1736
2557
  var BUN_CHECK_BLOCK = /<error file=[\s\S]*?<\/error>/g;
1737
2558
  var BUN_CHECK_SOURCE = /<source>[\s\S]*?<\/source>\n?/g;
1738
2559
  var BUN_CHECK_ATTRIBUTE = /(\w+)="([^"]*)"/g;
@@ -1839,7 +2660,7 @@ function squeeze(lines) {
1839
2660
  out.pop();
1840
2661
  return out;
1841
2662
  }
1842
- function cut(shown) {
2663
+ function cut2(shown) {
1843
2664
  return shown.length > MAX_LINES ? [...shown.slice(0, MAX_LINES), `... ${shown.length - MAX_LINES} more lines`].join(`
1844
2665
  `) : shown.join(`
1845
2666
  `);
@@ -1849,13 +2670,17 @@ function recognised(lines, parsers) {
1849
2670
  }
1850
2671
  function toolExcerpt(lines) {
1851
2672
  const found = recognised(lines.map((line) => stripAnsi(line)), TOOL_PARSERS);
1852
- return found === undefined ? undefined : cut(squeeze(found));
2673
+ return found === undefined ? undefined : cut2(squeeze(found));
1853
2674
  }
1854
- // ../kit/src/folders.ts
1855
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
2675
+
2676
+ // ../kit/src/index.ts
2677
+ init_folders();
2678
+ init_format();
2679
+
1856
2680
  // ../kit/src/git.ts
1857
- import { basename, dirname as dirname4 } from "path";
1858
- import process19 from "process";
2681
+ init_args();
2682
+ import { basename, dirname as dirname5 } from "path";
2683
+ import process23 from "process";
1859
2684
  var ORIGIN_PREFIX = /^origin\//;
1860
2685
  var GIT_NETWORK_MS = 60000;
1861
2686
  async function git(args, timeoutMs) {
@@ -1876,7 +2701,15 @@ async function resolveCommit(ref) {
1876
2701
  async function fetchBranch(branch) {
1877
2702
  if (branch.startsWith("-") || !await gitOk(["check-ref-format", "--branch", branch]))
1878
2703
  fail(`${branch} is not a branch name`);
1879
- await git(["fetch", "-q", "origin", `refs/heads/${branch}`], GIT_NETWORK_MS);
2704
+ const ref = `refs/heads/${branch}`;
2705
+ const fetched = await runTool("git fetch", ["git", "fetch", "-q", "origin", ref], { timeoutMs: GIT_NETWORK_MS });
2706
+ if (fetched.code === 0)
2707
+ return true;
2708
+ const listed = await runTool("git ls-remote", ["git", "ls-remote", "--exit-code", "origin", ref], { timeoutMs: GIT_NETWORK_MS });
2709
+ if (listed.code !== 2)
2710
+ throw new Error(`git fetch -q origin ${ref}: ${fetched.stderr.trim() || `exit ${fetched.code}`}`);
2711
+ await gitOk(["update-ref", "-d", `refs/remotes/origin/${branch}`]);
2712
+ return false;
1880
2713
  }
1881
2714
  async function defaultBranch() {
1882
2715
  const head = (await runTool("git symbolic-ref", ["git", "symbolic-ref", "--short", "-q", "refs/remotes/origin/HEAD"])).stdout.trim();
@@ -1885,9 +2718,10 @@ async function defaultBranch() {
1885
2718
  async function leaveWorktree() {
1886
2719
  const common = await git(["rev-parse", "--path-format=absolute", "--git-common-dir"]);
1887
2720
  if (basename(common) === ".git")
1888
- process19.chdir(dirname4(common));
2721
+ process23.chdir(dirname5(common));
1889
2722
  }
1890
2723
  // ../kit/src/limit.ts
2724
+ init_args();
1891
2725
  function limitOptions(fallback) {
1892
2726
  return {
1893
2727
  limit: { type: "string", short: "n", description: `show at most this many rows, the rest counted (${fallback})` },
@@ -1908,35 +2742,45 @@ function capped(rows, limit) {
1908
2742
  const more = rows.length - limit;
1909
2743
  return more > 0 ? { shown: rows.slice(0, limit), footer: moreFooter(more) } : { shown: [...rows], footer: undefined };
1910
2744
  }
2745
+
2746
+ // ../kit/src/index.ts
2747
+ init_mode();
2748
+
1911
2749
  // ../kit/src/pool.ts
1912
- async function pool(items, limit, task) {
2750
+ async function pool(items, limit, task, onDone) {
1913
2751
  const results = Array.from({ length: items.length });
1914
2752
  let next = 0;
2753
+ let done = 0;
1915
2754
  async function worker() {
1916
2755
  while (next < items.length) {
1917
2756
  const index = next++;
1918
2757
  results[index] = await task(items[index]);
2758
+ onDone?.(++done, items.length);
1919
2759
  }
1920
2760
  }
1921
2761
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1922
2762
  return results;
1923
2763
  }
2764
+ // ../kit/src/report.ts
2765
+ init_style();
2766
+ init_text2();
1924
2767
  // ../kit/src/secrets.ts
1925
2768
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
2769
+ var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1926
2770
  // ../kit/src/sessions.ts
1927
- import { homedir as homedir4 } from "os";
1928
- import { join as join6 } from "path";
1929
- import process20 from "process";
2771
+ import { homedir as homedir5 } from "os";
2772
+ import { join as join9 } from "path";
2773
+ import process24 from "process";
1930
2774
  var {Glob } = globalThis.Bun;
1931
2775
  var SESSION_FILES = new Glob("*.json");
1932
2776
  var ACCOUNT_DIRS = new Glob("*/sessions");
1933
2777
  async function sessionDirs() {
1934
- const home = homedir4();
1935
- const dirs = new Set([join6(home, ".claude", "sessions")]);
1936
- if (process20.env.CLAUDE_CONFIG_DIR !== undefined)
1937
- dirs.add(join6(process20.env.CLAUDE_CONFIG_DIR, "sessions"));
2778
+ const home = homedir5();
2779
+ const dirs = new Set([join9(home, ".claude", "sessions")]);
2780
+ if (process24.env.CLAUDE_CONFIG_DIR !== undefined)
2781
+ dirs.add(join9(process24.env.CLAUDE_CONFIG_DIR, "sessions"));
1938
2782
  try {
1939
- for await (const dir of ACCOUNT_DIRS.scan({ cwd: join6(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
2783
+ for await (const dir of ACCOUNT_DIRS.scan({ cwd: join9(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
1940
2784
  dirs.add(dir);
1941
2785
  } catch {}
1942
2786
  return [...dirs];
@@ -1980,7 +2824,7 @@ async function liveSessions() {
1980
2824
  }
1981
2825
  async function currentSession(sessions) {
1982
2826
  const byPid = new Map(sessions.map((session) => [session.pid, session]));
1983
- let pid = process20.ppid;
2827
+ let pid = process24.ppid;
1984
2828
  for (let depth = 0;depth < 32 && pid > 1; depth++) {
1985
2829
  const session = byPid.get(pid);
1986
2830
  if (session !== undefined)
@@ -1992,8 +2836,18 @@ async function currentSession(sessions) {
1992
2836
  }
1993
2837
  return;
1994
2838
  }
2839
+
2840
+ // ../kit/src/index.ts
2841
+ init_style();
2842
+ init_text2();
2843
+ init_theme();
2844
+ init_user_config();
2845
+
1995
2846
  // ../kit/src/watch.ts
1996
- import process21 from "process";
2847
+ init_args();
2848
+ init_input();
2849
+ init_style();
2850
+ import process25 from "process";
1997
2851
  import { format } from "util";
1998
2852
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1999
2853
  var DEFAULT_SECONDS = 2;
@@ -2015,7 +2869,7 @@ function withoutWatch(args) {
2015
2869
  }
2016
2870
  return rest;
2017
2871
  }
2018
- async function watching(value, step, stream = process21.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
2872
+ async function watching(value, step, stream = process25.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
2019
2873
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
2020
2874
  if (!takesControlCodes(stream))
2021
2875
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -2023,12 +2877,12 @@ async function watching(value, step, stream = process21.stdout, sleep = Bun.slee
2023
2877
  for (let round = 0;round < rounds; round++) {
2024
2878
  const held = [];
2025
2879
  const { log, info } = console;
2026
- const write = process21.stdout.write.bind(process21.stdout);
2880
+ const write = process25.stdout.write.bind(process25.stdout);
2027
2881
  const hold = (...parts) => void held.push(`${format(...parts)}
2028
2882
  `);
2029
2883
  console.log = hold;
2030
2884
  console.info = hold;
2031
- process21.stdout.write = (text) => {
2885
+ process25.stdout.write = (text) => {
2032
2886
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
2033
2887
  return true;
2034
2888
  };
@@ -2037,13 +2891,15 @@ async function watching(value, step, stream = process21.stdout, sleep = Bun.slee
2037
2891
  } finally {
2038
2892
  console.log = log;
2039
2893
  console.info = info;
2040
- process21.stdout.write = write;
2894
+ process25.stdout.write = write;
2041
2895
  }
2042
2896
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
2043
2897
  await sleep(interval);
2044
2898
  }
2045
2899
  return code;
2046
2900
  }
2901
+ // ../kit/src/workspace-root.ts
2902
+ init_user_config();
2047
2903
  // src/args.ts
2048
2904
  var repoOption = {
2049
2905
  repo: { type: "string", short: "r", description: "owner/name of the repository, instead of the one origin points at" }
@@ -2065,7 +2921,7 @@ function issueNumbers(values, usage) {
2065
2921
 
2066
2922
  // src/checklist.ts
2067
2923
  var BOX = /^(\s*[-*+] \[)([ x])(\]\s)(.*?)\r?$/is;
2068
- var FENCE = /^\s*(`{3,}|~{3,})/;
2924
+ var FENCE = /^\s*(`{3,}(?!.*`)|~{3,})/;
2069
2925
  var LIST_ITEM = /^\s*(?:[-*+]|\d+[.)])\s/;
2070
2926
  var INDENT_CODE = /^(?: {4}|\t)/;
2071
2927
  function boxes(body) {
@@ -2096,23 +2952,48 @@ function boxes(body) {
2096
2952
  return found;
2097
2953
  }
2098
2954
  var INDENT = /^\s*/;
2955
+ var LINE_END = /\r?\n/;
2956
+ var LINE_ENDS = /(\r?\n)/;
2957
+ function indentOf(line) {
2958
+ return INDENT.exec(line)?.[0].length ?? 0;
2959
+ }
2960
+ function lineEnding(body) {
2961
+ return body.includes(`\r
2962
+ `) ? `\r
2963
+ ` : `
2964
+ `;
2965
+ }
2966
+ function afterBox(lines, line) {
2967
+ const depth = indentOf(lines[line] ?? "");
2968
+ let end = line + 1;
2969
+ for (let next = line + 1;next < lines.length; next++) {
2970
+ const text = lines[next] ?? "";
2971
+ if (text.trim() === "")
2972
+ continue;
2973
+ if (indentOf(text) <= depth)
2974
+ break;
2975
+ end = next + 1;
2976
+ }
2977
+ return end;
2978
+ }
2979
+ function insertLines(body, at, added) {
2980
+ const eol = lineEnding(body);
2981
+ const parts = body.split(LINE_ENDS);
2982
+ if (2 * at >= parts.length)
2983
+ return `${body}${eol}${added.join(eol)}`;
2984
+ parts.splice(2 * at, 0, added.map((line) => `${line}${eol}`).join(""));
2985
+ return parts.join("");
2986
+ }
2099
2987
  function appendBoxes(body, texts) {
2100
- const end = body.includes(`\r
2101
- `) ? "\r" : "";
2988
+ const eol = lineEnding(body);
2102
2989
  const last = boxes(body).at(-1);
2103
- const lines = body.split(`
2104
- `);
2990
+ const lines = body.split(LINE_END);
2105
2991
  const indent = last === undefined ? "" : INDENT.exec(lines[last.line] ?? "")?.[0] ?? "";
2106
- const added = texts.map((text) => `${indent}- [ ] ${text}${end}`);
2992
+ const added = texts.map((text) => `${indent}- [ ] ${text}`);
2107
2993
  if (last === undefined)
2108
- return body.trim() === "" ? added.join(`
2109
- `) : `${body.trimEnd()}${end}
2110
- ${end}
2111
- ${added.join(`
2112
- `)}`;
2113
- lines.splice(last.line + 1, 0, ...added);
2114
- return lines.join(`
2115
- `);
2994
+ return body.trim() === "" ? added.join(eol) : `${body.trimEnd()}${eol}${eol}${added.join(eol)}${body.endsWith(`
2995
+ `) ? eol : ""}`;
2996
+ return insertLines(body, afterBox(lines, last.line), added);
2116
2997
  }
2117
2998
  function numberedBody(body) {
2118
2999
  const lines = body.replaceAll(`\r
@@ -2174,8 +3055,10 @@ function tickReferences(body, wanted) {
2174
3055
  }
2175
3056
 
2176
3057
  // src/claims.ts
2177
- var TAKEN = /^\s*taken by session ([\w.@:-]+?)\.?\s*$/i;
2178
- var RELEASED = /^\s*released by session ([\w.@:-]+?)\.?\s*$/i;
3058
+ var TAKEN = /^taken by session (.+)$/i;
3059
+ var RELEASED = /^released by session (.+)$/i;
3060
+ var WITHDRAWN = /^withdrawn by session (.+)$/i;
3061
+ var UNCLAIMABLE = /^\s|\s$|[\p{Cc}\u2028\u2029]|[,;:]\s/u;
2179
3062
  var LANE = /^lane-([^-]+)-/;
2180
3063
  function takenComment(name) {
2181
3064
  return `Taken by session ${name}.`;
@@ -2183,28 +3066,65 @@ function takenComment(name) {
2183
3066
  function releasedComment(name) {
2184
3067
  return `Released by session ${name}.`;
2185
3068
  }
2186
- function isClaimant(comment, author) {
3069
+ function withdrawnComment(name) {
3070
+ return `Withdrawn by session ${name}.`;
3071
+ }
3072
+ function claimable(name) {
3073
+ return name !== "" && !UNCLAIMABLE.test(name);
3074
+ }
3075
+ function named(sentence, body) {
3076
+ const name = sentence.exec(body.trim())?.[1];
3077
+ const bare = name?.endsWith(".") === true ? name.slice(0, -1) : name;
3078
+ return bare !== undefined && claimable(bare) ? bare : undefined;
3079
+ }
3080
+ function isClaimant(comment, author) {
2187
3081
  return author === undefined || comment.user === undefined || comment.user.login === author;
2188
3082
  }
3083
+ function inOrder(comments) {
3084
+ return comments.toSorted((a, b) => Date.parse(a.created_at) - Date.parse(b.created_at));
3085
+ }
3086
+ function claimEvents(comments, author) {
3087
+ const kept = [];
3088
+ for (const comment of comments.filter((each) => isClaimant(each, author))) {
3089
+ const withdrawn = named(WITHDRAWN, comment.body);
3090
+ if (withdrawn === undefined) {
3091
+ kept.push(comment);
3092
+ continue;
3093
+ }
3094
+ const take = kept.findLastIndex((each) => named(TAKEN, each.body) === withdrawn);
3095
+ if (take !== -1)
3096
+ kept.splice(take, 1);
3097
+ }
3098
+ return kept;
3099
+ }
2189
3100
  function latestClaim(comments, author) {
2190
3101
  let claim;
2191
- for (const comment of comments.filter((each) => isClaimant(each, author)).sort((a, b) => Date.parse(a.created_at) - Date.parse(b.created_at))) {
2192
- const taken = TAKEN.exec(comment.body)?.[1];
3102
+ for (const comment of claimEvents(inOrder(comments), author)) {
3103
+ const taken = named(TAKEN, comment.body);
2193
3104
  if (taken !== undefined) {
2194
3105
  claim = { holder: taken, at: comment.created_at };
2195
3106
  continue;
2196
3107
  }
2197
- if (claim !== undefined && RELEASED.exec(comment.body)?.[1] === claim.holder)
3108
+ if (claim !== undefined && named(RELEASED, comment.body) === claim.holder)
2198
3109
  claim = undefined;
2199
3110
  }
2200
3111
  return claim;
2201
3112
  }
3113
+ function firstClaimSince(comments, seen, author) {
3114
+ const fresh = new Set(inOrder(comments).slice(seen));
3115
+ for (const comment of claimEvents(inOrder(comments), author)) {
3116
+ const taken = fresh.has(comment) ? named(TAKEN, comment.body) : undefined;
3117
+ if (taken !== undefined)
3118
+ return taken;
3119
+ }
3120
+ return;
3121
+ }
2202
3122
  function laneSuffix(session) {
2203
3123
  const suffix = session.slice(session.lastIndexOf("-") + 1);
2204
3124
  return session.includes("-") && suffix !== "" ? suffix : undefined;
2205
3125
  }
2206
3126
  function latestNote(comments) {
2207
- return comments.filter((comment) => !TAKEN.test(comment.body) && !RELEASED.test(comment.body)).sort((a, b) => Date.parse(a.created_at) - Date.parse(b.created_at)).at(-1);
3127
+ return inOrder(comments.filter((comment) => [TAKEN, RELEASED, WITHDRAWN].every((sentence) => named(sentence, comment.body) === undefined))).at(-1);
2208
3128
  }
2209
3129
  function holderSession(holder, sessions) {
2210
3130
  const own = sessions.find((session) => session.name === holder);
@@ -2215,9 +3135,9 @@ function holderSession(holder, sessions) {
2215
3135
  }
2216
3136
 
2217
3137
  // src/good.ts
2218
- import process23 from "process";
3138
+ import process27 from "process";
2219
3139
  function good(text) {
2220
- return role("ok", process23.stdout)(text);
3140
+ return role("ok", process27.stdout)(text);
2221
3141
  }
2222
3142
 
2223
3143
  // src/config.ts
@@ -2250,12 +3170,10 @@ async function loadSettings(home) {
2250
3170
  }
2251
3171
 
2252
3172
  // src/tea.ts
2253
- import process25 from "process";
3173
+ import process28 from "process";
2254
3174
 
2255
3175
  // src/forge.ts
2256
- import { homedir as homedir5 } from "os";
2257
- import { join as join7 } from "path";
2258
- import process24 from "process";
3176
+ import { join as join10 } from "path";
2259
3177
 
2260
3178
  // src/remote.ts
2261
3179
  var SCP_LIKE = /^(?:([^@/]+)@)?([^:/]+):(?!\/)(.+?)(?:\.git)?\/?$/;
@@ -2312,8 +3230,7 @@ function loginHosts(config) {
2312
3230
  return hosts;
2313
3231
  }
2314
3232
  function teaConfigPath() {
2315
- const base = process24.env.XDG_CONFIG_HOME;
2316
- return join7(base !== undefined && base !== "" ? base : join7(homedir5(), ".config"), "tea", "config.yml");
3233
+ return join10(configBase(), "tea", "config.yml");
2317
3234
  }
2318
3235
  async function readConfig() {
2319
3236
  try {
@@ -2375,22 +3292,22 @@ function repoFlag(repo) {
2375
3292
  return repo === undefined ? [] : ["--repo", repo];
2376
3293
  }
2377
3294
  function usesGt() {
2378
- const PATH = process25.env.PATH ?? "";
3295
+ const PATH = process28.env.PATH ?? "";
2379
3296
  return Bun.which("tea", { PATH }) === null && Bun.which("gt", { PATH }) !== null;
2380
3297
  }
2381
3298
  var injected;
2382
3299
  async function injectLogin(repo) {
2383
- if (process25.env.GITEA_TOKEN !== undefined && process25.env.GITEA_TOKEN !== "")
3300
+ if (process28.env.GITEA_TOKEN !== undefined && process28.env.GITEA_TOKEN !== "")
2384
3301
  return;
2385
3302
  const login = await pickLogin(repo === undefined);
2386
3303
  if (login === undefined)
2387
3304
  return;
2388
3305
  injected = login.token;
2389
- process25.env.GITEA_TOKEN = login.token;
2390
- process25.env.GITEA_CLI_HOST = login.url;
3306
+ process28.env.GITEA_TOKEN = login.token;
3307
+ process28.env.GITEA_CLI_HOST = login.url;
2391
3308
  }
2392
3309
  function scrub(text) {
2393
- const token = injected ?? process25.env.GITEA_TOKEN;
3310
+ const token = injected ?? process28.env.GITEA_TOKEN;
2394
3311
  return token === undefined || token === "" ? text : text.replaceAll(token, "***");
2395
3312
  }
2396
3313
  function failureText(stdout, stderr, code) {
@@ -2448,8 +3365,12 @@ async function repoSend(method, path, fields, repo) {
2448
3365
  const flags = Object.entries(fields).flatMap(([name, value]) => typeof value === "string" ? ["-f", `${name}=${value}`] : ["-F", `${name}=${JSON.stringify(value)}`]);
2449
3366
  return runApi(full, ["-X", method, ...flags, full], repo);
2450
3367
  }
3368
+ async function repoWriteOrEmpty(method, path, fields, repo) {
3369
+ const text = await repoSend(method, path, fields, repo);
3370
+ return text.trim() === "" ? undefined : parseJson(`repos/{owner}/{repo}/${path}`, text);
3371
+ }
2451
3372
  async function repoWrite(method, path, fields, repo) {
2452
- return parseJson(`repos/{owner}/{repo}/${path}`, await repoSend(method, path, fields, repo));
3373
+ return await repoWriteOrEmpty(method, path, fields, repo) ?? parseJson(`repos/{owner}/{repo}/${path}`, "");
2453
3374
  }
2454
3375
  async function repoApiText(path, repo) {
2455
3376
  const full = `repos/{owner}/{repo}/${path}`;
@@ -2508,7 +3429,7 @@ function dueDate(milestone) {
2508
3429
  }
2509
3430
  function progress(milestone) {
2510
3431
  const total = milestone.open_issues + milestone.closed_issues;
2511
- return total === 0 ? "" : `${Math.round(milestone.closed_issues / total * 100)}%`;
3432
+ return total === 0 ? "" : `${Math.floor(milestone.closed_issues * 100 / total)}%`;
2512
3433
  }
2513
3434
  async function createMilestone(title, description, due, repo) {
2514
3435
  const fields = { title };
@@ -2686,7 +3607,6 @@ function standing(claim, sessions) {
2686
3607
  return session === undefined ? { state: "away", claim } : { state: "taken", claim, session };
2687
3608
  }
2688
3609
  var NOTE_WIDTH = 100;
2689
- var STATES = new Set(["available", "taken", "away"]);
2690
3610
  function dimmed(text) {
2691
3611
  return text === "" ? "" : paint(process.stdout).dim(text);
2692
3612
  }
@@ -2775,7 +3695,7 @@ var boardOptions = {
2775
3695
  labels: { type: "string", short: "L", description: "only issues with these labels, comma separated" },
2776
3696
  milestone: { type: "string", short: "m", description: "only issues of this milestone, a title or an id" },
2777
3697
  query: { type: "string", description: "only issues whose title matches this, a case-insensitive regex such as dom|eager" },
2778
- state: { type: "string", description: "only issues in this state: available, taken or away (claimed, no live session here)" },
3698
+ state: { type: "string", choices: ["available", "taken", "away"], description: "only issues in this state (away: claimed, no live session here)" },
2779
3699
  ...limitOptions(BOARD_LIMIT),
2780
3700
  json: jsonOption("number, title, labels, state, holder, since, session, boxesTotal, boxesLeft and note (author, at, body of the latest comment that is not a claim)"),
2781
3701
  watch: watchOption("the board"),
@@ -2788,8 +3708,6 @@ async function board(args) {
2788
3708
  return watching(values.watch, async () => board(withoutWatch(args)));
2789
3709
  const state = values.state;
2790
3710
  const limit = limitOf(values, BOARD_LIMIT);
2791
- if (state !== undefined && !STATES.has(state))
2792
- fail(`--state takes available, taken or away, not ${state}`);
2793
3711
  let query;
2794
3712
  try {
2795
3713
  query = values.query === undefined ? undefined : new RegExp(values.query, "i");
@@ -2809,12 +3727,12 @@ async function board(args) {
2809
3727
  return 0;
2810
3728
  }
2811
3729
  async function me(as, sessions) {
2812
- if (as !== undefined)
2813
- return as;
2814
- const session = await currentSession(sessions);
2815
- if (session === undefined)
3730
+ const name = as ?? (await currentSession(sessions))?.name;
3731
+ if (name === undefined)
2816
3732
  fail("not run from a Claude Code session: pass --as <name>");
2817
- return session.name;
3733
+ if (!claimable(name))
3734
+ fail(`a claim cannot carry the name ${JSON.stringify(name)}, empty, padded or holding a line break: pass --as`);
3735
+ return name;
2818
3736
  }
2819
3737
  var takeUsage = `ft take <n>...
2820
3738
 
@@ -2878,9 +3796,16 @@ async function take(args) {
2878
3796
  if (current.state === "away" && values["take-stale"] !== true)
2879
3797
  fail(`#${number} was taken by ${current.claim.holder} ${formatAge(current.claim.at)}, which no session here answers to: it may run on another machine`, 1, runHint(`ft take ${number} --take-stale`, "take it over"));
2880
3798
  await comment(number, takenComment(name), values.repo);
2881
- const standingNow = latestClaim(await commentsOf(number, values.repo), author);
2882
- if (standingNow?.holder !== name)
2883
- fail(`#${number} was taken by ${standingNow?.holder ?? "another session"} at the same moment`, 1);
3799
+ const winner = firstClaimSince(await commentsOf(number, values.repo), comments.length, author);
3800
+ if (winner !== name) {
3801
+ const taken = `#${number} was taken by ${winner ?? "another session"} at the same moment`;
3802
+ try {
3803
+ await comment(number, withdrawnComment(name), values.repo);
3804
+ } catch (error) {
3805
+ fail(`${taken}, and withdrawing this claim failed: ${error instanceof Error ? error.message : String(error)}`, 1, runHint(`ft comment ${number} '${withdrawnComment(name)}'`, "withdraw it"));
3806
+ }
3807
+ fail(taken, 1);
3808
+ }
2884
3809
  console.log(good(`took #${number} as ${name}: ${found.title}`));
2885
3810
  });
2886
3811
  }
@@ -2949,7 +3874,7 @@ async function drop(args) {
2949
3874
  }
2950
3875
 
2951
3876
  // src/commands/ci.ts
2952
- import process26 from "process";
3877
+ import process29 from "process";
2953
3878
 
2954
3879
  // src/git.ts
2955
3880
  async function tagsAt(commit) {
@@ -3216,7 +4141,7 @@ async function ci2(args) {
3216
4141
  return;
3217
4142
  }
3218
4143
  const json = values.json === true;
3219
- const live = takesControlCodes(process26.stderr) && takesControlCodes(process26.stdout) && !json && values.quiet !== true;
4144
+ const live = takesControlCodes(process29.stderr) && takesControlCodes(process29.stdout) && !json && values.quiet !== true;
3220
4145
  const runs = await waitForCi({
3221
4146
  tool: "ft ci",
3222
4147
  short,
@@ -3242,8 +4167,8 @@ async function ci2(args) {
3242
4167
  return stall === undefined ? undefined : { message: `runs queued on ${short} are not moving: ${stall.reason}`, certain: stall.certain };
3243
4168
  },
3244
4169
  lines: (spinner, found, started) => [
3245
- ciHeader(spinner, `CI on ${short}`, started, process26.stderr),
3246
- ...(found ?? []).map((run) => ` ${runLine(run, process26.stderr, undefined, run.commit_sha.slice(0, 7))}`)
4170
+ ciHeader(spinner, `CI on ${short}`, started, process29.stderr),
4171
+ ...(found ?? []).map((run) => ` ${runLine(run, process29.stderr, undefined, run.commit_sha.slice(0, 7))}`)
3247
4172
  ]
3248
4173
  });
3249
4174
  const status = overall(runs);
@@ -3260,7 +4185,7 @@ async function ci2(args) {
3260
4185
  }
3261
4186
  if (live) {
3262
4187
  for (const run of runs)
3263
- console.log(runLine(run, process26.stdout, undefined, run.commit_sha.slice(0, 7)));
4188
+ console.log(runLine(run, process29.stdout, undefined, run.commit_sha.slice(0, 7)));
3264
4189
  }
3265
4190
  if (status !== "failure") {
3266
4191
  if (live)
@@ -3279,7 +4204,7 @@ run ${run.id} failed${run.commit_sha === sha ? "" : `, testing every commit from
3279
4204
  }
3280
4205
 
3281
4206
  // src/commands/digest.ts
3282
- import process27 from "process";
4207
+ import process30 from "process";
3283
4208
  var RUNS_SCANNED = 50;
3284
4209
  var TITLE_WIDTH2 = 70;
3285
4210
  var SHOWN = 8;
@@ -3329,13 +4254,13 @@ async function quietly(read) {
3329
4254
  }
3330
4255
  }
3331
4256
  async function staleTodos() {
3332
- const bin = Bun.which("todo-scan", { PATH: process27.env.PATH ?? "" });
4257
+ const bin = Bun.which("src", { PATH: process30.env.PATH ?? "" });
3333
4258
  if (bin === null)
3334
4259
  return [];
3335
4260
  let found;
3336
4261
  try {
3337
- const ran = await runCommand([bin, "--stale", "--json"]);
3338
- found = JSON.parse(Buffer.concat(ran.chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString());
4262
+ const ran = await runCommand([bin, "todo-scan", "--stale", "--json"]);
4263
+ found = JSON.parse(ran.stdout);
3339
4264
  } catch {
3340
4265
  return [];
3341
4266
  }
@@ -3351,8 +4276,8 @@ async function staleTodos() {
3351
4276
  return [...byIssue.values()];
3352
4277
  }
3353
4278
  function claimLine(row, now) {
3354
- const id = role("id", process27.stdout);
3355
- return [id(`#${row.number}`), row.holder, paint(process27.stdout).dim(formatAge(row.since, now)), row.boxesTotal === 0 ? "" : `${row.boxesLeft}/${row.boxesTotal} left`, truncate(row.title, TITLE_WIDTH2)];
4279
+ const id = role("id", process30.stdout);
4280
+ return [id(`#${row.number}`), row.holder, paint(process30.stdout).dim(formatAge(row.since, now)), row.boxesTotal === 0 ? "" : `${row.boxesLeft}/${row.boxesTotal} left`, truncate(row.title, TITLE_WIDTH2)];
3356
4281
  }
3357
4282
  function capped2(lines) {
3358
4283
  return lines.length > SHOWN ? [...lines.slice(0, SHOWN), `... ${lines.length - SHOWN} more`] : lines;
@@ -3363,13 +4288,13 @@ function renderDigest(digest, now = Date.now()) {
3363
4288
  `) },
3364
4289
  { heading: "claimed, no live session here", tone: "warn", count: digest.away.length, lines: table(digest.away.map((row) => claimLine(row, now))).split(`
3365
4290
  `) },
3366
- { heading: "CI on the default branch", tone: "failed", count: digest.ci.length, lines: digest.ci.map((run) => `${run.workflow} ${badge(run.status, process27.stdout)} (run ${run.id}) ${truncate(upTo(run.title, `
4291
+ { heading: "CI on the default branch", tone: "failed", count: digest.ci.length, lines: digest.ci.map((run) => `${run.workflow} ${badge(run.status, process30.stdout)} (run ${run.id}) ${truncate(upTo(run.title, `
3367
4292
  `), TITLE_WIDTH2)}`) },
3368
4293
  { heading: "unpushed commits", tone: "queued", count: digest.unpushed.length, lines: capped2(digest.unpushed) },
3369
- { heading: "dirty files", tone: "warn", count: digest.dirty.length, lines: capped2(digest.dirty.map((file) => `${file.status} ${role("path", process27.stdout)(file.path)}`)) },
4294
+ { heading: "dirty files", tone: "warn", count: digest.dirty.length, lines: capped2(digest.dirty.map((file) => `${file.status} ${role("path", process30.stdout)(file.path)}`)) },
3370
4295
  { heading: "stale TODO comments", tone: "skipped", count: digest.stale.length, lines: capped2(digest.stale.map((todo) => `${todo.issue} closed: ${todo.comments.map((each) => `${each.path}:${each.line}`).join(", ")}`)) }
3371
4296
  ].filter((each) => each.count > 0);
3372
- return sections.length === 0 ? "nothing to pick up" : sections.map(({ heading, tone, count, lines }) => `${section(heading, count, process27.stdout, process27.env, tone)}
4297
+ return sections.length === 0 ? "nothing to pick up" : sections.map(({ heading, tone, count, lines }) => `${section(heading, count, process30.stdout, process30.env, tone)}
3373
4298
  ${lines.join(`
3374
4299
  `).replace(LINE_START2, " ")}`).join(`
3375
4300
 
@@ -3405,6 +4330,212 @@ async function digest(args) {
3405
4330
  return 0;
3406
4331
  }
3407
4332
 
4333
+ // src/commands/dispatch.ts
4334
+ import process31 from "process";
4335
+
4336
+ // src/commands/watch.ts
4337
+ var usage4 = `ft watch [--after <id>]
4338
+
4339
+ Waits for runs to finish: those newer than run <id>, or else the ones in progress now.
4340
+ Prints nothing but failures and each run's final status with --quiet, and a JSON result with --json.`;
4341
+ var EXITS3 = [[0, "every one passed or was skipped"], [1, "one failed or was cancelled"], [2, "a timeout or a stalled queue"]];
4342
+ var options3 = {
4343
+ after: { type: "string", short: "a", description: "watch the runs newer than this run id, as `ft runs --json` gives it" },
4344
+ timeout: { type: "string", short: "t", description: "how long before giving up (15m), a bare number in minutes" },
4345
+ json: jsonOption("status, runs, failedJobs with their log excerpts and url; the progress goes to stderr"),
4346
+ quiet: { type: "boolean", short: "q", description: "print only the failures and each run's final status" },
4347
+ ...repoOption
4348
+ };
4349
+ var timing = { poll: 1e4 };
4350
+ var LIMIT = 20;
4351
+ var STALLED2 = 3 * 60000;
4352
+ async function watchRuns(pick, timeout, repo, idle, out = process.stdout) {
4353
+ return (await followRuns(pick, timeout, repo, idle, out)).code;
4354
+ }
4355
+ async function followRuns(pick, timeout, repo, idle, out = process.stdout, mode = {}) {
4356
+ const { json = false, quiet = false } = mode;
4357
+ const started = Date.now();
4358
+ const latest = new Map;
4359
+ const seen = new Map;
4360
+ const line = (run) => runLine(run, out, seen.get(run.id) ?? Date.now());
4361
+ const region = takesControlCodes(out) && !quiet ? liveRegion((spinner) => [ciHeader(spinner, "CI", started, out), ...[...latest.values()].map((run) => ` ${line(run)}`)], out) : undefined;
4362
+ const followed = new Set;
4363
+ const failed = new Set;
4364
+ const failedJobs = [];
4365
+ let moving = started;
4366
+ async function poll() {
4367
+ const newest = await recentRuns(LIMIT, repo);
4368
+ const gone = await Promise.all([...followed].filter((id) => !newest.some((run) => run.id === id)).map(async (id) => runById(id, repo)));
4369
+ const runs = [...pick(newest), ...gone];
4370
+ for (const run of runs)
4371
+ followed.add(run.id);
4372
+ for (const run of runs) {
4373
+ if (!seen.has(run.id))
4374
+ seen.set(run.id, Date.now());
4375
+ if (region === undefined && !quiet && latest.get(run.id)?.status !== run.status)
4376
+ out.write(`${line(run)}
4377
+ `);
4378
+ latest.set(run.id, run);
4379
+ }
4380
+ region?.redraw();
4381
+ if (runs.length === 0) {
4382
+ if (idle !== undefined && Date.now() - started > idle) {
4383
+ if (!json)
4384
+ out.write(`no run started, so nothing was waited for
4385
+ `);
4386
+ return 0;
4387
+ }
4388
+ return;
4389
+ }
4390
+ for (const run of runs) {
4391
+ if (run.status === "failure" && !failed.has(run.id)) {
4392
+ const jobs = await failedJobsOf(run, repo);
4393
+ failedJobs.push(...jobs);
4394
+ if (!json)
4395
+ console.error(`
4396
+ ${failureText2(jobs)}
4397
+
4398
+ ${run.html_url}`);
4399
+ failed.add(run.id);
4400
+ }
4401
+ }
4402
+ if (runs.every((run) => FINISHED.has(run.status))) {
4403
+ const status = overall(runs);
4404
+ return status === "failure" || status === "cancelled" ? 1 : 0;
4405
+ }
4406
+ const stall = await stallReason(runs, repo);
4407
+ if (stall === undefined)
4408
+ moving = Date.now();
4409
+ else if (stall.certain || Date.now() - moving > STALLED2)
4410
+ fail(`queued runs are not moving: ${stall.reason}`);
4411
+ return;
4412
+ }
4413
+ async function settle() {
4414
+ for (;; ) {
4415
+ await Bun.sleep(timing.poll);
4416
+ if (Date.now() - started > timeout)
4417
+ fail(`the runs did not finish in ${formatDuration(timeout)}`);
4418
+ try {
4419
+ const code = await poll();
4420
+ if (code !== undefined)
4421
+ return code;
4422
+ } catch (error) {
4423
+ if (error instanceof Exit)
4424
+ throw error;
4425
+ const message = error instanceof Error ? error.message : String(error);
4426
+ if (isPermanentFailure(error))
4427
+ fail(message);
4428
+ if (!quiet)
4429
+ warn(`ft watch: ${message}, polling again`);
4430
+ }
4431
+ }
4432
+ }
4433
+ try {
4434
+ return { code: await settle(), runs: [...latest.values()], failedJobs };
4435
+ } finally {
4436
+ region?.stop();
4437
+ if (region !== undefined || quiet) {
4438
+ for (const run of latest.values())
4439
+ out.write(`${line(run)}
4440
+ `);
4441
+ }
4442
+ }
4443
+ }
4444
+ async function watch2(args) {
4445
+ const parsed = parse(args, usage4, options3, { exits: EXITS3 });
4446
+ const { values } = parsed;
4447
+ const timeout = duration(values.timeout, "timeout", 15 * 60000, "m");
4448
+ const json = values.json === true;
4449
+ const mode = { json, quiet: values.quiet === true };
4450
+ async function follow(pick) {
4451
+ const followed = await followRuns(pick, timeout, values.repo, undefined, json ? process.stderr : process.stdout, mode);
4452
+ if (json)
4453
+ printJson(ciJson(followed.runs, followed.failedJobs));
4454
+ return followed.code;
4455
+ }
4456
+ if (values.after !== undefined) {
4457
+ const after = wholeNumber(values.after, "after", 0, 0);
4458
+ return follow((runs) => runs.filter((run) => run.id > after));
4459
+ }
4460
+ const active = new Set((await recentRuns(LIMIT, values.repo)).filter((run) => !FINISHED.has(run.status)).map((run) => run.id));
4461
+ if (active.size === 0) {
4462
+ if (json)
4463
+ printJson(ciJson([], []));
4464
+ else
4465
+ console.log("no run in progress");
4466
+ return 0;
4467
+ }
4468
+ return follow((runs) => runs.filter((run) => active.has(run.id)));
4469
+ }
4470
+
4471
+ // src/commands/dispatch.ts
4472
+ var usage5 = `ft dispatch <workflow> [--ref <branch>] [--input key=value]...
4473
+
4474
+ Starts a run of a workflow that declares \`on: workflow_dispatch\`, on the ref (the default branch's tip unless given), and prints the run's id and link.
4475
+ --wait then follows it to its end as \`ft watch\` does.`;
4476
+ var EXITS4 = [[0, "the run started, and with --wait it passed"], [1, "Forgejo refused it, or with --wait the run failed or was cancelled"], [2, "a usage error, or with --wait a timeout or a stalled queue"]];
4477
+ var options4 = {
4478
+ ref: { type: "string", description: "the branch, tag or commit sha to run, by default the repository's default branch" },
4479
+ input: { type: "string", short: "i", multiple: true, description: "an input the workflow declares, key=value, repeatable" },
4480
+ wait: { type: "boolean", short: "w", description: "follow the run to its end, exit 1 when it fails" },
4481
+ timeout: { type: "string", short: "t", description: "how long --wait waits before giving up (30m), a bare number in minutes" },
4482
+ quiet: { type: "boolean", short: "q", description: "with --wait, print only the failures and the run's final status" },
4483
+ json: jsonOption("{id, number, workflow, ref, url}; with --wait, ft watch --json's status, runs and failedJobs"),
4484
+ ...repoOption
4485
+ };
4486
+ var WORKFLOW_FILE = /\.ya?ml$/;
4487
+ function parseInputs(given) {
4488
+ const inputs = {};
4489
+ for (const each of given) {
4490
+ const at = each.indexOf("=");
4491
+ if (at <= 0)
4492
+ badUsage(`--input takes key=value, not '${each}'`);
4493
+ inputs[each.slice(0, at)] = each.slice(at + 1);
4494
+ }
4495
+ return inputs;
4496
+ }
4497
+ async function dispatch2(args) {
4498
+ const { values, positionals } = parse(args, usage5, options4, {
4499
+ positionals: ["<workflow>"],
4500
+ exits: EXITS4,
4501
+ replaces: "tea api -X POST on a workflow's dispatches, then finding the run it started",
4502
+ examples: [["ft dispatch apps.yml", "on the default branch"], ["ft dispatch deploy.yml --ref v1.2.0 -i target=prod --wait", "a tag, an input, and wait for it"]]
4503
+ });
4504
+ const workflow = positionals[0] ?? badUsage(`a workflow file is needed
4505
+
4506
+ ${usage5}`);
4507
+ if (!WORKFLOW_FILE.test(workflow))
4508
+ badUsage(`<workflow> is a file name under .forgejo/workflows, such as test.yml, not '${workflow}'`);
4509
+ if (values.wait !== true && (values.timeout !== undefined || values.quiet === true))
4510
+ badUsage("--timeout and --quiet go with --wait");
4511
+ const inputs = parseInputs(values.input ?? []);
4512
+ const timeout = duration(values.timeout, "timeout", 30 * 60000, "m");
4513
+ const ref = values.ref ?? (await api("repos/{owner}/{repo}", values.repo)).default_branch;
4514
+ const json = values.json === true;
4515
+ const wait = values.wait === true;
4516
+ const say = json ? console.error : console.log;
4517
+ const fields = { ref, ...Object.keys(inputs).length === 0 ? {} : { inputs }, return_run_info: true };
4518
+ const started = await repoWriteOrEmpty("POST", `actions/workflows/${encodeURIComponent(workflow)}/dispatches`, fields, values.repo);
4519
+ if (started === undefined) {
4520
+ const said = `${workflow} started on ${ref}, but Forgejo did not say which run`;
4521
+ if (wait || json)
4522
+ fail(`${said}, so it cannot be ${wait ? "followed" : "printed"}`, 1, `ft runs -w ${workflow} lists it`);
4523
+ console.error(`${said}: ft runs -w ${workflow} lists it`);
4524
+ return 0;
4525
+ }
4526
+ const run = await runById(started.id, values.repo);
4527
+ if (json && !wait)
4528
+ printJson({ id: run.id, number: started.run_number, workflow, ref, url: run.html_url });
4529
+ else
4530
+ say(`started ${workflow} run ${run.id} on ${ref}: ${run.html_url}`);
4531
+ if (!wait)
4532
+ return 0;
4533
+ const followed = await followRuns((runs) => runs.filter((each) => each.id === run.id), timeout, values.repo, undefined, json ? process31.stderr : process31.stdout, { json, quiet: values.quiet === true });
4534
+ if (json)
4535
+ printJson(ciJson(followed.runs, followed.failedJobs));
4536
+ return followed.code;
4537
+ }
4538
+
3408
4539
  // src/commands/issue-target.ts
3409
4540
  var ISSUE_REFERENCE = /^#?\d+$/;
3410
4541
  async function chooseTarget(positionals, held, usage) {
@@ -3455,7 +4586,7 @@ var tickUsage = `ft tick [<n>] <box>...
3455
4586
  Ticks checklist boxes of issue <n>, each given by its number from \`ft issue\` or by text matching exactly one box, then posts the -m or -F comment.
3456
4587
  With --closed, ticks instead every box opening with \`#<issue>\` whose issue is closed, as a release plan lists them.
3457
4588
 
3458
- Without <n> (a first argument that is not a number) it takes the one open issue this session holds (\`ft take\`), and exits 2 when it holds none or several, saying which issue it used. A first argument that is a number is always the issue, so boxes named by number need it.`;
4589
+ Without <n> it takes the one open issue this session holds (\`ft take\`); a first argument that is a number is always the issue.`;
3459
4590
  var tickExits = [[0, "it ticked the boxes"], [1, "Forgejo refuses"], [2, "a usage error or a box matching none or several"]];
3460
4591
  var tickOptions = {
3461
4592
  undo: { type: "boolean", short: "u", description: "untick them instead" },
@@ -3506,9 +4637,9 @@ ${tickUsage}`);
3506
4637
  }
3507
4638
  var fixedUsage = `ft fixed [<n>] [commit]...
3508
4639
 
3509
- Comments "Fixed in <sha>: <message>" on issue <n> and closes it, naming each commit given as "Fixed in <a>, <b> and <c>".
3510
- Without a commit it takes those on origin's default branch whose message names #<n>, and says which, or HEAD when none does.
3511
- Without <n> it takes the one open issue this session holds (\`ft take\`). The message defaults to the subject of the first commit. Every open issue listing \`- [ ] #<n>\` in its checklist gets that line ticked. An issue with boxes left is refused, as a partly done issue stays open, unless --tick ticks them first.`;
4640
+ Comments "Fixed in <a>, <b> and <c>: <subject>" on issue <n> and closes it.
4641
+ Without a commit it takes those on origin's default branch naming #<n> in their message, or HEAD when none does, and says which; without <n> it takes the one open issue this session holds (\`ft take\`).
4642
+ An issue with boxes left is refused unless --tick ticks them first, and every open issue listing \`- [ ] #<n>\` gets that line ticked.`;
3512
4643
  var fixedExits = [[0, "it closed the issue"], [1, "the issue is already closed, has boxes left or Forgejo refuses"], [2, "a usage error"]];
3513
4644
  var fixedOptions = {
3514
4645
  message: { type: "string", short: "m", description: 'the line after "Fixed in <sha>:"' },
@@ -3710,7 +4841,7 @@ var editOptions = {
3710
4841
  milestone: { type: "string", short: "m", description: "move the issue to this milestone, a title or an id; an empty value takes it out of its milestone" },
3711
4842
  ...repoOption
3712
4843
  };
3713
- async function edit(args) {
4844
+ async function edit2(args) {
3714
4845
  const parsed = parse(args, editUsage, editOptions, { exits: editExits });
3715
4846
  const { values, positionals } = parsed;
3716
4847
  const number = issueNumber(positionals[0], editUsage);
@@ -3872,12 +5003,12 @@ async function issue(args) {
3872
5003
  }
3873
5004
 
3874
5005
  // src/commands/logs.ts
3875
- var usage4 = `ft logs <run id>
5006
+ var usage6 = `ft logs <run id>
3876
5007
 
3877
5008
  Prints what the failed jobs of a run say went wrong: each failed bun test's output and the end of each failed step, cut to the errors when it is a tsc, eslint, vitest, playwright, phpstan or php-cs-fixer step.
3878
5009
  With no failed job it prints every job's last lines; --full prints whole logs.`;
3879
- var EXITS3 = [[0, "it printed the logs"], [1, "Forgejo cannot be read"], [2, "a usage error or a job the run lacks"]];
3880
- var options3 = {
5010
+ var EXITS5 = [[0, "it printed the logs"], [1, "Forgejo cannot be read"], [2, "a usage error or a job the run lacks"]];
5011
+ var options5 = {
3881
5012
  job: { type: "string", short: "j", description: "only this job, by name or id" },
3882
5013
  full: { type: "boolean", short: "f", description: "the whole log, timestamps stripped" },
3883
5014
  json: jsonOption("status, runs, failedJobs, url and the picked jobs with their log excerpts"),
@@ -3890,7 +5021,7 @@ function pickJobs(jobs, wanted) {
3890
5021
  return failed.length > 0 ? failed : jobs;
3891
5022
  }
3892
5023
  async function logs2(args) {
3893
- const parsed = parse(args, usage4, options3, { exits: EXITS3 });
5024
+ const parsed = parse(args, usage6, options5, { exits: EXITS5 });
3894
5025
  const { values, positionals } = parsed;
3895
5026
  if (positionals[0] === undefined)
3896
5027
  fail("a run id is needed", 2, runHint("ft runs", "list them"));
@@ -3921,7 +5052,8 @@ ${await text(job)}`);
3921
5052
  }
3922
5053
 
3923
5054
  // src/commands/milestone.ts
3924
- import process28 from "process";
5055
+ import process32 from "process";
5056
+ init_text();
3925
5057
  var TITLE_WIDTH3 = 60;
3926
5058
  var LIST_LIMIT = 30;
3927
5059
  var CONCURRENCY2 = 4;
@@ -3930,15 +5062,15 @@ function counts(milestone) {
3930
5062
  }
3931
5063
  function progressBar(milestone) {
3932
5064
  const total = milestone.open_issues + milestone.closed_issues;
3933
- return takesControlCodes(process28.stdout) ? bar(total === 0 ? 0 : milestone.closed_issues / total, { width: 16 }) : "";
5065
+ return takesControlCodes(process32.stdout) ? bar(total === 0 ? 0 : milestone.closed_issues / total, { width: 16 }) : "";
3934
5066
  }
3935
5067
  function milestoneCells(each, showState) {
3936
5068
  const drawn = progressBar(each);
3937
5069
  return [String(each.id), truncate(each.title, TITLE_WIDTH3), `${each.open_issues} open`, `${each.closed_issues} closed`, ...drawn === "" ? [] : [drawn], progress(each), dueDate(each) === "" ? "" : `due ${dueDate(each)}`, ...showState ? [each.state] : []];
3938
5070
  }
3939
5071
  async function printWithIssues(list, repo) {
3940
- const colors = paint(process28.stdout);
3941
- const id = role("id", process28.stdout);
5072
+ const colors = paint(process32.stdout);
5073
+ const id = role("id", process32.stdout);
3942
5074
  const issuesOf = await pool(list, concurrencyOf(CONCURRENCY2), async (each) => Promise.all([openIssues(undefined, repo, each.id), closedIssues(each.id, repo)]));
3943
5075
  const blocks = list.map((each, index) => {
3944
5076
  const byNumber = (left, right) => left.number - right.number;
@@ -3949,7 +5081,7 @@ async function printWithIssues(list, repo) {
3949
5081
  ...open.map((issue) => ` ${id(`#${issue.number}`)} ${truncate(issue.title, TITLE_WIDTH3)}`),
3950
5082
  ...closed.map((issue) => colors.dim(` #${issue.number} ${truncate(issue.title, TITLE_WIDTH3)} (closed)`))
3951
5083
  ];
3952
- return [section(`${each.title}${drawn === "" ? "" : ` ${drawn}`} ${facts}`, undefined, process28.stdout, process28.env, "accent"), ...lines].join(`
5084
+ return [section(`${each.title}${drawn === "" ? "" : ` ${drawn}`} ${facts}`, undefined, process32.stdout, process32.env, "accent"), ...lines].join(`
3953
5085
  `);
3954
5086
  });
3955
5087
  console.log(blocks.join(`
@@ -3961,7 +5093,7 @@ var listUsage = `ft milestones
3961
5093
  Lists the repository's milestones, the open ones unless --state says otherwise, with the issues open and closed in each, the progress and the due date; on a terminal the progress is a bar, and --issues lists the title of every issue under its milestone.`;
3962
5094
  var listExits = [[0, "it listed them"], [1, "Forgejo refuses"], [2, "a usage error"]];
3963
5095
  var listOptions = {
3964
- state: { type: "string", description: "open (the default), closed or all" },
5096
+ state: { type: "string", choices: ["open", "closed", "all"], default: "open", description: "which milestones to list (open)" },
3965
5097
  issues: { type: "boolean", short: "i", description: "list the open and closed issues of each milestone by title" },
3966
5098
  ...limitOptions(LIST_LIMIT),
3967
5099
  json: jsonOption("id, title, state, description, open, closed, due (YYYY-MM-DD or null)"),
@@ -3970,9 +5102,7 @@ var listOptions = {
3970
5102
  async function milestones(args) {
3971
5103
  const parsed = parse(args, listUsage, listOptions, { exits: listExits });
3972
5104
  const { values } = parsed;
3973
- const state = values.state ?? "open";
3974
- if (state !== "open" && state !== "closed" && state !== "all")
3975
- fail(`--state takes open, closed or all, not ${state}`);
5105
+ const state = values.state;
3976
5106
  const limit = limitOf(values, LIST_LIMIT);
3977
5107
  const found = await listMilestones(state, values.repo);
3978
5108
  if (values.issues === true && values.json === true)
@@ -4039,7 +5169,7 @@ ${closeUsage2}`);
4039
5169
  }
4040
5170
  const open = await openIssues(undefined, values.repo, found.id);
4041
5171
  if (open.length > 0 && values.force !== true)
4042
- fail(`milestone ${found.title} has ${go(open.length, "open issue")}:
5172
+ fail(`milestone ${found.title} has ${bo(open.length, "open issue")}:
4043
5173
  ${open.map((issue) => ` #${issue.number} ${truncate(issue.title, TITLE_WIDTH3)}`).join(`
4044
5174
  `)}`, 1, `${runHint(`ft milestone close ${found.title} --force`, "close it with them open")}, or move them with \`ft edit <n> -m <milestone>\``);
4045
5175
  await closeMilestone(found.id, values.repo);
@@ -4095,44 +5225,39 @@ function heading(line) {
4095
5225
  }
4096
5226
  function insertionPoint(lines, body, section) {
4097
5227
  const all = boxes(body);
5228
+ const last = all.at(-1);
4098
5229
  if (section === undefined)
4099
- return all.length === 0 ? undefined : (all.at(-1)?.line ?? 0) + 1;
5230
+ return last === undefined ? undefined : afterBox(lines, last.line);
4100
5231
  const title = heading(section);
4101
5232
  const at = lines.findIndex((line) => heading(line) === title);
4102
5233
  if (at === -1)
4103
5234
  return;
4104
5235
  const lineOfBox = new Set(all.map((box) => box.line));
4105
5236
  let end = at + 1;
4106
- for (let next = at + 1;next < lines.length; next++) {
4107
- if (lineOfBox.has(next))
4108
- end = next + 1;
4109
- else if (lines[next]?.trim() !== "")
5237
+ let next = at + 1;
5238
+ while (next < lines.length) {
5239
+ if (lineOfBox.has(next)) {
5240
+ end = afterBox(lines, next);
5241
+ next = end;
5242
+ } else if (lines[next]?.trim() === "") {
5243
+ next++;
5244
+ } else {
4110
5245
  break;
5246
+ }
4111
5247
  }
4112
5248
  return end;
4113
5249
  }
4114
5250
  function addLines(body, added, section) {
4115
5251
  if (added.length === 0)
4116
5252
  return body;
4117
- const eol = body.includes(`\r
4118
- `) ? "\r" : "";
4119
- const lines = body.split(`
4120
- `);
4121
- const at = insertionPoint(lines, body, section);
4122
- const fresh = added.map((line) => `${line}${eol}`);
4123
- if (at !== undefined) {
4124
- lines.splice(at, 0, ...fresh);
4125
- return lines.join(`
4126
- `);
4127
- }
5253
+ const eol = lineEnding(body);
5254
+ const at = insertionPoint(body.split(`
5255
+ `), body, section);
5256
+ if (at !== undefined)
5257
+ return insertLines(body, at, added);
4128
5258
  const text = body.trimEnd();
4129
- return `${text}${text === "" ? "" : `${eol}
4130
- ${eol}
4131
- `}${section === undefined ? "" : `${section}${eol}
4132
- `}${fresh.join(`
4133
- `)}${body.endsWith(`
4134
- `) ? `
4135
- ` : ""}`;
5259
+ return `${text}${text === "" ? "" : `${eol}${eol}`}${section === undefined ? "" : `${section}${eol}`}${added.join(eol)}${body.endsWith(`
5260
+ `) ? eol : ""}`;
4136
5261
  }
4137
5262
  function listedIssues(body) {
4138
5263
  return new Set(referencedBoxes(body).map(({ issue }) => issue));
@@ -4154,7 +5279,7 @@ Copies the unticked \`#<n>\` lines of issue <from> into issue <to>, skipping tho
4154
5279
  Lines go under --section, created at the end of the body when missing, or else after the checklist's last box.
4155
5280
  The body is read again just before it is written, so an edit made meanwhile is kept.`;
4156
5281
  var carryExits = [[0, "it copied the lines"], [1, "Forgejo refuses"], [2, "a usage error"]];
4157
- var options4 = {
5282
+ var options6 = {
4158
5283
  section: { type: "string", short: "s", description: 'the heading the lines go under, e.g. "Bugs:"' },
4159
5284
  ...repoOption
4160
5285
  };
@@ -4166,7 +5291,7 @@ var plan = {
4166
5291
  }
4167
5292
  };
4168
5293
  async function add(args) {
4169
- const parsed = parse(args, addUsage, options4, { exits: addExits });
5294
+ const parsed = parse(args, addUsage, options6, { exits: addExits });
4170
5295
  const { section, repo } = parsed.values;
4171
5296
  const [target, ...listed] = parsed.positionals;
4172
5297
  const planNumber = issueNumber(target, addUsage);
@@ -4187,7 +5312,7 @@ ${addUsage}`);
4187
5312
  return 0;
4188
5313
  }
4189
5314
  async function carry(args) {
4190
- const parsed = parse(args, carryUsage, options4, { exits: carryExits });
5315
+ const parsed = parse(args, carryUsage, options6, { exits: carryExits });
4191
5316
  const { section, repo } = parsed.values;
4192
5317
  const from = issueNumber(parsed.positionals[0], carryUsage);
4193
5318
  const to = issueNumber(parsed.positionals[1], carryUsage);
@@ -4208,147 +5333,20 @@ function report2(plan, added, skipped) {
4208
5333
  }
4209
5334
 
4210
5335
  // src/commands/release.ts
4211
- import { basename as basename3, join as join11 } from "path";
4212
- import process30 from "process";
5336
+ import { basename as basename3, join as join14 } from "path";
5337
+ import process34 from "process";
4213
5338
  var {$: $2 } = globalThis.Bun;
4214
5339
 
4215
- // src/commands/watch.ts
4216
- var usage5 = `ft watch [--after <id>]
4217
-
4218
- Waits for runs to finish: those newer than run <id>, or else the ones in progress now.
4219
- Prints nothing but failures and each run's final status with --quiet, and a JSON result with --json.`;
4220
- var EXITS4 = [[0, "every one passed or was skipped"], [1, "one failed or was cancelled"], [2, "a timeout or a stalled queue"]];
4221
- var options5 = {
4222
- after: { type: "string", short: "a", description: "watch the runs newer than this run id, as `ft runs --json` gives it" },
4223
- timeout: { type: "string", short: "t", description: "how long before giving up (15m), a bare number in minutes" },
4224
- json: jsonOption("status, runs, failedJobs with their log excerpts and url; the progress goes to stderr"),
4225
- quiet: { type: "boolean", short: "q", description: "print only the failures and each run's final status" },
4226
- ...repoOption
4227
- };
4228
- var timing = { poll: 1e4 };
4229
- var LIMIT = 20;
4230
- var STALLED2 = 3 * 60000;
4231
- async function watchRuns(pick, timeout, repo, idle, out = process.stdout) {
4232
- return (await followRuns(pick, timeout, repo, idle, out)).code;
4233
- }
4234
- async function followRuns(pick, timeout, repo, idle, out = process.stdout, mode = {}) {
4235
- const { json = false, quiet = false } = mode;
4236
- const started = Date.now();
4237
- const latest = new Map;
4238
- const seen = new Map;
4239
- const line = (run) => runLine(run, out, seen.get(run.id) ?? Date.now());
4240
- const region = takesControlCodes(out) && !quiet ? liveRegion((spinner) => [ciHeader(spinner, "CI", started, out), ...[...latest.values()].map((run) => ` ${line(run)}`)], out) : undefined;
4241
- const followed = new Set;
4242
- const failed = new Set;
4243
- const failedJobs = [];
4244
- let moving = started;
4245
- async function poll() {
4246
- const newest = await recentRuns(LIMIT, repo);
4247
- const gone = await Promise.all([...followed].filter((id) => !newest.some((run) => run.id === id)).map(async (id) => runById(id, repo)));
4248
- const runs = [...pick(newest), ...gone];
4249
- for (const run of runs)
4250
- followed.add(run.id);
4251
- for (const run of runs) {
4252
- if (!seen.has(run.id))
4253
- seen.set(run.id, Date.now());
4254
- if (region === undefined && !quiet && latest.get(run.id)?.status !== run.status)
4255
- out.write(`${line(run)}
4256
- `);
4257
- latest.set(run.id, run);
4258
- }
4259
- region?.redraw();
4260
- if (runs.length === 0) {
4261
- if (idle !== undefined && Date.now() - started > idle) {
4262
- if (!json)
4263
- out.write(`no run started, so nothing was waited for
4264
- `);
4265
- return 0;
4266
- }
4267
- return;
4268
- }
4269
- for (const run of runs) {
4270
- if (run.status === "failure" && !failed.has(run.id)) {
4271
- const jobs = await failedJobsOf(run, repo);
4272
- failedJobs.push(...jobs);
4273
- if (!json)
4274
- console.error(`
4275
- ${failureText2(jobs)}
4276
-
4277
- ${run.html_url}`);
4278
- failed.add(run.id);
4279
- }
4280
- }
4281
- if (runs.every((run) => FINISHED.has(run.status))) {
4282
- const status = overall(runs);
4283
- return status === "failure" || status === "cancelled" ? 1 : 0;
4284
- }
4285
- const stall = await stallReason(runs, repo);
4286
- if (stall === undefined)
4287
- moving = Date.now();
4288
- else if (stall.certain || Date.now() - moving > STALLED2)
4289
- fail(`queued runs are not moving: ${stall.reason}`);
4290
- return;
4291
- }
4292
- async function settle() {
4293
- for (;; ) {
4294
- await Bun.sleep(timing.poll);
4295
- if (Date.now() - started > timeout)
4296
- fail(`the runs did not finish in ${formatDuration(timeout)}`);
4297
- try {
4298
- const code = await poll();
4299
- if (code !== undefined)
4300
- return code;
4301
- } catch (error) {
4302
- if (error instanceof Exit)
4303
- throw error;
4304
- const message = error instanceof Error ? error.message : String(error);
4305
- if (isPermanentFailure(error))
4306
- fail(message);
4307
- if (!quiet)
4308
- warn(`ft watch: ${message}, polling again`);
4309
- }
4310
- }
4311
- }
5340
+ // src/commands/release-checks.ts
5341
+ var limits = { pushMs: 5 * 60000 };
5342
+ async function pushToOrigin(refspecs, onStart) {
5343
+ const prompts = askpass();
4312
5344
  try {
4313
- return { code: await settle(), runs: [...latest.values()], failedJobs };
5345
+ return await runTool("git push", ["git", "push", ...refspecs], { timeoutMs: limits.pushMs, onStart, env: prompts?.env });
4314
5346
  } finally {
4315
- region?.stop();
4316
- if (region !== undefined || quiet) {
4317
- for (const run of latest.values())
4318
- out.write(`${line(run)}
4319
- `);
4320
- }
5347
+ prompts?.close();
4321
5348
  }
4322
5349
  }
4323
- async function watch2(args) {
4324
- const parsed = parse(args, usage5, options5, { exits: EXITS4 });
4325
- const { values } = parsed;
4326
- const timeout = duration(values.timeout, "timeout", 15 * 60000, "m");
4327
- const json = values.json === true;
4328
- const mode = { json, quiet: values.quiet === true };
4329
- async function follow(pick) {
4330
- const followed = await followRuns(pick, timeout, values.repo, undefined, json ? process.stderr : process.stdout, mode);
4331
- if (json)
4332
- printJson(ciJson(followed.runs, followed.failedJobs));
4333
- return followed.code;
4334
- }
4335
- if (values.after !== undefined) {
4336
- const after = wholeNumber(values.after, "after", 0, 0);
4337
- return follow((runs) => runs.filter((run) => run.id > after));
4338
- }
4339
- const active = new Set((await recentRuns(LIMIT, values.repo)).filter((run) => !FINISHED.has(run.status)).map((run) => run.id));
4340
- if (active.size === 0) {
4341
- if (json)
4342
- printJson(ciJson([], []));
4343
- else
4344
- console.log("no run in progress");
4345
- return 0;
4346
- }
4347
- return follow((runs) => runs.filter((run) => active.has(run.id)));
4348
- }
4349
-
4350
- // src/commands/release-checks.ts
4351
- var limits = { pushMs: 5 * 60000 };
4352
5350
  var NO_RUN2 = 3 * 60000;
4353
5351
  var RUNS_LOOKED_AT = 20;
4354
5352
  async function alreadyPassed(sha) {
@@ -4365,7 +5363,7 @@ async function testsPass(sha, branch, timeout, json = false) {
4365
5363
  const held = holdSignals();
4366
5364
  let push;
4367
5365
  try {
4368
- push = await runTool("git push", ["git", "push", "origin", `${sha}:refs/heads/${branch}`], { timeoutMs: limits.pushMs, onStart: (child) => held.forward(child) });
5366
+ push = await pushToOrigin(["origin", `${sha}:refs/heads/${branch}`], (child) => held.forward(child));
4369
5367
  } finally {
4370
5368
  held.release();
4371
5369
  }
@@ -4385,7 +5383,7 @@ ${push.stderr.trim()}`, 1);
4385
5383
 
4386
5384
  // src/commands/release-many.ts
4387
5385
  import { readdir } from "fs/promises";
4388
- import { join as join8 } from "path";
5386
+ import { join as join11 } from "path";
4389
5387
 
4390
5388
  // src/commands/release-version.ts
4391
5389
  var LEVELS = new Set(["patch", "minor", "major", "prepatch", "preminor", "premajor", "prerelease"]);
@@ -4434,11 +5432,11 @@ function parseTargets(spec, level) {
4434
5432
  });
4435
5433
  }
4436
5434
  async function publishable() {
4437
- const root = join8(await git(["rev-parse", "--show-toplevel"]), "packages");
5435
+ const root = join11(await git(["rev-parse", "--show-toplevel"]), "packages");
4438
5436
  const folders = (await readdir(root, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).toSorted();
4439
5437
  const found = [];
4440
5438
  for (const folder of folders) {
4441
- const file = Bun.file(join8(root, folder, "package.json"));
5439
+ const file = Bun.file(join11(root, folder, "package.json"));
4442
5440
  if (await file.exists() && (await file.json()).private !== true)
4443
5441
  found.push(folder);
4444
5442
  }
@@ -4446,13 +5444,13 @@ async function publishable() {
4446
5444
  }
4447
5445
 
4448
5446
  // src/commands/release-plan.ts
4449
- import { basename as basename2, join as join9, relative } from "path";
4450
- import process29 from "process";
5447
+ import { basename as basename2, join as join12, relative } from "path";
5448
+ import process33 from "process";
4451
5449
  async function planOf({ level, dir, prefix }, registry) {
4452
- const file = Bun.file(join9(dir ?? ".", "package.json"));
5450
+ const file = Bun.file(join12(dir ?? ".", "package.json"));
4453
5451
  const pkg = await file.exists() ? await file.json() : undefined;
4454
- const name = pkg?.name ?? basename2(dir ?? process29.cwd());
4455
- const where = dir === undefined ? "" : ` in ${relative(process29.cwd(), dir) || "."}`;
5452
+ const name = pkg?.name ?? basename2(dir ?? process33.cwd());
5453
+ const where = dir === undefined ? "" : ` in ${relative(process33.cwd(), dir) || "."}`;
4456
5454
  let version;
4457
5455
  let bump;
4458
5456
  if (level === undefined) {
@@ -4464,7 +5462,7 @@ async function planOf({ level, dir, prefix }, registry) {
4464
5462
  console.log(`would release ${name} ${version}, tagged ${tag}`);
4465
5463
  } else {
4466
5464
  if (pkg?.version === undefined)
4467
- fail(`no version in ${join9(dir ?? ".", "package.json")}`);
5465
+ fail(`no version in ${join12(dir ?? ".", "package.json")}`);
4468
5466
  version = nextVersion(pkg.version, level);
4469
5467
  bump = dir === undefined ? `bun pm version ${level}, which commits and tags ${prefix}${version}` : `bun pm version ${level} --no-git-tag-version${where}, then commit it with bun.lock refreshed and tag ${prefix}${version}`;
4470
5468
  console.log(`would release ${name} ${pkg.version} -> ${version}, tagged ${prefix}${version}`);
@@ -4491,25 +5489,26 @@ async function printPlan({ releases, branch, base, timeout, registry }) {
4491
5489
  }
4492
5490
 
4493
5491
  // src/commands/release-steps.ts
4494
- import { join as join10, relative as relative2, resolve as resolve5 } from "path";
5492
+ import { join as join13, relative as relative2, resolve as resolve5 } from "path";
5493
+ init_text();
4495
5494
  var {$ } = globalThis.Bun;
4496
5495
  var registryWait = { tries: 12, poll: 5000 };
4497
5496
  var REGISTRY_INFO_MS = 30000;
4498
5497
  async function packageDir(value) {
4499
- for (const dir of [resolve5(value), join10(await git(["rev-parse", "--show-toplevel"]), "packages", value)]) {
4500
- if (await Bun.file(join10(dir, "package.json")).exists())
5498
+ for (const dir of [resolve5(value), join13(await git(["rev-parse", "--show-toplevel"]), "packages", value)]) {
5499
+ if (await Bun.file(join13(dir, "package.json")).exists())
4501
5500
  return dir;
4502
5501
  }
4503
5502
  fail(`no package.json in ${value} nor in packages/${value}`);
4504
5503
  }
4505
5504
  async function commitPackageBump(dir, prefix) {
4506
- const { version } = await Bun.file(join10(dir, "package.json")).json();
5505
+ const { version } = await Bun.file(join13(dir, "package.json")).json();
4507
5506
  const root = await git(["rev-parse", "--show-toplevel"]);
4508
5507
  const tag = `${prefix}${version}`;
4509
5508
  const lock = await $`bun install --lockfile-only`.cwd(root).quiet().nothrow();
4510
5509
  if (lock.exitCode !== 0)
4511
5510
  fail(`bun install --lockfile-only after the bump: ${lock.stderr.toString().trim()}`);
4512
- await git(["add", join10(dir, "package.json"), join10(root, "bun.lock")]);
5511
+ await git(["add", join13(dir, "package.json"), join13(root, "bun.lock")]);
4513
5512
  await git(["commit", "-q", "-m", tag]);
4514
5513
  await git(["tag", "-a", tag, "-m", tag]);
4515
5514
  }
@@ -4533,11 +5532,11 @@ async function rollBack(preBump, dirs) {
4533
5532
  try {
4534
5533
  if (dirs.length > 0) {
4535
5534
  const root = await git(["rev-parse", "--show-toplevel"]);
4536
- const paths = [...dirs.map((dir) => join10(dir, "package.json")), join10(root, "bun.lock")].map((path) => relative2(root, path));
5535
+ const paths = [...dirs.map((dir) => join13(dir, "package.json")), join13(root, "bun.lock")].map((path) => relative2(root, path));
4537
5536
  const tracked = (await git(["ls-tree", "-r", "--full-tree", "--name-only", "HEAD", "--", ...paths])).split(`
4538
5537
  `).filter((path) => path !== "");
4539
5538
  if (tracked.length > 0)
4540
- await git(["restore", "--source=HEAD", "--staged", "--worktree", "--", ...tracked.map((path) => join10(root, path))]);
5539
+ await git(["restore", "--source=HEAD", "--staged", "--worktree", "--", ...tracked.map((path) => join13(root, path))]);
4541
5540
  }
4542
5541
  for (const commit of (await git(["rev-list", `${preBump}..HEAD`])).split(`
4543
5542
  `).filter(Boolean)) {
@@ -4556,7 +5555,7 @@ async function settleMilestone(version, tag, say = console.log) {
4556
5555
  if (found === undefined)
4557
5556
  return;
4558
5557
  const [done, left] = await Promise.all([closedIssues(found.id), openIssues(undefined, undefined, found.id)]);
4559
- say(`milestone ${found.title}: ${go(done.length, "closed issue")}${done.length === 0 ? "" : `
5558
+ say(`milestone ${found.title}: ${bo(done.length, "closed issue")}${done.length === 0 ? "" : `
4560
5559
  ${done.map((issue) => ` #${issue.number} ${issue.title}`).join(`
4561
5560
  `)}`}`);
4562
5561
  if (left.length > 0)
@@ -4570,31 +5569,27 @@ ${done.map((issue) => ` #${issue.number} ${issue.title}`).join(`
4570
5569
 
4571
5570
  // src/commands/release.ts
4572
5571
  var SEVERAL = /[,:]/;
4573
- var usage6 = `ft release <patch|minor|major|x.y.z>
5572
+ var usage7 = `ft release <patch|minor|major|x.y.z>
4574
5573
  ft release <level> -p <a,b:minor,...>
4575
5574
  ft release <level> --all
4576
5575
  ft release --tagged
4577
5576
 
4578
- Cuts a release from the default branch: first the commit it sits on is pushed and its runs waited for, so failing tests stop it before anything is bumped or tagged. Then \`bun pm version\` commits and tags the bump, one atomic push sends the branch and its tag, and it waits for the runs the push started and for the registry to serve the version.
4579
- --tagged releases a version commit already tagged at HEAD instead, for repos bumping with their own script; the runs waited for first are then those of the commit below it.
4580
- --package releases one workspace package of a monorepo on its own, tagged \`<folder>-v<version>\` (\`ft release patch -p ft\` tags packages/ft as ft-v0.3.0).
4581
- --package takes several folders separated by commas, each optionally with its own level after a colon (\`-p ft:minor,db\` bumps ft by minor and db by the level given); --all takes every published package of the workspace. Each package gets its own bump commit and tag, and one atomic push sends the branch with every tag, so the tests run once for them all; the registry is then waited for package by package, stopping at the first one it does not serve.
4582
- A refused or interrupted push drops the bump commits and their tags, so a retry starts clean; with --tagged the commit and tag are yours and stay.
4583
- Once released, an open milestone titled like the version (\`1.2.0\`, \`v1.2.0\` or the tag) has its closed issues listed and is closed; a failure there only warns.
4584
- --dry-run checks the same and prints the plan: the version bump, the tag, the pushes and the runs and registry it would wait for, changing nothing.
4585
- --json prints {released, tag, package, version, status, runs, failedJobs, url} on stdout and the progress on stderr, an array of them with --package a,b or --all; it does not take --dry-run.`;
4586
- var EXITS5 = [[0, "released or planned"], [1, "a run fails, origin refuses a push or the registry never serves the version"], [2, "a timeout, a stalled queue, a refusal before anything ran (another branch, uncommitted changes, origin ahead) or a usage error"]];
4587
- var options6 = {
5577
+ Cuts a release from the default branch: waits for the runs on HEAD, bumps and tags with \`bun pm version\`, pushes, then waits for the runs and the registry.
5578
+ Failing tests stop it before anything is bumped or tagged, and a refused or interrupted push drops the bump commits and their tags; with --tagged the commit and tag are yours and stay.
5579
+ --package releases workspace packages tagged \`<folder>-v<version>\`, each with an optional level of its own (\`-p ft:minor,db\`), --all every published one, in one atomic push.
5580
+ Once released, an open milestone titled like the version has its closed issues listed and is closed; a failure there only warns.`;
5581
+ var EXITS6 = [[0, "released or planned"], [1, "a run fails, origin refuses a push or the registry never serves the version"], [2, "a timeout, a stalled queue, a refusal before anything ran (another branch, uncommitted changes, origin ahead) or a usage error"]];
5582
+ var options7 = {
4588
5583
  tagged: { type: "boolean", description: "push the version commit and tag already at HEAD instead of bumping" },
4589
5584
  package: { type: "string", short: "p", description: "workspace folder to release, a path or a name under packages/, several separated by commas" },
4590
5585
  all: { type: "boolean", description: "release every published package of the workspace in one push" },
4591
5586
  "no-registry": { type: "boolean", description: "do not wait for the registry to serve the new version" },
4592
5587
  "dry-run": { type: "boolean", description: "print what the release would do, changing nothing" },
4593
5588
  timeout: { type: "string", short: "t", description: "how long to wait for the runs (15m), a bare number in minutes" },
4594
- json: jsonOption("what was released and how its runs ended")
5589
+ json: jsonOption("{released, tag, package, version, status, runs, failedJobs, url} on stdout and the progress on stderr, an array with several packages; not with --dry-run")
4595
5590
  };
4596
5591
  async function release(args) {
4597
- const parsed = parse(args, usage6, options6, { exits: EXITS5 });
5592
+ const parsed = parse(args, usage7, options7, { exits: EXITS6 });
4598
5593
  const { values, positionals } = parsed;
4599
5594
  const json = values.json === true;
4600
5595
  const say = json ? console.error : console.log;
@@ -4605,7 +5600,7 @@ async function release(args) {
4605
5600
  if (tagged === (level !== undefined))
4606
5601
  fail(`give a level or --tagged
4607
5602
 
4608
- ${usage6}`);
5603
+ ${usage7}`);
4609
5604
  if (level !== undefined && !LEVELS.has(level) && !VERSION.test(level))
4610
5605
  fail(`${level} is no level nor x.y.z version`);
4611
5606
  const several = values.all === true || SEVERAL.test(values.package ?? "");
@@ -4624,8 +5619,7 @@ ${usage6}`);
4624
5619
  fail(`a release is cut from ${branch}, not ${current || "a detached HEAD"}`, 2, runHint(`git switch ${branch}`));
4625
5620
  if (await git(["status", "--porcelain"]) !== "")
4626
5621
  fail("the tree has uncommitted changes", 2, runHint("gst", "see them, then commit them with gc"));
4627
- await fetchBranch(branch);
4628
- if ((await $2`git merge-base --is-ancestor ${`origin/${branch}`} HEAD`.quiet().nothrow()).exitCode !== 0)
5622
+ if (await fetchBranch(branch) && (await $2`git merge-base --is-ancestor ${`origin/${branch}`} HEAD`.quiet().nothrow()).exitCode !== 0)
4629
5623
  fail(`origin/${branch} has commits HEAD lacks`, 2, runHint(`git pull --rebase origin ${branch}`));
4630
5624
  const base = await git(["rev-parse", tagged ? "HEAD~1" : "HEAD"]);
4631
5625
  if (values["dry-run"] === true)
@@ -4659,7 +5653,7 @@ ${usage6}`);
4659
5653
  const tags = bumped.map((each) => each.tag);
4660
5654
  let push;
4661
5655
  try {
4662
- push = await runTool("git push", ["git", "push", "--atomic", "origin", `HEAD:refs/heads/${branch}`, ...tags.map((tag) => `refs/tags/${tag}`)], { timeoutMs: limits.pushMs, onStart: (child) => held.forward(child) });
5656
+ push = await pushToOrigin(["--atomic", "origin", `HEAD:refs/heads/${branch}`, ...tags.map((tag) => `refs/tags/${tag}`)], (child) => held.forward(child));
4663
5657
  } catch (error) {
4664
5658
  isPushUnknown = true;
4665
5659
  fail(`${error instanceof Error ? error.message : String(error)}, so ${tags.join(", ")} and ${tags.length === 1 ? "its commit are" : "their commits are"} kept: the push may have landed`, 2, tags.length === 1 ? `git ls-remote origin refs/tags/${tags[0]} tells; if it is there, ft release --tagged waits for its runs` : `git ls-remote --tags origin tells; if they are there, ft watch --after ${before} waits for their runs`);
@@ -4678,7 +5672,7 @@ ${push.stderr.trim()}`, signal === undefined ? 1 : exitCodeOf(null, signal));
4678
5672
  }
4679
5673
  const heads = new Set(bumped.map((each) => each.head));
4680
5674
  const manifests = await Promise.all(bumped.map(async (each) => {
4681
- const file = Bun.file(join11(each.dir ?? ".", "package.json"));
5675
+ const file = Bun.file(join14(each.dir ?? ".", "package.json"));
4682
5676
  return await file.exists() ? await file.json() : undefined;
4683
5677
  }));
4684
5678
  const released = new Set;
@@ -4697,7 +5691,7 @@ ${push.stderr.trim()}`, signal === undefined ? 1 : exitCodeOf(null, signal));
4697
5691
  if (late !== undefined)
4698
5692
  fail(`interrupted by ${late} after ${bumped.map((each) => each.tag).join(", ")} ${bumped.length === 1 ? "was pushed: its runs are" : "were pushed: their runs are"} not waited for`, exitCodeOf(null, late));
4699
5693
  say(`pushed ${branch} and ${bumped.map((each) => each.tag).join(", ")}, waiting for their runs`);
4700
- followed = await followRuns((runs) => runs.filter((run) => run.id > before && heads.has(run.commit_sha)), timeout, undefined, NO_RUN2, json ? process30.stderr : process30.stdout, { json });
5694
+ followed = await followRuns((runs) => runs.filter((run) => run.id > before && heads.has(run.commit_sha)), timeout, undefined, NO_RUN2, json ? process34.stderr : process34.stdout, { json });
4701
5695
  if (followed.code !== 0) {
4702
5696
  report();
4703
5697
  return followed.code;
@@ -4726,15 +5720,15 @@ ${push.stderr.trim()}`, signal === undefined ? 1 : exitCodeOf(null, signal));
4726
5720
  }
4727
5721
 
4728
5722
  // src/commands/remote.ts
4729
- import { lookup } from "dns/promises";
5723
+ import { lookup as lookup2 } from "dns/promises";
4730
5724
  var {$: $3 } = globalThis.Bun;
4731
- var usage7 = `ft remote [--fix]
5725
+ var usage8 = `ft remote [--fix]
4732
5726
 
4733
5727
  Checks that origin's URLs name the Forgejo host itself: tea only finds the repository when origin's host is the login's ssh_host, never through an ssh alias such as \`forgejo\` or \`gitea\`.
4734
5728
  --fix switches every alias URL to \`git@<host>:<owner>/<repo>.git\` and proves it with \`git ls-remote\`.
4735
5729
  The host comes from --host, else \`remoteHost\` in ~/.config/kaynooo-cli/ft.json; with neither, it checks nothing.`;
4736
- var EXITS6 = [[0, "origin names the Forgejo host (or was switched) or no host is set"], [1, "it does not or a switch is still to run"], [2, "a usage error"]];
4737
- var options7 = {
5730
+ var EXITS7 = [[0, "origin names the Forgejo host (or was switched) or no host is set"], [1, "it does not or a switch is still to run"], [2, "a usage error"]];
5731
+ var options8 = {
4738
5732
  host: { type: "string", description: "the Forgejo ssh host, instead of remoteHost in ~/.config/kaynooo-cli/ft.json" },
4739
5733
  fix: { type: "boolean", description: "rewrite the alias URLs" }
4740
5734
  };
@@ -4750,7 +5744,7 @@ async function sshHostname(alias) {
4750
5744
  }
4751
5745
  async function addresses(name) {
4752
5746
  try {
4753
- return (await lookup(name, { all: true })).map((entry) => entry.address);
5747
+ return (await lookup2(name, { all: true })).map((entry) => entry.address);
4754
5748
  } catch {
4755
5749
  return [];
4756
5750
  }
@@ -4767,7 +5761,7 @@ function originHost2(url) {
4767
5761
  return parseSshRemote(url)?.host ?? (URL.canParse(url) ? new URL(url).hostname : undefined);
4768
5762
  }
4769
5763
  async function remote(args, home) {
4770
- const { values } = parse(args, usage7, options7, { exits: EXITS6 });
5764
+ const { values } = parse(args, usage8, options8, { exits: EXITS7 });
4771
5765
  const host = values.host ?? (await loadSettings(home)).remoteHost;
4772
5766
  if (host === undefined) {
4773
5767
  note(`no Forgejo host to check origin against: pass --host, or set "remoteHost" in ${settingsPath(home)}`);
@@ -4823,14 +5817,14 @@ async function remote(args, home) {
4823
5817
  }
4824
5818
 
4825
5819
  // src/commands/runs.ts
4826
- var usage8 = `ft runs [--sha <ref>]
5820
+ var usage9 = `ft runs [--sha <ref>]
4827
5821
 
4828
5822
  Lists recent runs with what tea's own listing leaves empty: workflow, ref, duration and age, ten by default with the count of the rest (--full for all of them; --json is never cut unless --limit is given).
4829
5823
 
4830
5824
  --open also opens the newest run listed in the browser.`;
4831
- var EXITS7 = [[0, "it listed them"], [1, "Forgejo or git cannot be read"], [2, "a usage error"]];
5825
+ var EXITS8 = [[0, "it listed them"], [1, "Forgejo or git cannot be read"], [2, "a usage error"]];
4832
5826
  var DEFAULT_LIMIT = 10;
4833
- var options8 = {
5827
+ var options9 = {
4834
5828
  ...limitOptions(DEFAULT_LIMIT),
4835
5829
  sha: { type: "string", short: "s", description: "only the runs of this commit" },
4836
5830
  workflow: { type: "string", short: "w", description: "only this workflow file, e.g. test.yml" },
@@ -4844,7 +5838,7 @@ async function onCommit(sha, repo) {
4844
5838
  return { runs: found, total: found.length };
4845
5839
  }
4846
5840
  async function runs(args) {
4847
- const parsed = parse(args, usage8, options8, { exits: EXITS7 });
5841
+ const parsed = parse(args, usage9, options9, { exits: EXITS8 });
4848
5842
  const { values } = parsed;
4849
5843
  const limit = limitOf(values, DEFAULT_LIMIT);
4850
5844
  const { runs: found, total } = values.sha === undefined ? await runsListing(limit, values.repo, values.workflow) : await onCommit(values.sha, values.repo);
@@ -4872,7 +5866,7 @@ async function runs(args) {
4872
5866
  }
4873
5867
 
4874
5868
  // src/cli.ts
4875
- process31.exitCode = await runCli({
5869
+ process35.exitCode = await runCli({
4876
5870
  name: "ft",
4877
5871
  about: "Forgejo tools over tea, run from a repository whose origin is on Forgejo",
4878
5872
  replaces: "tea api calls piped through jq, and sleep loops waiting on CI",
@@ -4881,6 +5875,7 @@ process31.exitCode = await runCli({
4881
5875
  runs: { run: runs, summary: "recent runs with workflow, ref, duration and age", group: "CI and release" },
4882
5876
  ci: { run: ci2, summary: "wait for the runs covering a commit, printing what failed", group: "CI and release" },
4883
5877
  watch: { run: watch2, summary: "wait for runs newer than an id, or those in progress", group: "CI and release" },
5878
+ dispatch: { run: dispatch2, summary: "start a workflow_dispatch run, --wait to follow it to its end", group: "CI and release" },
4884
5879
  logs: { run: logs2, summary: "what the failed jobs of a run say went wrong", group: "CI and release" },
4885
5880
  release: { run: release, summary: "bump, push branch and tag atomically, wait for runs and registry", group: "CI and release" },
4886
5881
  board: { run: board, summary: "open issues: available, taken by a live session, or claimed by one gone", group: "Issues and claims" },
@@ -4889,7 +5884,7 @@ process31.exitCode = await runCli({
4889
5884
  drop: { run: drop, summary: "give back an issue this session took", group: "Issues and claims" },
4890
5885
  issue: { run: issue, summary: "an issue's claim, description and numbered boxes, -c comments", group: "Issues and claims" },
4891
5886
  new: { run: newIssue, summary: "create an issue from -t and a description file or stdin", group: "Issues and claims" },
4892
- edit: { run: edit, summary: "replace an issue's title or description, from a file or stdin", group: "Issues and claims" },
5887
+ edit: { run: edit2, summary: "replace an issue's title or description, from a file or stdin", group: "Issues and claims" },
4893
5888
  tick: { run: tick, summary: "tick checklist boxes of an issue, -m to comment too", group: "Issues and claims" },
4894
5889
  comment: { run: commentOn, summary: "comment on an issue, from stdin when no text is given", group: "Issues and claims" },
4895
5890
  fixed: { run: fixed, summary: 'comment "Fixed in <sha>" and close an issue', group: "Issues and claims" },