@kaynooo/cli-git 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gb.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/gb.ts
5
- import process20 from "process";
5
+ import process23 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -108,7 +108,7 @@ function Fe(r = {}) {
108
108
  var o = Fe();
109
109
 
110
110
  // ../kit/src/theme.ts
111
- import { existsSync as existsSync2, readFileSync, statSync } from "fs";
111
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
112
112
  import { homedir as homedir2 } from "os";
113
113
  import { join as join3, resolve as resolve2 } from "path";
114
114
  import process5 from "process";
@@ -129,6 +129,7 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
129
129
  }
130
130
 
131
131
  // ../kit/src/user-config.ts
132
+ import { existsSync as existsSync2, readFileSync } from "fs";
132
133
  import { homedir } from "os";
133
134
  import { join as join2 } from "path";
134
135
  import process4 from "process";
@@ -139,6 +140,24 @@ function configBase(where = {}) {
139
140
  function userConfigPath(bin, where = {}) {
140
141
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
141
142
  }
143
+ function userConfigReadPath(bin, legacy = [], where = {}) {
144
+ const current = userConfigPath(bin, where);
145
+ if (existsSync2(current))
146
+ return current;
147
+ const base = configBase(where);
148
+ return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
149
+ }
150
+ function readUserConfig(bin, where = {}, legacy = []) {
151
+ const path = userConfigReadPath(bin, legacy, where);
152
+ if (!existsSync2(path))
153
+ return {};
154
+ try {
155
+ const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
156
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
157
+ } catch {
158
+ return {};
159
+ }
160
+ }
142
161
 
143
162
  // ../kit/src/theme.ts
144
163
  function toLinear(channel) {
@@ -240,7 +259,7 @@ function readThemeFile(path, warn) {
240
259
  warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
241
260
  return;
242
261
  }
243
- const parsed = JSON.parse(readFileSync(path, "utf8"));
262
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
244
263
  if (isRecord(parsed))
245
264
  return parsed;
246
265
  warn(`${path} is not a JSON object, theme ignored`);
@@ -306,7 +325,7 @@ function applyFile(theme, file, where, warn) {
306
325
  }
307
326
  }
308
327
  function endsWalk(home) {
309
- return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
328
+ return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
310
329
  }
311
330
  var warned = new Set;
312
331
  function warnOnce(message) {
@@ -474,24 +493,20 @@ function printJson(value) {
474
493
 
475
494
  // ../kit/src/help.ts
476
495
  import process8 from "process";
477
- var OPTIONAL = /\[[^\]]+\]/g;
496
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
478
497
  var USAGE_PREFIX = /^usage:\s*/i;
479
498
  var FULL_STOP = /\.$/;
480
499
  function usageLine(usage, colors = paint(process8.stdout)) {
481
500
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
482
501
  }
483
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
484
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
502
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
503
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
485
504
  `);
486
505
  }
487
506
  function exitRows(exits, colors = paint(process8.stdout)) {
488
507
  if (exits.length === 0)
489
508
  return [];
490
- const width = Math.max(...exits.map(([code]) => String(code).length));
491
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
492
- }
493
- function replacesRows(replaces, colors = paint(process8.stdout)) {
494
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
509
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
495
510
  }
496
511
  function wantsHelpJson(env = process8.env) {
497
512
  return env.KIT_HELP === "json";
@@ -517,29 +532,41 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
517
532
  return [];
518
533
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
519
534
  }
535
+ var MAX_INLINE_CHOICES = 24;
520
536
  function optionRows(options, colors = paint(process8.stdout)) {
521
537
  const rows = Object.entries(options).map(([name, option]) => {
522
538
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
523
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
539
+ const choices = option.choices?.join("|");
540
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
541
+ const named = inline ? `<${choices}>` : "<value>";
524
542
  const placeholder = option.optional === undefined ? named : `[${named}]`;
525
543
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
526
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
544
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
545
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
527
546
  });
528
547
  const width = Math.max(0, ...rows.map((row) => row.width));
529
548
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
530
549
  }
531
550
 
532
551
  // ../kit/src/text.ts
533
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
552
+ var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
534
553
  function distance(a, b) {
535
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
536
- for (const [i, left] of [...a].entries()) {
554
+ const left = [...a];
555
+ const right = [...b];
556
+ let before = [];
557
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
558
+ for (const [i, x] of left.entries()) {
537
559
  const current = [i + 1];
538
- for (const [j, right] of [...b].entries())
539
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
560
+ for (const [j, y] of right.entries()) {
561
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
562
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
563
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
564
+ current.push(cost);
565
+ }
566
+ before = previous;
540
567
  previous = current;
541
568
  }
542
- return previous[b.length] ?? 0;
569
+ return previous[right.length] ?? 0;
543
570
  }
544
571
  function closest(name, names) {
545
572
  const started = names.find((known) => known.startsWith(name));
@@ -788,12 +815,12 @@ function nearestOption(message, options, allowNegative) {
788
815
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
789
816
  }
790
817
  // ../kit/src/argv.ts
791
- import { readFileSync as readFileSync2, realpathSync } from "fs";
818
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
792
819
  import { resolve as resolve3 } from "path";
793
820
  import process10 from "process";
794
821
  function commandLine() {
795
822
  try {
796
- return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
823
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
797
824
  } catch {
798
825
  return;
799
826
  }
@@ -1121,15 +1148,33 @@ function interceptOutput(clear) {
1121
1148
  };
1122
1149
  }
1123
1150
  // ../kit/src/cli.ts
1124
- import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
1151
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
1125
1152
  import { dirname as dirname3, join as join5 } from "path";
1126
- import process14 from "process";
1153
+ import process15 from "process";
1154
+
1155
+ // ../kit/src/notify.ts
1156
+ import process13 from "process";
1157
+ var NOTIFY_AFTER_MS = 1e4;
1158
+ var CANCELLED = 130;
1159
+ function base64(text) {
1160
+ return Buffer.from(text).toString("base64");
1161
+ }
1162
+ function notification(title, body, env = process13.env) {
1163
+ const id = `kit${process13.pid}`;
1164
+ 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\\`];
1165
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1166
+ }
1167
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1168
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1169
+ return;
1170
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1171
+ }
1127
1172
 
1128
1173
  // ../kit/src/usage.ts
1129
1174
  import { appendFileSync, mkdirSync } from "fs";
1130
1175
  import { homedir as homedir3 } from "os";
1131
1176
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1132
- import process13 from "process";
1177
+ import process14 from "process";
1133
1178
 
1134
1179
  // ../kit/src/logs.ts
1135
1180
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -1143,14 +1188,14 @@ var usageError;
1143
1188
  function noteUsageError(message) {
1144
1189
  usageError = message;
1145
1190
  }
1146
- function stateHome(env = process13.env) {
1191
+ function stateHome(env = process14.env) {
1147
1192
  const dir = env.XDG_STATE_HOME;
1148
1193
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1149
1194
  }
1150
- function usagePath(env = process13.env) {
1195
+ function usagePath(env = process14.env) {
1151
1196
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1152
1197
  }
1153
- function usageRecorded(env = process13.env) {
1198
+ function usageRecorded(env = process14.env) {
1154
1199
  const off = env.KAYNOOO_CLI_NO_USAGE;
1155
1200
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1156
1201
  }
@@ -1164,7 +1209,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
1164
1209
  usageError = undefined;
1165
1210
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1166
1211
  }
1167
- function recordUsage(entry, env = process13.env) {
1212
+ function recordUsage(entry, env = process14.env) {
1168
1213
  if (!usageRecorded(env))
1169
1214
  return;
1170
1215
  try {
@@ -1182,8 +1227,8 @@ var LEVEL_OPTIONS = {
1182
1227
  };
1183
1228
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1184
1229
  function printError(prefix, message, hint, cause) {
1185
- const colors = paint(process14.stderr);
1186
- const styled = takesControlCodes(process14.stderr);
1230
+ const colors = paint(process15.stderr);
1231
+ const styled = takesControlCodes(process15.stderr);
1187
1232
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1188
1233
  const under = (label, text, tint) => text === undefined ? "" : `
1189
1234
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1269,9 +1314,13 @@ async function printCandidates(found) {
1269
1314
  return 0;
1270
1315
  }
1271
1316
  function packageVersion(entry = Bun.main) {
1272
- for (let dir = dirname3(realpathSync2(entry));; dir = dirname3(dir)) {
1317
+ let resolved = entry;
1318
+ try {
1319
+ resolved = realpathSync2(entry);
1320
+ } catch {}
1321
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1273
1322
  try {
1274
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1323
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1275
1324
  if (typeof version === "string")
1276
1325
  return version;
1277
1326
  } catch {}
@@ -1287,11 +1336,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
1287
1336
  return 0;
1288
1337
  }
1289
1338
  let code;
1339
+ const started = performance.now();
1290
1340
  try {
1291
1341
  code = await run(argv);
1292
1342
  } catch (error) {
1293
1343
  code = reportThrown(name, error, redact, wantsJson(argv));
1294
1344
  }
1345
+ notifyEnd(name, code, performance.now() - started);
1295
1346
  if (usage !== false) {
1296
1347
  try {
1297
1348
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1308,7 +1359,7 @@ var {Glob } = globalThis.Bun;
1308
1359
  var SESSION_FILES = new Glob("*.json");
1309
1360
  var ACCOUNT_DIRS = new Glob("*/sessions");
1310
1361
  // ../kit/src/watch.ts
1311
- import process15 from "process";
1362
+ import process16 from "process";
1312
1363
  import { format } from "util";
1313
1364
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1314
1365
  var DEFAULT_SECONDS = 2;
@@ -1330,7 +1381,7 @@ function withoutWatch(args) {
1330
1381
  }
1331
1382
  return rest;
1332
1383
  }
1333
- async function watching(value, step, stream = process15.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1384
+ async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1334
1385
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1335
1386
  if (!takesControlCodes(stream))
1336
1387
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1338,12 +1389,12 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1338
1389
  for (let round = 0;round < rounds; round++) {
1339
1390
  const held = [];
1340
1391
  const { log, info } = console;
1341
- const write = process15.stdout.write.bind(process15.stdout);
1392
+ const write = process16.stdout.write.bind(process16.stdout);
1342
1393
  const hold = (...parts) => void held.push(`${format(...parts)}
1343
1394
  `);
1344
1395
  console.log = hold;
1345
1396
  console.info = hold;
1346
- process15.stdout.write = (text) => {
1397
+ process16.stdout.write = (text) => {
1347
1398
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1348
1399
  return true;
1349
1400
  };
@@ -1352,16 +1403,146 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1352
1403
  } finally {
1353
1404
  console.log = log;
1354
1405
  console.info = info;
1355
- process15.stdout.write = write;
1406
+ process16.stdout.write = write;
1356
1407
  }
1357
1408
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1358
1409
  await sleep(interval);
1359
1410
  }
1360
1411
  return code;
1361
1412
  }
1413
+ // ../kit/src/workspace-root.ts
1414
+ import { homedir as homedir4 } from "os";
1415
+ import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1416
+ import process17 from "process";
1417
+ function expandHome(path, home) {
1418
+ if (path === "~")
1419
+ return home;
1420
+ return path.startsWith("~/") ? join6(home, path.slice(2)) : path;
1421
+ }
1422
+ function configured(env, home) {
1423
+ const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1424
+ return typeof folder === "string" && folder !== "" ? folder : undefined;
1425
+ }
1426
+ function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
1427
+ const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1428
+ return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1429
+ }
1362
1430
  // src/branch.ts
1363
1431
  import { basename } from "path";
1364
- import process19 from "process";
1432
+ import process22 from "process";
1433
+
1434
+ // ../kit/src/picker/line.ts
1435
+ var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1436
+ var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1437
+ var FORWARD_KILLS = new Set(["killnext", "killend"]);
1438
+ function isEditKey(key) {
1439
+ return EDIT_KEYS.has(key);
1440
+ }
1441
+ function endsKills(key) {
1442
+ return typeof key !== "object" && !isEditKey(key);
1443
+ }
1444
+ var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
1445
+ var SPACE = /\s/;
1446
+ function isWord(char) {
1447
+ return char !== undefined && WORD_CHARACTER.test(char);
1448
+ }
1449
+ function wordStart(chars, from) {
1450
+ let at = from;
1451
+ while (at > 0 && !isWord(chars[at - 1]))
1452
+ at--;
1453
+ while (at > 0 && isWord(chars[at - 1]))
1454
+ at--;
1455
+ return at;
1456
+ }
1457
+ function wordEnd(chars, from) {
1458
+ let at = from;
1459
+ while (at < chars.length && !isWord(chars[at]))
1460
+ at++;
1461
+ while (at < chars.length && isWord(chars[at]))
1462
+ at++;
1463
+ return at;
1464
+ }
1465
+ function spacedStart(chars, from) {
1466
+ let at = from;
1467
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
1468
+ at--;
1469
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
1470
+ at--;
1471
+ return at;
1472
+ }
1473
+ function cut(chars, from, to) {
1474
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
1475
+ }
1476
+ function insert(chars, at, text) {
1477
+ const typed = [...text];
1478
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
1479
+ }
1480
+ function editLine(line, key) {
1481
+ const { killed = "", chained = false } = line;
1482
+ const chars = [...line.text];
1483
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
1484
+ const edited = edit(chars, at, key, killed);
1485
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
1486
+ return line.killed === undefined ? edited : { ...edited, killed };
1487
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1488
+ if (taken === "")
1489
+ return { ...edited, killed, chained };
1490
+ if (!chained)
1491
+ return { ...edited, killed: taken, chained: true };
1492
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
1493
+ }
1494
+ function edit(chars, at, key, killed) {
1495
+ const text = chars.join("");
1496
+ if (typeof key === "object")
1497
+ return insert(chars, at, key.text);
1498
+ switch (key) {
1499
+ case "left":
1500
+ return { text, caret: Math.max(at - 1, 0) };
1501
+ case "right":
1502
+ return { text, caret: Math.min(at + 1, chars.length) };
1503
+ case "wordleft":
1504
+ return { text, caret: wordStart(chars, at) };
1505
+ case "wordright":
1506
+ return { text, caret: wordEnd(chars, at) };
1507
+ case "linestart":
1508
+ return { text, caret: 0 };
1509
+ case "lineend":
1510
+ return { text, caret: chars.length };
1511
+ case "erase":
1512
+ return cut(chars, Math.max(at - 1, 0), at);
1513
+ case "delete":
1514
+ return cut(chars, at, Math.min(at + 1, chars.length));
1515
+ case "word":
1516
+ return cut(chars, spacedStart(chars, at), at);
1517
+ case "killword":
1518
+ return cut(chars, wordStart(chars, at), at);
1519
+ case "killnext":
1520
+ return cut(chars, at, wordEnd(chars, at));
1521
+ case "clear":
1522
+ return cut(chars, 0, at);
1523
+ case "killend":
1524
+ return cut(chars, at, chars.length);
1525
+ case "yank":
1526
+ return insert(chars, at, killed);
1527
+ }
1528
+ }
1529
+ function visible({ text, caret }, room) {
1530
+ const chars = [...text];
1531
+ const at = Math.min(Math.max(caret, 0), chars.length);
1532
+ const cells = at === chars.length ? [...chars, " "] : chars;
1533
+ const widths = cells.map((char) => Bun.stringWidth(char));
1534
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
1535
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
1536
+ let start = at;
1537
+ let end = at + 1;
1538
+ while (start > 0 && fits(start - 1, end))
1539
+ start--;
1540
+ while (end < cells.length && fits(start, end + 1))
1541
+ end++;
1542
+ const left = start > 0 ? "\u2026" : "";
1543
+ const right = end < cells.length ? "\u2026" : "";
1544
+ 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) };
1545
+ }
1365
1546
 
1366
1547
  // ../kit/src/picker/score.ts
1367
1548
  var MATCH = 16;
@@ -1447,7 +1628,6 @@ function rank(query, lines) {
1447
1628
  }
1448
1629
 
1449
1630
  // ../kit/src/picker/state.ts
1450
- var ANSI2 = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
1451
1631
  var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1452
1632
  var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1453
1633
  var SGR = /^\x1B\[[0-9;]*m$/;
@@ -1455,7 +1635,6 @@ var RESET = /^\x1B\[0?m$/;
1455
1635
  var COLUMN_GAP = 2;
1456
1636
  var PASTE_START = "\x1B[200~";
1457
1637
  var PASTE_END = "\x1B[201~";
1458
- var LAST_WORD = /\S*\s*$/;
1459
1638
  var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1460
1639
  var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1461
1640
  var WHEEL_LINES = 3;
@@ -1478,10 +1657,29 @@ var KEYS = {
1478
1657
  "\n": "enter",
1479
1658
  "\x03": "cancel",
1480
1659
  "\x1B": "cancel",
1660
+ "\x1B[D": "left",
1661
+ "\x1BOD": "left",
1662
+ "\x1B[C": "right",
1663
+ "\x1BOC": "right",
1664
+ "\x1B[1;5D": "wordleft",
1665
+ "\x1B[1;3D": "wordleft",
1666
+ "\x1Bb": "wordleft",
1667
+ "\x1B[1;5C": "wordright",
1668
+ "\x1B[1;3C": "wordright",
1669
+ "\x1Bf": "wordright",
1670
+ "\x01": "linestart",
1671
+ "\x05": "lineend",
1481
1672
  "\x7F": "erase",
1482
- "\b": "erase",
1673
+ "\x1B[3~": "delete",
1674
+ "\b": "killword",
1675
+ "\x1B\x7F": "killword",
1676
+ "\x1B[3;5~": "killnext",
1677
+ "\x1Bd": "killnext",
1483
1678
  "\x15": "clear",
1679
+ "\v": "killend",
1484
1680
  "\x17": "word",
1681
+ "\x19": "yank",
1682
+ "\x1A": "suspend",
1485
1683
  "\t": "tab",
1486
1684
  "\x1F": "help",
1487
1685
  "\x1BOP": "help",
@@ -1503,7 +1701,7 @@ function styled(line) {
1503
1701
  colored ||= active !== "" && flat !== "";
1504
1702
  styles.push(...repeat(active, flat.length));
1505
1703
  }
1506
- for (const found of line.matchAll(ANSI2)) {
1704
+ for (const found of line.matchAll(ANSI)) {
1507
1705
  add(line.slice(last, found.index));
1508
1706
  last = found.index + found[0].length;
1509
1707
  if (SGR.test(found[0]))
@@ -1515,7 +1713,7 @@ function styled(line) {
1515
1713
  function lay(rows, searched) {
1516
1714
  const parsed = rows.map((row) => row.cells.map(styled));
1517
1715
  const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1518
- return parsed.map((cells) => {
1716
+ return parsed.map((cells, at) => {
1519
1717
  let text = "";
1520
1718
  const styles = [];
1521
1719
  let colored = false;
@@ -1534,7 +1732,7 @@ function lay(rows, searched) {
1534
1732
  styles.push(...repeat("", pad));
1535
1733
  }
1536
1734
  }
1537
- return { text, styles: colored ? styles : undefined, searchable: text.slice(0, searchEnd) };
1735
+ return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1538
1736
  });
1539
1737
  }
1540
1738
  function parseKeys(input, paste = { active: false }, ctrls = []) {
@@ -1558,7 +1756,7 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
1558
1756
  });
1559
1757
  }
1560
1758
  function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1561
- const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1759
+ const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, killed: "", chained: false, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1562
1760
  return withRows(state, rows);
1563
1761
  }
1564
1762
  function withRows(state, rows, header = state.header) {
@@ -1568,8 +1766,9 @@ function withRows(state, rows, header = state.header) {
1568
1766
  const matches = rank(state.query, searchable);
1569
1767
  return { ...state, rows: cells, items: laid.map((row) => row.text), styles: laid.map((row) => row.styles), searchable, header, matches, cursor: Math.max(0, Math.min(matches.length - 1, state.cursor)), marked: new Set };
1570
1768
  }
1571
- function withQuery(state, query) {
1572
- return { ...state, query, matches: rank(query, state.searchable), cursor: 0 };
1769
+ function withQuery(state, key) {
1770
+ const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1771
+ return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1573
1772
  }
1574
1773
  function move(state, by) {
1575
1774
  return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
@@ -1580,13 +1779,17 @@ function highlighted(state) {
1580
1779
  function press(state, key) {
1581
1780
  if (state.done !== undefined)
1582
1781
  return state;
1782
+ if (state.chained && endsKills(key))
1783
+ state = { ...state, chained: false };
1583
1784
  if (state.help)
1584
1785
  return { ...state, help: false };
1585
1786
  if (typeof key === "object") {
1586
1787
  if ("text" in key)
1587
- return withQuery(state, state.query + key.text);
1788
+ return withQuery(state, key);
1588
1789
  return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1589
1790
  }
1791
+ if (isEditKey(key))
1792
+ return withQuery(state, key);
1590
1793
  switch (key) {
1591
1794
  case "up":
1592
1795
  return move(state, -1);
@@ -1604,12 +1807,8 @@ function press(state, key) {
1604
1807
  return { ...state, done: "cancel" };
1605
1808
  case "help":
1606
1809
  return { ...state, help: true };
1607
- case "erase":
1608
- return withQuery(state, [...state.query].slice(0, -1).join(""));
1609
- case "clear":
1610
- return withQuery(state, "");
1611
- case "word":
1612
- return withQuery(state, state.query.replace(LAST_WORD, ""));
1810
+ case "suspend":
1811
+ return state;
1613
1812
  case "enter":
1614
1813
  return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1615
1814
  case "tab": {
@@ -1632,11 +1831,25 @@ function chosen(state) {
1632
1831
 
1633
1832
  // ../kit/src/picker/terminal.ts
1634
1833
  import { openSync } from "fs";
1635
- import process18 from "process";
1834
+ import process21 from "process";
1636
1835
  import tty from "tty";
1637
1836
 
1837
+ // ../kit/src/job.ts
1838
+ import process19 from "process";
1839
+ function stopJob() {
1840
+ process19.kill(0, "SIGTSTP");
1841
+ }
1842
+
1843
+ // ../kit/src/redraw.ts
1844
+ var SYNC_START = "\x1B[?2026h";
1845
+ var SYNC_END = "\x1B[?2026l";
1846
+ function overwrite(lines, columns) {
1847
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1848
+ `);
1849
+ }
1850
+
1638
1851
  // ../kit/src/picker/preview.ts
1639
- import process17 from "process";
1852
+ import process20 from "process";
1640
1853
 
1641
1854
  // ../kit/src/shell.ts
1642
1855
  var SEPARATORS = new Set([`
@@ -1705,7 +1918,7 @@ async function runPreview(template, line, signal, hidden = []) {
1705
1918
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1706
1919
  const stop = () => {
1707
1920
  try {
1708
- process17.kill(-proc.pid, "SIGKILL");
1921
+ process20.kill(-proc.pid, "SIGKILL");
1709
1922
  } catch {
1710
1923
  proc.kill();
1711
1924
  }
@@ -1780,13 +1993,20 @@ function fitStyled(line, width, plain = identity) {
1780
1993
  const { text, styles } = styled(line);
1781
1994
  return fit(text, width, plain, plain, new Set, styles);
1782
1995
  }
1783
- function caretColumn(state, layout) {
1784
- return Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + Bun.stringWidth(state.query) + 1);
1996
+ function queryShown(state, layout) {
1997
+ return visible({ text: state.query, caret: state.caret }, Math.max(1, layout.listWidth - Bun.stringWidth(state.prompt)));
1998
+ }
1999
+ function caretCell(state, layout) {
2000
+ const shown = queryShown(state, layout);
2001
+ return { column: Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + shown.column + 1), char: shown.at ?? " " };
1785
2002
  }
1786
2003
  function helpLines(state, layout, theme) {
1787
2004
  const lines = [
1788
2005
  "type to filter, up, down, ctrl-p, ctrl-n, pgup, pgdn, home, end, the wheel move",
1789
- `enter picks${state.multi ? ", tab marks" : ""}, ctrl-u clears the query, ctrl-w a word, esc or ctrl-c cancels`,
2006
+ "left, right, ctrl-a, ctrl-e move in the query, ctrl or alt with left or right by a word",
2007
+ "ctrl-w or ctrl-backspace erase a word, ctrl-u back to the start, ctrl-k to the end, del ahead",
2008
+ "ctrl-y puts back what they erased, ctrl-z suspends to the shell",
2009
+ `enter picks${state.multi ? ", tab marks" : ""}, esc or ctrl-c cancels`,
1790
2010
  ...state.expect.length > 0 ? [`${state.expect.join(", ")} end the pick as this command asks`] : []
1791
2011
  ];
1792
2012
  const title = "keys, any key closes this help";
@@ -1802,7 +2022,9 @@ function listLines(state, layout, theme) {
1802
2022
  const top = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), state.matches.length - rows));
1803
2023
  const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
1804
2024
  const promptWidth = Bun.stringWidth(state.prompt);
1805
- const query = fit(state.query, Math.max(1, layout.listWidth - promptWidth), identity);
2025
+ const shown = queryShown(state, layout);
2026
+ const text = `${shown.before}${shown.at ?? ""}${shown.after}`;
2027
+ const query = { text, width: Bun.stringWidth(text) };
1806
2028
  const place = state.matches.length > rows ? ` (${state.cursor + 1} of ${state.matches.length})` : "";
1807
2029
  const count = fit(` ${state.matches.length}/${state.items.length}${place}${marks} ctrl-/ keys`, layout.listWidth, theme.label);
1808
2030
  const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
@@ -1835,7 +2057,8 @@ var ESCAPE_WAIT_MS = 30;
1835
2057
  var OPEN = { ctrl: "open" };
1836
2058
  var HIDE_CURSOR = "\x1B[?25l";
1837
2059
  var SHOW_CURSOR = "\x1B[?25h";
1838
- var CARET = "\x1B[7m \x1B[27m";
2060
+ var REVERSE = "\x1B[7m";
2061
+ var REVERSE_END = "\x1B[27m";
1839
2062
  var PASTE_ON = "\x1B[?2004h";
1840
2063
  var PASTE_OFF = "\x1B[?2004l";
1841
2064
  var MOUSE_ON = "\x1B[?1000h\x1B[?1006h";
@@ -1853,7 +2076,7 @@ function openTerminal() {
1853
2076
  return fail("no terminal to read keys from (/dev/tty)");
1854
2077
  }
1855
2078
  const keys = Bun.file("/dev/tty").stream().getReader();
1856
- const out = process18.stderr;
2079
+ const out = process21.stderr;
1857
2080
  let resize;
1858
2081
  async function read(onChunk) {
1859
2082
  const decoder = new TextDecoder;
@@ -1879,6 +2102,11 @@ function openTerminal() {
1879
2102
  out.on("resize", onResize);
1880
2103
  read(onChunk);
1881
2104
  },
2105
+ suspend() {
2106
+ mode.setRawMode(false);
2107
+ stopJob();
2108
+ mode.setRawMode(true);
2109
+ },
1882
2110
  close() {
1883
2111
  if (resize !== undefined)
1884
2112
  out.off("resize", resize);
@@ -1906,14 +2134,14 @@ async function select(rows, settings, terminal = openTerminal()) {
1906
2134
  if (restored)
1907
2135
  return;
1908
2136
  const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
1909
- let frame = HIDE_CURSOR;
2137
+ let frame = SYNC_START + HIDE_CURSOR;
1910
2138
  if (reserved !== layout.height || clear) {
1911
2139
  frame += CLEAR_BELOW2 + `
1912
2140
  `.repeat(layout.height - 1) + up(layout.height - 1);
1913
2141
  reserved = layout.height;
1914
2142
  }
1915
- frame += `\r${render(state, layout, theme, preview).map((line) => `\x1B[2K${line}`).join(`
1916
- `)}${up(layout.height - 1)}\r\x1B[${caretColumn(state, layout)}G${CARET}\r`;
2143
+ const caret = caretCell(state, layout);
2144
+ frame += `\r${overwrite(render(state, layout, theme, preview), terminal.columns)}${up(layout.height - 1)}\r\x1B[${caret.column}G${REVERSE}${caret.char}${REVERSE_END}\r${SYNC_END}`;
1917
2145
  terminal.write(frame);
1918
2146
  }
1919
2147
  function pageSize() {
@@ -1955,6 +2183,14 @@ async function select(rows, settings, terminal = openTerminal()) {
1955
2183
  terminal.write(`${CLEAR_BELOW2}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
1956
2184
  terminal.close();
1957
2185
  }
2186
+ function suspend() {
2187
+ if (terminal.suspend === undefined)
2188
+ return;
2189
+ terminal.write(`${CLEAR_BELOW2}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
2190
+ terminal.suspend();
2191
+ terminal.write(`${PASTE_ON}${MOUSE_ON}`);
2192
+ draw(true);
2193
+ }
1958
2194
  const stop = () => {
1959
2195
  state = { ...state, done: "cancel" };
1960
2196
  finish?.();
@@ -1988,6 +2224,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1988
2224
  for (let key = pending.shift();key !== undefined && state.done === undefined; key = pending.shift()) {
1989
2225
  if (key === OPEN || typeof key === "object" && "ctrl" in key && key.ctrl === reload?.key)
1990
2226
  await reloadRows();
2227
+ else if (key === "suspend")
2228
+ suspend();
1991
2229
  else
1992
2230
  state = press({ ...state, page: pageSize() }, key);
1993
2231
  }
@@ -2027,9 +2265,9 @@ async function select(rows, settings, terminal = openTerminal()) {
2027
2265
  const ended = new Promise((resolve) => {
2028
2266
  finish = resolve;
2029
2267
  });
2030
- process18.once("exit", restore);
2268
+ process21.once("exit", restore);
2031
2269
  for (const signal of SIGNALS2)
2032
- process18.once(signal, stop);
2270
+ process21.once(signal, stop);
2033
2271
  try {
2034
2272
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
2035
2273
  terminal.listen(onChunk, () => draw(true));
@@ -2042,8 +2280,8 @@ async function select(rows, settings, terminal = openTerminal()) {
2042
2280
  await ended;
2043
2281
  } finally {
2044
2282
  for (const signal of SIGNALS2)
2045
- process18.off(signal, stop);
2046
- process18.off("exit", restore);
2283
+ process21.off(signal, stop);
2284
+ process21.off("exit", restore);
2047
2285
  restore();
2048
2286
  }
2049
2287
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -2314,7 +2552,7 @@ async function gb(args) {
2314
2552
  if (parsed.values.json === true)
2315
2553
  printJson(all);
2316
2554
  else
2317
- console.log(table2(all.map(row)).map((line) => takesControlCodes(process19.stdout) ? line : Bun.stripANSI(line)).join(`
2555
+ console.log(table2(all.map(row)).map((line) => takesControlCodes(process22.stdout) ? line : Bun.stripANSI(line)).join(`
2318
2556
  `));
2319
2557
  return 0;
2320
2558
  }
@@ -2371,4 +2609,4 @@ async function finish(command, typed, emitting) {
2371
2609
  }
2372
2610
 
2373
2611
  // src/gb.ts
2374
- process20.exitCode = await runMain({ name: "gb", run: gb });
2612
+ process23.exitCode = await runMain({ name: "gb", run: gb });