@kaynooo/cli-workspace 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/audit-cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/audit-cli.ts
5
- import process18 from "process";
5
+ import process20 from "process";
6
6
 
7
7
  // ../kit/src/advisory.ts
8
8
  var SEVERITIES = ["low", "moderate", "high", "critical"];
@@ -492,24 +492,20 @@ function printJson(value) {
492
492
 
493
493
  // ../kit/src/help.ts
494
494
  import process8 from "process";
495
- var OPTIONAL = /\[[^\]]+\]/g;
495
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
496
496
  var USAGE_PREFIX = /^usage:\s*/i;
497
497
  var FULL_STOP = /\.$/;
498
498
  function usageLine(usage, colors = paint(process8.stdout)) {
499
499
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
500
500
  }
501
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
502
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
501
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
502
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
503
503
  `);
504
504
  }
505
505
  function exitRows(exits, colors = paint(process8.stdout)) {
506
506
  if (exits.length === 0)
507
507
  return [];
508
- const width = Math.max(...exits.map(([code]) => String(code).length));
509
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
510
- }
511
- function replacesRows(replaces, colors = paint(process8.stdout)) {
512
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
508
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
513
509
  }
514
510
  function wantsHelpJson(env = process8.env) {
515
511
  return env.KIT_HELP === "json";
@@ -535,29 +531,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
535
531
  return [];
536
532
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
537
533
  }
534
+ var MAX_INLINE_CHOICES = 24;
538
535
  function optionRows(options, colors = paint(process8.stdout)) {
539
536
  const rows = Object.entries(options).map(([name, option]) => {
540
537
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
541
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
538
+ const choices = option.choices?.join("|");
539
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
540
+ const named = inline ? `<${choices}>` : "<value>";
542
541
  const placeholder = option.optional === undefined ? named : `[${named}]`;
543
542
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
544
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
543
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
544
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
545
545
  });
546
546
  const width = Math.max(0, ...rows.map((row) => row.width));
547
547
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
548
548
  }
549
549
 
550
550
  // ../kit/src/text.ts
551
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
552
551
  function distance(a, b) {
553
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
554
- for (const [i, left] of [...a].entries()) {
552
+ const left = [...a];
553
+ const right = [...b];
554
+ let before = [];
555
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
556
+ for (const [i, x] of left.entries()) {
555
557
  const current = [i + 1];
556
- for (const [j, right] of [...b].entries())
557
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
558
+ for (const [j, y] of right.entries()) {
559
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
560
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
561
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
562
+ current.push(cost);
563
+ }
564
+ before = previous;
558
565
  previous = current;
559
566
  }
560
- return previous[b.length] ?? 0;
567
+ return previous[right.length] ?? 0;
561
568
  }
562
569
  function closest(name, names) {
563
570
  const started = names.find((known) => known.startsWith(name));
@@ -796,9 +803,33 @@ function nearestOption(message, options, allowNegative) {
796
803
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
797
804
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
798
805
  }
806
+ // ../kit/src/argv.ts
807
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
808
+ import { resolve as resolve3 } from "path";
809
+ import process10 from "process";
810
+ function commandLine() {
811
+ try {
812
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
813
+ } catch {
814
+ return;
815
+ }
816
+ }
817
+ function realPath(word) {
818
+ try {
819
+ return realpathSync(resolve3(word));
820
+ } catch {
821
+ return;
822
+ }
823
+ }
824
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
825
+ const target = script === undefined ? undefined : realPath(script) ?? script;
826
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
827
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
828
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
829
+ }
799
830
  // ../kit/src/process.ts
800
831
  import { constants } from "os";
801
- import process10 from "process";
832
+ import process11 from "process";
802
833
  var KILL_GRACE_MS = 2000;
803
834
  function exitCodeOf(code, signal) {
804
835
  if (code !== null)
@@ -818,7 +849,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
818
849
  return;
819
850
  try {
820
851
  if (grouped)
821
- process10.kill(-proc.pid, killing);
852
+ process11.kill(-proc.pid, killing);
822
853
  else
823
854
  proc.kill(killing);
824
855
  } catch {}
@@ -893,10 +924,10 @@ var RESET_STYLE = `${ESC}[0m`;
893
924
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
894
925
 
895
926
  // ../kit/src/tool.ts
896
- import process11 from "process";
927
+ import process12 from "process";
897
928
  function cwdGone() {
898
929
  try {
899
- process11.cwd();
930
+ process12.cwd();
900
931
  return false;
901
932
  } catch {
902
933
  return true;
@@ -918,7 +949,7 @@ function spawnFailure(command, error) {
918
949
  async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
919
950
  let ran;
920
951
  try {
921
- ran = await runCommand(argv, { env: process11.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
952
+ ran = await runCommand(argv, { env: process12.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
922
953
  } catch (error) {
923
954
  throw spawnFailure(label, error);
924
955
  }
@@ -933,15 +964,33 @@ async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
933
964
  return { code: ran.code, ...streams };
934
965
  }
935
966
  // ../kit/src/cli.ts
936
- import { readFileSync as readFileSync3, realpathSync } from "fs";
967
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
937
968
  import { dirname as dirname3, join as join5 } from "path";
969
+ import process15 from "process";
970
+
971
+ // ../kit/src/notify.ts
938
972
  import process13 from "process";
973
+ var NOTIFY_AFTER_MS = 1e4;
974
+ var CANCELLED = 130;
975
+ function base64(text) {
976
+ return Buffer.from(text).toString("base64");
977
+ }
978
+ function notification(title, body, env = process13.env) {
979
+ const id = `kit${process13.pid}`;
980
+ 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\\`];
981
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
982
+ }
983
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
984
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
985
+ return;
986
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
987
+ }
939
988
 
940
989
  // ../kit/src/usage.ts
941
990
  import { appendFileSync, mkdirSync } from "fs";
942
991
  import { homedir as homedir3 } from "os";
943
992
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
944
- import process12 from "process";
993
+ import process14 from "process";
945
994
 
946
995
  // ../kit/src/logs.ts
947
996
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -955,14 +1004,14 @@ var usageError;
955
1004
  function noteUsageError(message) {
956
1005
  usageError = message;
957
1006
  }
958
- function stateHome(env = process12.env) {
1007
+ function stateHome(env = process14.env) {
959
1008
  const dir = env.XDG_STATE_HOME;
960
1009
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
961
1010
  }
962
- function usagePath(env = process12.env) {
1011
+ function usagePath(env = process14.env) {
963
1012
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
964
1013
  }
965
- function usageRecorded(env = process12.env) {
1014
+ function usageRecorded(env = process14.env) {
966
1015
  const off = env.KAYNOOO_CLI_NO_USAGE;
967
1016
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
968
1017
  }
@@ -976,7 +1025,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
976
1025
  usageError = undefined;
977
1026
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
978
1027
  }
979
- function recordUsage(entry, env = process12.env) {
1028
+ function recordUsage(entry, env = process14.env) {
980
1029
  if (!usageRecorded(env))
981
1030
  return;
982
1031
  try {
@@ -1053,7 +1102,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1053
1102
  header(colors, summary),
1054
1103
  "",
1055
1104
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
1056
- ...replacesRows(replaces, colors),
1057
1105
  "",
1058
1106
  ...await commandRows(commands, colors),
1059
1107
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -1067,8 +1115,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1067
1115
  `);
1068
1116
  }
1069
1117
  function printError(prefix, message, hint, cause) {
1070
- const colors = paint(process13.stderr);
1071
- const styled = takesControlCodes(process13.stderr);
1118
+ const colors = paint(process15.stderr);
1119
+ const styled = takesControlCodes(process15.stderr);
1072
1120
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1073
1121
  const under = (label, text, tint) => text === undefined ? "" : `
1074
1122
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1111,11 +1159,11 @@ async function dispatch(level, typed, { version, redact }) {
1111
1159
  }
1112
1160
  }
1113
1161
  if (name === undefined && level.path.length > 1) {
1114
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1162
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
1115
1163
  return 2;
1116
1164
  }
1117
1165
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1118
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1166
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
1119
1167
  return 0;
1120
1168
  }
1121
1169
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1171,24 +1219,24 @@ function candidateLine(candidate) {
1171
1219
  }
1172
1220
  function positionalBeingTyped(before, { options, positionals }) {
1173
1221
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1174
- let index = 0;
1222
+ const typed = [];
1175
1223
  let at = 0;
1176
1224
  while (at < before.length) {
1177
1225
  const word = before[at];
1178
1226
  if (word === "--") {
1179
- index += before.length - at - 1;
1227
+ typed.push(...before.slice(at + 1));
1180
1228
  break;
1181
1229
  }
1182
1230
  if (!word.startsWith("-"))
1183
- index++;
1231
+ typed.push(word);
1184
1232
  else if (takesValue(word))
1185
1233
  at++;
1186
1234
  at++;
1187
1235
  }
1188
1236
  const last = positionals.at(-1);
1189
- if (index < positionals.length)
1190
- return positionals[index];
1191
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1237
+ if (typed.length < positionals.length)
1238
+ return { name: positionals[typed.length], typed };
1239
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1192
1240
  }
1193
1241
  async function leafCandidates(run, words) {
1194
1242
  const completing = await completingOf(run);
@@ -1196,12 +1244,12 @@ async function leafCandidates(run, words) {
1196
1244
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1197
1245
  const flag = words.at(-2);
1198
1246
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1247
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1199
1248
  if (option?.type === "string") {
1200
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1249
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1201
1250
  return values === undefined ? [FILES] : values.map(candidateLine);
1202
1251
  }
1203
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1204
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1252
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1205
1253
  return values === undefined ? [FILES] : values.map(candidateLine);
1206
1254
  }
1207
1255
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -1232,9 +1280,13 @@ async function printCandidates(found) {
1232
1280
  return 0;
1233
1281
  }
1234
1282
  function packageVersion(entry = Bun.main) {
1235
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1283
+ let resolved = entry;
1284
+ try {
1285
+ resolved = realpathSync2(entry);
1286
+ } catch {}
1287
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1236
1288
  try {
1237
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1289
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1238
1290
  if (typeof version === "string")
1239
1291
  return version;
1240
1292
  } catch {}
@@ -1242,14 +1294,17 @@ function packageVersion(entry = Bun.main) {
1242
1294
  return "0.0.0";
1243
1295
  }
1244
1296
  }
1245
- async function runCli(cli, argv = process13.argv.slice(2)) {
1297
+ async function runCli(cli, argv = scriptArgs()) {
1246
1298
  const version = cli.version ?? packageVersion();
1247
1299
  if (argv[0] === COMPLETE)
1248
1300
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1301
+ const started = performance.now();
1249
1302
  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 });
1303
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1304
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1250
1305
  if (cli.usage !== false) {
1251
1306
  try {
1252
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1307
+ recordUsage(usageEntry(cli.name, command, argv, code));
1253
1308
  } catch {}
1254
1309
  }
1255
1310
  return code;
@@ -1269,7 +1324,7 @@ function commandPath(scope, argv) {
1269
1324
  }
1270
1325
  return path.length === 0 ? undefined : path.join(" ");
1271
1326
  }
1272
- async function runMain({ name, version, run, redact, usage }, argv = process13.argv.slice(2)) {
1327
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1273
1328
  if (argv[0] === COMPLETE)
1274
1329
  return printCandidates(leafCandidates(run, argv.slice(1)));
1275
1330
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1277,11 +1332,13 @@ async function runMain({ name, version, run, redact, usage }, argv = process13.a
1277
1332
  return 0;
1278
1333
  }
1279
1334
  let code;
1335
+ const started = performance.now();
1280
1336
  try {
1281
1337
  code = await run(argv);
1282
1338
  } catch (error) {
1283
1339
  code = reportThrown(name, error, redact, wantsJson(argv));
1284
1340
  }
1341
+ notifyEnd(name, code, performance.now() - started);
1285
1342
  if (usage !== false) {
1286
1343
  try {
1287
1344
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1321,7 +1378,7 @@ function parseSize(text, bareUnit = 1) {
1321
1378
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1322
1379
  }
1323
1380
  // ../kit/src/watch.ts
1324
- import process14 from "process";
1381
+ import process16 from "process";
1325
1382
  import { format } from "util";
1326
1383
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1327
1384
  var DEFAULT_SECONDS = 2;
@@ -1343,7 +1400,7 @@ function withoutWatch(args) {
1343
1400
  }
1344
1401
  return rest;
1345
1402
  }
1346
- async function watching(value, step, stream = process14.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1403
+ async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1347
1404
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1348
1405
  if (!takesControlCodes(stream))
1349
1406
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1351,12 +1408,12 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
1351
1408
  for (let round = 0;round < rounds; round++) {
1352
1409
  const held = [];
1353
1410
  const { log, info } = console;
1354
- const write = process14.stdout.write.bind(process14.stdout);
1411
+ const write = process16.stdout.write.bind(process16.stdout);
1355
1412
  const hold = (...parts) => void held.push(`${format(...parts)}
1356
1413
  `);
1357
1414
  console.log = hold;
1358
1415
  console.info = hold;
1359
- process14.stdout.write = (text) => {
1416
+ process16.stdout.write = (text) => {
1360
1417
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1361
1418
  return true;
1362
1419
  };
@@ -1365,7 +1422,7 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
1365
1422
  } finally {
1366
1423
  console.log = log;
1367
1424
  console.info = info;
1368
- process14.stdout.write = write;
1425
+ process16.stdout.write = write;
1369
1426
  }
1370
1427
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1371
1428
  await sleep(interval);
@@ -1374,8 +1431,8 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
1374
1431
  }
1375
1432
  // ../kit/src/workspace-root.ts
1376
1433
  import { homedir as homedir4 } from "os";
1377
- import { dirname as dirname4, join as join6, resolve as resolve3 } from "path";
1378
- import process15 from "process";
1434
+ import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1435
+ import process17 from "process";
1379
1436
  function expandHome(path, home) {
1380
1437
  if (path === "~")
1381
1438
  return home;
@@ -1385,18 +1442,22 @@ function configured(env, home) {
1385
1442
  const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1386
1443
  return typeof folder === "string" && folder !== "" ? folder : undefined;
1387
1444
  }
1388
- function workspaceRoot({ given, env = process15.env, home = homedir4() } = {}) {
1445
+ function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
1389
1446
  const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1390
- return resolve3(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1447
+ return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1391
1448
  }
1392
1449
  // src/audit.ts
1393
- import { existsSync as existsSync5, readdirSync, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
1450
+ import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync7, statSync as statSync2 } from "fs";
1394
1451
  import { readdir } from "fs/promises";
1395
- import { join as join8, relative, resolve as resolve4 } from "path";
1396
- import process17 from "process";
1452
+ import { join as join9, relative, resolve as resolve5 } from "path";
1453
+ import process19 from "process";
1454
+
1455
+ // src/osv.ts
1456
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
1457
+ import { join as join8 } from "path";
1397
1458
 
1398
1459
  // src/report.ts
1399
- import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
1460
+ import { existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
1400
1461
  import { join as join7 } from "path";
1401
1462
  var UPPER_BOUND = /<\s*(\d[\w.+-]*)/;
1402
1463
  var DEPENDENCY_KINDS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
@@ -1480,7 +1541,7 @@ function reachedFrom(graph, direct, targets) {
1480
1541
  }
1481
1542
  function readManifest(path) {
1482
1543
  try {
1483
- return existsSync4(path) ? JSON.parse(readFileSync4(path, "utf8")) : {};
1544
+ return existsSync4(path) ? JSON.parse(readFileSync5(path, "utf8")) : {};
1484
1545
  } catch {
1485
1546
  return {};
1486
1547
  }
@@ -1510,14 +1571,121 @@ function workspaceFolders(root, children) {
1510
1571
  return patterns.filter((pattern) => typeof pattern === "string").flatMap((pattern) => pattern.endsWith("/*") ? children(pattern.slice(0, -2)).map((name) => join7(pattern.slice(0, -2), name)) : [pattern]);
1511
1572
  }
1512
1573
 
1574
+ // src/osv.ts
1575
+ var OSV = "https://api.osv.dev/v1";
1576
+ var BATCH = 1000;
1577
+ var DETAIL_CONCURRENCY = 8;
1578
+ var TIMEOUT_MS = 20000;
1579
+ var PACKAGE_BLOCK = /^\[\[package\]\]\s*$/m;
1580
+ var FIELD = /^(name|version|source) = (.+)$/gm;
1581
+ var QUOTED = /^"([^"]*)"$/;
1582
+ var LEADING_V = /^v/;
1583
+ function parseComposerLock(text) {
1584
+ const lock = JSON.parse(text);
1585
+ const entry = (prod) => (each) => ({ name: each.name, version: each.version.replace(LEADING_V, ""), prod });
1586
+ return [...(lock.packages ?? []).map(entry(true)), ...(lock["packages-dev"] ?? []).map(entry(false))];
1587
+ }
1588
+ function tomlPackages(text, fromRegistry) {
1589
+ const found = [];
1590
+ for (const block of text.split(PACKAGE_BLOCK).slice(1)) {
1591
+ const fields = new Map;
1592
+ for (const [, key, value] of block.matchAll(FIELD))
1593
+ fields.set(key, QUOTED.exec(value.trim())?.[1] ?? value.trim());
1594
+ const source = fields.get("source");
1595
+ const name = fields.get("name");
1596
+ const version = fields.get("version");
1597
+ if (name !== undefined && version !== undefined && source !== undefined && fromRegistry(source))
1598
+ found.push({ name, version, prod: true });
1599
+ }
1600
+ return found;
1601
+ }
1602
+ function parseCargoLock(text) {
1603
+ return tomlPackages(text, (source) => source.startsWith("registry+"));
1604
+ }
1605
+ function parseUvLock(text) {
1606
+ return tomlPackages(text, (source) => source.includes("registry"));
1607
+ }
1608
+ var ECOSYSTEMS = [
1609
+ { lockfile: "composer.lock", osv: "Packagist", parse: parseComposerLock },
1610
+ { lockfile: "Cargo.lock", osv: "crates.io", parse: parseCargoLock },
1611
+ { lockfile: "uv.lock", osv: "PyPI", parse: parseUvLock }
1612
+ ];
1613
+ function holdsOsvLock(dir) {
1614
+ return ECOSYSTEMS.some((each) => existsSync5(join8(dir, each.lockfile)));
1615
+ }
1616
+ var SEVERITY_NAMES = { LOW: "low", MODERATE: "moderate", MEDIUM: "moderate", HIGH: "high", CRITICAL: "critical" };
1617
+ async function ok2(response) {
1618
+ if (!response.ok)
1619
+ throw new Error(`osv.dev answered ${response.status}`);
1620
+ return response.json();
1621
+ }
1622
+ function rowOf(vuln, name) {
1623
+ const fixes = (vuln.affected ?? []).filter((each) => each.package?.name === name).flatMap((each) => each.ranges ?? []).flatMap((range) => range.events ?? []).map((event) => event.fixed).filter((fixed) => fixed !== undefined);
1624
+ return { id: 0, ghsa: vuln.id, url: `https://osv.dev/vulnerability/${vuln.id}`, title: vuln.summary ?? vuln.id, severity: SEVERITY_NAMES[vuln.database_specific?.severity?.toUpperCase() ?? ""] ?? "moderate", fixed: fixes.length === 0 ? undefined : fixedAt(fixes.map((fix) => `<${fix}`).join(" || ")) };
1625
+ }
1626
+ async function osvFindings(locked, ecosystem, direct, level, ignore, fetcher = fetch) {
1627
+ const hits = new Map;
1628
+ for (let start = 0;start < locked.length; start += BATCH) {
1629
+ const chunk = locked.slice(start, start + BATCH);
1630
+ const queries = chunk.map((each) => ({ package: { name: each.name, ecosystem }, version: each.version }));
1631
+ const answer = await ok2(await fetcher(`${OSV}/querybatch`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ queries }), signal: AbortSignal.timeout(TIMEOUT_MS) }));
1632
+ for (const [index, each] of chunk.entries()) {
1633
+ const ids = (answer.results[index]?.vulns ?? []).map((vuln) => vuln.id).filter((id) => !ignore.includes(id));
1634
+ if (ids.length > 0)
1635
+ hits.set(each, ids);
1636
+ }
1637
+ }
1638
+ const details = new Map;
1639
+ await pool([...new Set([...hits.values()].flat())], DETAIL_CONCURRENCY, async (id) => {
1640
+ details.set(id, await ok2(await fetcher(`${OSV}/vulns/${encodeURIComponent(id)}`, { signal: AbortSignal.timeout(TIMEOUT_MS) })));
1641
+ });
1642
+ const findings = [];
1643
+ let below = 0;
1644
+ for (const [each, ids] of hits) {
1645
+ const rows = ids.map((id) => rowOf(details.get(id), each.name));
1646
+ const advisories = rows.filter((row) => severityRank(row.severity) >= severityRank(level));
1647
+ below += rows.length - advisories.length;
1648
+ if (advisories.length === 0)
1649
+ continue;
1650
+ const fixes = advisories.map((row) => row.fixed);
1651
+ findings.push({
1652
+ package: each.name,
1653
+ severity: advisories.reduce((worst, row) => severityRank(row.severity) > severityRank(worst) ? row.severity : worst, advisories[0].severity),
1654
+ advisories,
1655
+ scope: each.prod ? "prod" : "dev",
1656
+ direct: direct.has(each.name),
1657
+ via: [],
1658
+ fix: fixes.includes(undefined) ? undefined : fixes.reduce((highest, fix) => Bun.semver.order(fix, highest) > 0 ? fix : highest)
1659
+ });
1660
+ }
1661
+ return { findings: findings.toSorted((a, b) => severityRank(b.severity) - severityRank(a.severity) || Number(b.scope === "prod") - Number(a.scope === "prod") || a.package.localeCompare(b.package)), below };
1662
+ }
1663
+ function manifestNames(dir) {
1664
+ try {
1665
+ const manifest = JSON.parse(readFileSync6(join8(dir, "composer.json"), "utf8"));
1666
+ return new Set([...Object.keys(manifest.require ?? {}), ...Object.keys(manifest["require-dev"] ?? {})]);
1667
+ } catch {
1668
+ return new Set;
1669
+ }
1670
+ }
1671
+ async function osvAudit(dir, level, ignore, fetcher = fetch) {
1672
+ const all = { findings: [], below: 0 };
1673
+ for (const each of ECOSYSTEMS.filter((each) => existsSync5(join8(dir, each.lockfile)))) {
1674
+ const done = await osvFindings(each.parse(readFileSync6(join8(dir, each.lockfile), "utf8")), each.osv, each.lockfile === "composer.lock" ? manifestNames(dir) : new Set, level, ignore, fetcher);
1675
+ all.findings.push(...done.findings);
1676
+ all.below += done.below;
1677
+ }
1678
+ return all;
1679
+ }
1680
+
1513
1681
  // src/audit.ts
1514
- var USAGE = `audit [options] [root]: the known vulnerabilities of the Bun repositories under root (the current folder by default), one table per repository
1682
+ var USAGE = `audit [options] [root]: the known vulnerabilities of the Bun, Composer, Cargo and uv repositories under root (the current folder by default), one table per repository
1515
1683
 
1516
1684
  Each package with an advisory is one row: its worst severity, how many advisories, whether a production dependency needs it (prod) or only a development one (dev), whether the repository asks for it itself (direct) or a dependency does (the row then says via and the direct dependencies leading to it, upgrading one of which is what fixes it), and the version that fixes every advisory at once, "-" when an advisory names none. The worst and the production ones come first.
1517
- Advisories under --level (moderate by default) are counted under the table, and what \`bun audit\` warned about, such as a private registry that would not audit its packages, is repeated there. It runs \`bun audit --json\` in each repository holding a bun.lock, which reaches the registry; the walk goes three levels deep, stops at a bun.lock and skips node_modules and hidden folders.
1685
+ Advisories under --level (moderate by default) are counted under the table, and what \`bun audit\` warned about, such as a private registry that would not audit its packages, is repeated there. It runs \`bun audit --json\` in each repository holding a bun.lock, which reaches the registry, and asks osv.dev about the packages of a composer.lock, Cargo.lock or uv.lock (a severity the source leaves out reads as moderate, and only composer's manifest tells direct from pulled in); the walk goes three levels deep, stops at a lockfile and skips node_modules and hidden folders.
1518
1686
 
1519
1687
  Reach for it to sweep many repositories at once; \`pkg audit\` vets the one repository in a folder (package age, install scripts, licences) as well as its advisories, and shares --level, --prod and --ignore.`;
1520
- var EXITS = [[0, "no repository has an advisory at the level asked"], [1, "one has"], [2, "a repository's audit failed, no bun.lock sits under root, a usage error or a root that is no folder"]];
1688
+ var EXITS = [[0, "no repository has an advisory at the level asked"], [1, "one has"], [2, "a repository's audit failed, no lockfile sits under root, a usage error or a root that is no folder"]];
1521
1689
  var OPTIONS = {
1522
1690
  level: { type: "string", choices: SEVERITIES, default: "moderate", description: "only the advisories at least this severe: low, moderate, high or critical" },
1523
1691
  prod: { type: "boolean", description: "only the packages a production dependency needs" },
@@ -1532,8 +1700,11 @@ var VIA_SHOWN = 2;
1532
1700
  function countAdvisories(findings) {
1533
1701
  return findings.reduce((sum, found) => sum + found.advisories.length, 0);
1534
1702
  }
1703
+ function holdsBunLock(dir) {
1704
+ return existsSync6(join9(dir, "bun.lock")) || existsSync6(join9(dir, "bun.lockb"));
1705
+ }
1535
1706
  function holdsLock(dir) {
1536
- return existsSync5(join8(dir, "bun.lock")) || existsSync5(join8(dir, "bun.lockb"));
1707
+ return holdsBunLock(dir) || holdsOsvLock(dir);
1537
1708
  }
1538
1709
  async function findRepos(root) {
1539
1710
  if (holdsLock(root))
@@ -1549,7 +1720,7 @@ async function findRepos(root) {
1549
1720
  for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
1550
1721
  if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith("."))
1551
1722
  continue;
1552
- const path = join8(dir, entry.name);
1723
+ const path = join9(dir, entry.name);
1553
1724
  if (holdsLock(path))
1554
1725
  found.push(path);
1555
1726
  else if (depth < MAX_DEPTH)
@@ -1562,13 +1733,24 @@ async function findRepos(root) {
1562
1733
  function children(root) {
1563
1734
  return (folder) => {
1564
1735
  try {
1565
- return readdirSync(join8(root, folder), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
1736
+ return readdirSync(join9(root, folder), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
1566
1737
  } catch {
1567
1738
  return [];
1568
1739
  }
1569
1740
  };
1570
1741
  }
1571
1742
  async function audited(path, shown, level, ignore) {
1743
+ const bun = holdsBunLock(path) ? await bunAudited(path, shown, level, ignore) : { repo: shown, path, findings: [], below: 0, warnings: [], error: undefined };
1744
+ if (bun.error !== undefined || !holdsOsvLock(path))
1745
+ return bun;
1746
+ try {
1747
+ const osv = await osvAudit(path, level, ignore);
1748
+ return { ...bun, findings: [...bun.findings, ...osv.findings], below: bun.below + osv.below };
1749
+ } catch (error) {
1750
+ return { ...bun, error: `osv.dev: ${error instanceof Error ? error.message : String(error)}` };
1751
+ }
1752
+ }
1753
+ async function bunAudited(path, shown, level, ignore) {
1572
1754
  const [all, production] = await Promise.all([
1573
1755
  runCommand(["bun", "audit", "--json"], { cwd: path, timeoutMs: AUDIT_MS }),
1574
1756
  runCommand(["bun", "audit", "--json", "--prod"], { cwd: path, timeoutMs: AUDIT_MS })
@@ -1585,7 +1767,7 @@ async function audited(path, shown, level, ignore) {
1585
1767
  }
1586
1768
  function lockText(path) {
1587
1769
  try {
1588
- return readFileSync5(join8(path, "bun.lock"), "utf8");
1770
+ return readFileSync7(join9(path, "bun.lock"), "utf8");
1589
1771
  } catch {
1590
1772
  return "";
1591
1773
  }
@@ -1605,7 +1787,7 @@ function failure(ran) {
1605
1787
  `).at(-1) ?? `exit ${ran.code}`;
1606
1788
  }
1607
1789
  function tint(severity) {
1608
- const colors = paint(process17.stdout);
1790
+ const colors = paint(process19.stdout);
1609
1791
  if (severity === "critical" || severity === "high")
1610
1792
  return colors.red;
1611
1793
  return severity === "moderate" ? colors.yellow : colors.dim;
@@ -1622,13 +1804,13 @@ function rows(findings) {
1622
1804
  }
1623
1805
  async function audit(args) {
1624
1806
  const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[root]"], exits: EXITS, replaces: "a bun audit run in each repository and a read of every advisory to find what is worth fixing", examples: ["audit", "audit ~/Workspace --level high --prod"] });
1625
- const root = resolve4(positionals[0] ?? ".");
1626
- if (!existsSync5(root) || !statSync2(root).isDirectory())
1807
+ const root = resolve5(positionals[0] ?? ".");
1808
+ if (!existsSync6(root) || !statSync2(root).isDirectory())
1627
1809
  fail(`no folder ${root}`);
1628
1810
  const level = oneOf(values.level, "level", SEVERITIES);
1629
1811
  const paths = await findRepos(root);
1630
1812
  if (paths.length === 0)
1631
- fail(`no bun.lock under ${root}`);
1813
+ fail(`no bun.lock, composer.lock, Cargo.lock or uv.lock under ${root}`);
1632
1814
  const audits = await pool(paths, configuredNumber("audit", "concurrency", CONCURRENCY), async (path) => audited(path, relative(root, path) || ".", level, values.ignore ?? []));
1633
1815
  const kept = audits.map((each) => ({ ...each, findings: values.prod === true ? each.findings.filter((found) => found.scope === "prod") : each.findings }));
1634
1816
  if (values.json === true)
@@ -1640,8 +1822,8 @@ async function audit(args) {
1640
1822
  return kept.some((each) => each.findings.length > 0) ? 1 : 0;
1641
1823
  }
1642
1824
  function show(audits, total) {
1643
- const label = role("label", process17.stdout);
1644
- const path = role("path", process17.stdout);
1825
+ const label = role("label", process19.stdout);
1826
+ const path = role("path", process19.stdout);
1645
1827
  const flagged = audits.filter((each) => each.error !== undefined || each.findings.length > 0);
1646
1828
  if (flagged.length === 0) {
1647
1829
  console.log(label(`no advisory in ${total} ${total === 1 ? "repository" : "repositories"}`));
@@ -1661,4 +1843,4 @@ function show(audits, total) {
1661
1843
  }
1662
1844
 
1663
1845
  // src/audit-cli.ts
1664
- process18.exitCode = await runMain({ name: "audit", run: audit });
1846
+ process20.exitCode = await runMain({ name: "audit", run: audit });