@kaynooo/cli-dl 0.0.1 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +10 -2
  2. package/dist/cli.js +1095 -215
  3. package/package.json +6 -6
package/dist/cli.js CHANGED
@@ -29,8 +29,8 @@ var __esm = (fn, res, err) => () => {
29
29
  // ../kit/src/advisory.ts
30
30
  var init_advisory = () => {};
31
31
 
32
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
33
- function ko(t, e, r = "...") {
32
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
33
+ function Ao(t, e, r = "...") {
34
34
  let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
35
35
  if (t.length <= e)
36
36
  return t;
@@ -41,18 +41,18 @@ function ko(t, e, r = "...") {
41
41
  c = c.trimEnd();
42
42
  return s ? (c + n).slice(0, l) : c + n;
43
43
  }
44
- var N, Nt, Y, be, z;
45
- var init_chunk_rxztfxgv = __esm(() => {
44
+ var N, Nt, Y, be, W;
45
+ var init_chunk_rkhsft4a = __esm(() => {
46
46
  N = new Map;
47
47
  Nt = /\s+\S*$/;
48
48
  Y = /\s/;
49
49
  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));
50
- z = new Map;
50
+ W = new Map;
51
51
  });
52
52
 
53
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
53
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
54
54
  var init_text = __esm(() => {
55
- init_chunk_rxztfxgv();
55
+ init_chunk_rkhsft4a();
56
56
  });
57
57
 
58
58
  // ../kit/src/mode.ts
@@ -76,7 +76,7 @@ var init_mode = __esm(() => {
76
76
  AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
77
77
  });
78
78
 
79
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
79
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
80
80
  function b(r) {
81
81
  let e = r.startsWith("#") ? r.slice(1) : r;
82
82
  if (!G2.test(e))
@@ -100,7 +100,7 @@ function f(r, e = []) {
100
100
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
101
101
  let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
102
102
  return new Proxy(c, { get(t, i) {
103
- let a = B2[i];
103
+ let a = B[i];
104
104
  if (Array.isArray(a)) {
105
105
  let s = g.get(i);
106
106
  if (s === undefined)
@@ -123,10 +123,10 @@ function f(r, e = []) {
123
123
  function Fe(r = {}) {
124
124
  return f(r);
125
125
  }
126
- var G2, B2, h, o;
126
+ var G2, B, h, o;
127
127
  var init_chunk_x450vn3m = __esm(() => {
128
128
  G2 = /^[a-f0-9]+$/i;
129
- 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") => {
129
+ 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") => {
130
130
  let [l, n, c] = b(r);
131
131
  return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
132
132
  }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
@@ -134,7 +134,7 @@ var init_chunk_x450vn3m = __esm(() => {
134
134
  o = Fe();
135
135
  });
136
136
 
137
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
137
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
138
138
  var init_colors = __esm(() => {
139
139
  init_chunk_x450vn3m();
140
140
  });
@@ -159,11 +159,14 @@ var init_config = __esm(() => {
159
159
 
160
160
  // ../kit/src/user-config.ts
161
161
  import { homedir } from "os";
162
- import { join as join2 } from "path";
162
+ import { isAbsolute, join as join2 } from "path";
163
163
  import process4 from "process";
164
+ function xdgFolder(value, fallback) {
165
+ return value !== undefined && isAbsolute(value) ? value : fallback;
166
+ }
164
167
  function configBase(where = {}) {
165
168
  const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
166
- return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
169
+ return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
167
170
  }
168
171
  function userConfigPath(bin, where = {}) {
169
172
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
@@ -409,6 +412,9 @@ function marked(mark, text, stream, detail, env = process6.env) {
409
412
  }
410
413
  return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
411
414
  }
415
+ function warn(text, detail) {
416
+ console.error(marked("warn", text, process6.stderr, detail));
417
+ }
412
418
  var MARK_WORDS, STATUS_WORDS, STATUS_OF;
413
419
  var init_style = __esm(() => {
414
420
  init_colors();
@@ -458,7 +464,7 @@ function formatAge(date, now = Date.now()) {
458
464
  return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
459
465
  }
460
466
  function truncate(text, width) {
461
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
467
+ return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
462
468
  }
463
469
  function textWidth(text) {
464
470
  return Bun.stringWidth(text);
@@ -521,7 +527,27 @@ var init_format = __esm(() => {
521
527
  // ../kit/src/help.ts
522
528
  import process8 from "process";
523
529
  function usageLine(usage, colors = paint(process8.stdout)) {
524
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
530
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
531
+ `);
532
+ const blank = lines.indexOf("");
533
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
534
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
535
+ const colon = synopses[0].indexOf(": ");
536
+ const inline = synopses[0].slice(colon + 2);
537
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
538
+ if (colon !== -1)
539
+ synopses[0] = synopses[0].slice(0, colon);
540
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
541
+ `)}`;
542
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
543
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
544
+ return [head, ...lead, ...rest].join(`
545
+ `);
546
+ }
547
+ function prose(line, colors) {
548
+ if (colors.cyan("x") === "x")
549
+ return line;
550
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
525
551
  }
526
552
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
527
553
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -570,16 +596,25 @@ function optionRows(options, colors = paint(process8.stdout)) {
570
596
  const width = Math.max(0, ...rows.map((row) => row.width));
571
597
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
572
598
  }
573
- var OPTIONAL, USAGE_PREFIX, FULL_STOP, MAX_INLINE_CHOICES = 24;
599
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
574
600
  var init_help = __esm(() => {
575
601
  init_mode();
576
602
  init_style();
577
603
  OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
578
604
  USAGE_PREFIX = /^usage:\s*/i;
579
605
  FULL_STOP = /\.$/;
606
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
580
607
  });
581
608
 
582
609
  // ../kit/src/text.ts
610
+ function escapeControls(text) {
611
+ return text.replace(CONTROLS, (char) => {
612
+ const code = char.charCodeAt(0);
613
+ if (code === 127)
614
+ return "^?";
615
+ return code < 128 ? `^${String.fromCharCode(code + 64)}` : `M-^${String.fromCharCode(code - 64)}`;
616
+ });
617
+ }
583
618
  function distance(a, b) {
584
619
  const left = [...a];
585
620
  const right = [...b];
@@ -605,7 +640,10 @@ function closest(name, names) {
605
640
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
606
641
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
607
642
  }
608
- var init_text2 = () => {};
643
+ var CONTROLS;
644
+ var init_text2 = __esm(() => {
645
+ CONTROLS = /[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;
646
+ });
609
647
 
610
648
  // ../kit/src/input.ts
611
649
  var init_input = __esm(() => {
@@ -803,7 +841,7 @@ function nearestOption(message, options, allowNegative) {
803
841
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
804
842
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
805
843
  }
806
- var DASHES, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
844
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
807
845
  var init_args = __esm(() => {
808
846
  init_format();
809
847
  init_help();
@@ -811,14 +849,21 @@ var init_args = __esm(() => {
811
849
  init_help();
812
850
  init_input();
813
851
  DASHES = /^-+/;
852
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
814
853
  Exit = class Exit extends Error {
815
854
  code;
816
855
  hint;
856
+ [EXIT] = true;
817
857
  constructor(message, code, hint) {
818
858
  super(message);
819
859
  this.code = code;
820
860
  this.hint = hint;
821
861
  }
862
+ static [Symbol.hasInstance](value) {
863
+ if (this !== Exit)
864
+ return Function.prototype[Symbol.hasInstance].call(this, value);
865
+ return typeof value === "object" && value !== null && value[EXIT] === true;
866
+ }
822
867
  };
823
868
  UsageError = class UsageError extends Exit {
824
869
  constructor(message, hint) {
@@ -873,7 +918,31 @@ var init_chart = __esm(() => {
873
918
  });
874
919
 
875
920
  // ../kit/src/process.ts
921
+ import { readFileSync as readFileSync3 } from "fs";
922
+ import { constants } from "os";
876
923
  import process11 from "process";
924
+ function exitCodeOf(code, signal) {
925
+ if (code !== null)
926
+ return code;
927
+ if (typeof signal === "number")
928
+ return 128 + signal;
929
+ return signal === null ? 129 : 128 + constants.signals[signal];
930
+ }
931
+ function groupsOf(pid) {
932
+ try {
933
+ const stat = readFileSync3(`/proc/${pid}/stat`, "utf8");
934
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
935
+ return { group: Number(fields[2]), foreground: Number(fields[5]) };
936
+ } catch {
937
+ return;
938
+ }
939
+ }
940
+ function heardTheTerminal(child) {
941
+ if (child.pid === undefined)
942
+ return false;
943
+ const own = groupsOf("self");
944
+ return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
945
+ }
877
946
  function holdSignals(cleanup) {
878
947
  let received;
879
948
  let child;
@@ -892,7 +961,8 @@ function holdSignals(cleanup) {
892
961
  function onSignal(signal) {
893
962
  received = signal;
894
963
  if (child !== undefined) {
895
- child.kill(signal);
964
+ if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
965
+ child.kill(signal);
896
966
  return;
897
967
  }
898
968
  if (cleanup === undefined)
@@ -905,9 +975,99 @@ function holdSignals(cleanup) {
905
975
  process11.on(signal, onSignal);
906
976
  return held;
907
977
  }
908
- var SIGNALS;
978
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
979
+ const chunks = [];
980
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
981
+ 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 } : {} });
982
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
983
+ const timers = [];
984
+ const killGroup = (killing) => {
985
+ if (state.done)
986
+ return;
987
+ try {
988
+ if (grouped)
989
+ process11.kill(-proc.pid, killing);
990
+ else
991
+ proc.kill(killing);
992
+ } catch {}
993
+ };
994
+ const stop = () => {
995
+ killGroup("SIGTERM");
996
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
997
+ };
998
+ const onAbort = () => stop();
999
+ if (timeoutMs !== undefined) {
1000
+ timers.push(setTimeout(() => {
1001
+ state.timedOut = true;
1002
+ stop();
1003
+ }, timeoutMs));
1004
+ }
1005
+ if (signal?.aborted === true)
1006
+ onAbort();
1007
+ else
1008
+ signal?.addEventListener("abort", onAbort, { once: true });
1009
+ onStart?.({ kill: (killing) => killGroup(killing) });
1010
+ const drain = async (stream, name) => {
1011
+ for await (const data of stream) {
1012
+ if (state.failure !== undefined)
1013
+ continue;
1014
+ try {
1015
+ onChunk?.({ stream: name, data });
1016
+ } catch (error) {
1017
+ state.failure = error;
1018
+ stop();
1019
+ continue;
1020
+ }
1021
+ if (state.truncated)
1022
+ continue;
1023
+ let kept = data;
1024
+ if (state.kept + data.length > maxBytes) {
1025
+ let cut = maxBytes - state.kept;
1026
+ while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
1027
+ cut--;
1028
+ kept = data.subarray(0, cut);
1029
+ state.truncated = true;
1030
+ }
1031
+ state.kept += kept.length;
1032
+ if (kept.length > 0)
1033
+ chunks.push({ stream: name, data: kept });
1034
+ }
1035
+ };
1036
+ try {
1037
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
1038
+ await proc.exited;
1039
+ } finally {
1040
+ state.done = true;
1041
+ for (const timer of timers)
1042
+ clearTimeout(timer);
1043
+ signal?.removeEventListener("abort", onAbort);
1044
+ }
1045
+ if (state.failure !== undefined)
1046
+ throw state.failure;
1047
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
1048
+ let output;
1049
+ let text;
1050
+ let stdout;
1051
+ return {
1052
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
1053
+ chunks,
1054
+ timedOut: state.timedOut,
1055
+ truncated: state.truncated,
1056
+ get output() {
1057
+ return output ??= joined();
1058
+ },
1059
+ get text() {
1060
+ return text ??= (output ??= joined()).toString();
1061
+ },
1062
+ get stdout() {
1063
+ return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
1064
+ }
1065
+ };
1066
+ }
1067
+ var KILL_GRACE_MS = 2000, SIGNALS, GROUP_SIGNALS;
909
1068
  var init_process = __esm(() => {
910
1069
  SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1070
+ GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
911
1071
  });
912
1072
 
913
1073
  // ../kit/src/progress.ts
@@ -919,10 +1079,14 @@ function liveRegion(render, stream = process12.stderr, env = process12.env) {
919
1079
  }, print: (text) => void stream.write(`${text}
920
1080
  `), stop: () => {
921
1081
  return;
1082
+ }, pause: () => () => {
1083
+ return;
922
1084
  } };
923
1085
  const write = stream.write.bind(stream);
924
1086
  let frame = 0;
925
1087
  let drawn = false;
1088
+ let paused = false;
1089
+ let stopped = false;
926
1090
  const columns = () => {
927
1091
  const now = stream.getWindowSize?.()[0] ?? stream.columns;
928
1092
  return now === undefined || now === 0 ? 80 : now;
@@ -933,6 +1097,8 @@ function liveRegion(render, stream = process12.stderr, env = process12.env) {
933
1097
  drawn = false;
934
1098
  };
935
1099
  const draw = () => {
1100
+ if (paused)
1101
+ return;
936
1102
  const width = columns() - 1;
937
1103
  const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
938
1104
  const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
@@ -944,16 +1110,17 @@ function liveRegion(render, stream = process12.stderr, env = process12.env) {
944
1110
  `)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
945
1111
  drawn = true;
946
1112
  };
947
- const timer = setInterval(draw, FRAME_MS);
1113
+ let timer = setInterval(draw, FRAME_MS);
948
1114
  stream.on?.("resize", draw);
949
- const restore = interceptOutput(clear);
950
- const release = swallowInput();
1115
+ let restore = interceptOutput(clear);
1116
+ let release = swallowInput();
951
1117
  const onExit = () => {
952
1118
  clear();
953
1119
  release();
954
1120
  };
955
1121
  const signals = holdSignals(stop);
956
1122
  function stop() {
1123
+ stopped = true;
957
1124
  clearInterval(timer);
958
1125
  stream.off?.("resize", draw);
959
1126
  clear();
@@ -962,6 +1129,29 @@ function liveRegion(render, stream = process12.stderr, env = process12.env) {
962
1129
  process12.off("exit", onExit);
963
1130
  signals.release();
964
1131
  }
1132
+ function pause() {
1133
+ if (paused || stopped)
1134
+ return () => {
1135
+ return;
1136
+ };
1137
+ paused = true;
1138
+ clearInterval(timer);
1139
+ stream.off?.("resize", draw);
1140
+ clear();
1141
+ restore();
1142
+ release();
1143
+ return () => {
1144
+ if (!paused || stopped)
1145
+ return;
1146
+ paused = false;
1147
+ timer = setInterval(draw, FRAME_MS);
1148
+ timer.unref();
1149
+ stream.on?.("resize", draw);
1150
+ restore = interceptOutput(clear);
1151
+ release = swallowInput();
1152
+ draw();
1153
+ };
1154
+ }
965
1155
  timer.unref();
966
1156
  process12.on("exit", onExit);
967
1157
  return {
@@ -972,7 +1162,8 @@ function liveRegion(render, stream = process12.stderr, env = process12.env) {
972
1162
  `);
973
1163
  draw();
974
1164
  },
975
- stop
1165
+ stop,
1166
+ pause
976
1167
  };
977
1168
  }
978
1169
  function progressLine(stream = process12.stderr, env = process12.env) {
@@ -997,6 +1188,7 @@ function progressLine(stream = process12.stderr, env = process12.env) {
997
1188
  }
998
1189
  },
999
1190
  stop: region.stop,
1191
+ pause: region.pause,
1000
1192
  done: (text) => end(marked("ok", text, stream, formatDuration(performance.now() - begun), env)),
1001
1193
  failed: (text) => end(marked("problem", text, stream, undefined, env))
1002
1194
  };
@@ -1100,9 +1292,48 @@ var init_progress = __esm(() => {
1100
1292
  });
1101
1293
 
1102
1294
  // ../kit/src/tool.ts
1295
+ import process13 from "process";
1296
+ function cwdGone() {
1297
+ try {
1298
+ process13.cwd();
1299
+ return false;
1300
+ } catch {
1301
+ return true;
1302
+ }
1303
+ }
1304
+ function spawnFailure(command, error) {
1305
+ const gone = cwdGone();
1306
+ const missing = !gone && error?.code === "ENOENT";
1307
+ return new SpawnError(`${command}: ${error instanceof Error ? error.message : String(error)}${gone ? " (the working directory was removed)" : ""}`, missing);
1308
+ }
1309
+ async function runTool(label, argv, { timeoutMs, cwd, onStart, env } = {}) {
1310
+ let ran;
1311
+ try {
1312
+ ran = await runCommand(argv, { env: { ...process13.env, ...env }, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
1313
+ } catch (error) {
1314
+ throw spawnFailure(label, error);
1315
+ }
1316
+ if (ran.timedOut)
1317
+ throw new Error(`${label}: no answer in ${formatDuration(timeoutMs ?? 0)}`);
1318
+ const decoders = { stdout: new TextDecoder, stderr: new TextDecoder };
1319
+ const streams = { stdout: "", stderr: "" };
1320
+ for (const { stream, data } of ran.chunks)
1321
+ streams[stream] += decoders[stream].decode(data, { stream: true });
1322
+ streams.stdout += decoders.stdout.decode();
1323
+ streams.stderr += decoders.stderr.decode();
1324
+ return { code: ran.code, ...streams };
1325
+ }
1326
+ var SpawnError;
1103
1327
  var init_tool = __esm(() => {
1104
1328
  init_format();
1105
1329
  init_process();
1330
+ SpawnError = class SpawnError extends Error {
1331
+ missing;
1332
+ constructor(message, missing) {
1333
+ super(message);
1334
+ this.missing = missing;
1335
+ }
1336
+ };
1106
1337
  });
1107
1338
 
1108
1339
  // ../kit/src/ci.ts
@@ -1114,6 +1345,46 @@ var init_ci = __esm(() => {
1114
1345
  init_tool();
1115
1346
  });
1116
1347
 
1348
+ // ../kit/src/askpass.ts
1349
+ import process14 from "process";
1350
+ async function askpassClient(argv) {
1351
+ const socketPath = process14.env[SOCKET_VARIABLE];
1352
+ if (socketPath === undefined)
1353
+ return;
1354
+ const request = { prompt: argv[0] ?? "", ...process14.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1355
+ const { promise, resolve } = Promise.withResolvers();
1356
+ let received = "";
1357
+ try {
1358
+ await Bun.connect({
1359
+ unix: socketPath,
1360
+ socket: {
1361
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1362
+ `),
1363
+ data: (_, chunk) => {
1364
+ received += chunk.toString();
1365
+ },
1366
+ close: () => resolve(received),
1367
+ error: () => resolve("")
1368
+ }
1369
+ });
1370
+ } catch {
1371
+ return 1;
1372
+ }
1373
+ const reply = await promise;
1374
+ if (reply === "")
1375
+ return 1;
1376
+ const { answer } = JSON.parse(reply);
1377
+ if (request.notice === true)
1378
+ return 0;
1379
+ if (answer === undefined)
1380
+ return 1;
1381
+ process14.stdout.write(`${answer}
1382
+ `);
1383
+ return 0;
1384
+ }
1385
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1386
+ var init_askpass = () => {};
1387
+
1117
1388
  // ../kit/src/completions.ts
1118
1389
  function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1119
1390
  if (shell === "fish")
@@ -1175,16 +1446,16 @@ var init_completions = __esm(() => {
1175
1446
  });
1176
1447
 
1177
1448
  // ../kit/src/notify.ts
1178
- import process13 from "process";
1449
+ import process15 from "process";
1179
1450
  function base64(text) {
1180
1451
  return Buffer.from(text).toString("base64");
1181
1452
  }
1182
- function notification(title, body, env = process13.env) {
1183
- const id = `kit${process13.pid}`;
1453
+ function notification(title, body, env = process15.env) {
1454
+ const id = `kit${process15.pid}`;
1184
1455
  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\\`];
1185
1456
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1186
1457
  }
1187
- function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1458
+ function notifyEnd(command, code, ms, { stream = process15.stderr, env = process15.env } = {}) {
1188
1459
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1189
1460
  return;
1190
1461
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
@@ -1198,25 +1469,25 @@ var init_notify = __esm(() => {
1198
1469
  // ../kit/src/logs.ts
1199
1470
  var DAY_MS, CLI_FOLDER = "kaynooo-cli";
1200
1471
  var init_logs = __esm(() => {
1472
+ init_user_config();
1201
1473
  DAY_MS = 24 * 60 * 60 * 1000;
1202
1474
  });
1203
1475
 
1204
1476
  // ../kit/src/usage.ts
1205
1477
  import { appendFileSync, mkdirSync } from "fs";
1206
1478
  import { homedir as homedir3 } from "os";
1207
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1208
- import process14 from "process";
1479
+ import { dirname as dirname2, join as join4 } from "path";
1480
+ import process16 from "process";
1209
1481
  function noteUsageError(message) {
1210
1482
  usageError = message;
1211
1483
  }
1212
- function stateHome(env = process14.env) {
1213
- const dir = env.XDG_STATE_HOME;
1214
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1484
+ function stateHome(env = process16.env) {
1485
+ return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
1215
1486
  }
1216
- function usagePath(env = process14.env) {
1487
+ function usagePath(env = process16.env) {
1217
1488
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1218
1489
  }
1219
- function usageRecorded(env = process14.env) {
1490
+ function usageRecorded(env = process16.env) {
1220
1491
  const off = env.KAYNOOO_CLI_NO_USAGE;
1221
1492
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1222
1493
  }
@@ -1225,12 +1496,12 @@ function flagNames(argv) {
1225
1496
  const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1226
1497
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1227
1498
  }
1228
- function usageEntry(bin, command, argv, code, now = new Date) {
1499
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1229
1500
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1230
1501
  usageError = undefined;
1231
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1502
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1232
1503
  }
1233
- function recordUsage(entry, env = process14.env) {
1504
+ function recordUsage(entry, env = process16.env) {
1234
1505
  if (!usageRecorded(env))
1235
1506
  return;
1236
1507
  try {
@@ -1243,14 +1514,15 @@ function recordUsage(entry, env = process14.env) {
1243
1514
  var UNKNOWN_OPTION2, FLAG_NAME, LONGEST_NAME = 40, usageError;
1244
1515
  var init_usage = __esm(() => {
1245
1516
  init_logs();
1517
+ init_user_config();
1246
1518
  UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1247
1519
  FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1248
1520
  });
1249
1521
 
1250
1522
  // ../kit/src/cli.ts
1251
- import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
1523
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
1252
1524
  import { dirname as dirname3, join as join5 } from "path";
1253
- import process15 from "process";
1525
+ import process17 from "process";
1254
1526
  async function commandRows(all, colors) {
1255
1527
  const commands = shown(all);
1256
1528
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -1285,6 +1557,10 @@ function takeOutputFlags(argv) {
1285
1557
  async function resolveSummary(summary) {
1286
1558
  return typeof summary === "string" ? summary : summary();
1287
1559
  }
1560
+ function lookup({ commands, aliases }, word) {
1561
+ const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
1562
+ return Object.hasOwn(commands, name) ? commands[name] : undefined;
1563
+ }
1288
1564
  function scopeOf(commands, extra, aliases) {
1289
1565
  return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
1290
1566
  }
@@ -1324,8 +1600,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1324
1600
  `);
1325
1601
  }
1326
1602
  function printError(prefix, message, hint, cause) {
1327
- const colors = paint(process15.stderr);
1328
- const styled = takesControlCodes(process15.stderr);
1603
+ const colors = paint(process17.stderr);
1604
+ const styled = takesControlCodes(process17.stderr);
1329
1605
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1330
1606
  const under = (label, text, tint) => text === undefined ? "" : `
1331
1607
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1368,23 +1644,23 @@ async function dispatch(level, typed, { version, redact }) {
1368
1644
  }
1369
1645
  }
1370
1646
  if (name === undefined && level.path.length > 1) {
1371
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
1647
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stderr));
1372
1648
  return 2;
1373
1649
  }
1374
1650
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1375
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
1651
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stdout));
1376
1652
  return 0;
1377
1653
  }
1378
1654
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
1379
1655
  console.log(version);
1380
1656
  return 0;
1381
1657
  }
1382
- let command = level.commands[level.aliases?.[name] ?? name];
1658
+ let command = lookup(level, name);
1383
1659
  let rest = args;
1384
1660
  let ran = name;
1385
1661
  if (command === undefined && level.lazy.length > 0) {
1386
1662
  level = await expand(level, [...level.path.slice(1), ...argv]);
1387
- command = level.commands[level.aliases?.[name] ?? name];
1663
+ command = lookup(level, name);
1388
1664
  }
1389
1665
  if (command === undefined && level.defaultCommand !== undefined) {
1390
1666
  command = level.commands[level.defaultCommand];
@@ -1462,18 +1738,19 @@ async function leafCandidates(run, words) {
1462
1738
  async function candidates(scope, defaultCommand, words, before = []) {
1463
1739
  const [word = "", ...rest] = words;
1464
1740
  const listing = rest.length === 0 && !word.startsWith("-");
1465
- let { commands, aliases } = scope;
1466
- let command = commands[aliases?.[word] ?? word];
1741
+ let { commands } = scope;
1742
+ let command = lookup(scope, word);
1467
1743
  if (listing || command === undefined) {
1468
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
1469
- command = commands[aliases?.[word] ?? word];
1744
+ const expanded = await expand(scope, [...before, ...words]);
1745
+ commands = expanded.commands;
1746
+ command = lookup(expanded, word);
1470
1747
  }
1471
1748
  if (listing) {
1472
1749
  const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1473
1750
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1474
1751
  const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1475
1752
  const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1476
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1753
+ return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
1477
1754
  }
1478
1755
  if (command === undefined) {
1479
1756
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
@@ -1505,7 +1782,7 @@ function packageVersion(entry = Bun.main) {
1505
1782
  } catch {}
1506
1783
  for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1507
1784
  try {
1508
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1785
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1509
1786
  if (typeof version === "string")
1510
1787
  return version;
1511
1788
  } catch {}
@@ -1515,6 +1792,9 @@ function packageVersion(entry = Bun.main) {
1515
1792
  }
1516
1793
  async function runCli(cli, argv = scriptArgs()) {
1517
1794
  const version = cli.version ?? packageVersion();
1795
+ const answered = await askpassClient(argv);
1796
+ if (answered !== undefined)
1797
+ return answered;
1518
1798
  if (argv[0] === COMPLETE)
1519
1799
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1520
1800
  if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
@@ -1525,7 +1805,7 @@ async function runCli(cli, argv = scriptArgs()) {
1525
1805
  notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1526
1806
  if (cli.usage !== false) {
1527
1807
  try {
1528
- recordUsage(usageEntry(cli.name, command, argv, code));
1808
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
1529
1809
  } catch {}
1530
1810
  }
1531
1811
  return code;
@@ -1534,8 +1814,7 @@ function commandPath(scope, argv) {
1534
1814
  const path = [];
1535
1815
  let level = scope;
1536
1816
  for (const word of argv.filter((each) => !each.startsWith("-"))) {
1537
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1538
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1817
+ const command = lookup(level, word);
1539
1818
  if (command === undefined)
1540
1819
  break;
1541
1820
  path.push(word);
@@ -1549,6 +1828,7 @@ var LEVEL_OPTIONS, TOP_OPTIONS, COMPLETE = "__complete", FILES = "__files__", CO
1549
1828
  var init_cli = __esm(() => {
1550
1829
  init_args();
1551
1830
  init_argv();
1831
+ init_askpass();
1552
1832
  init_completions();
1553
1833
  init_notify();
1554
1834
  init_style();
@@ -1594,9 +1874,10 @@ var init_report = __esm(() => {
1594
1874
  });
1595
1875
 
1596
1876
  // ../kit/src/secrets.ts
1597
- var SECRET_WORDS;
1877
+ var SECRET_WORDS, NOT_PASSWORDS;
1598
1878
  var init_secrets = __esm(() => {
1599
1879
  SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1880
+ NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1600
1881
  });
1601
1882
 
1602
1883
  // ../kit/src/sessions.ts
@@ -1612,8 +1893,13 @@ function parseSize(text, bareUnit = 1) {
1612
1893
  const match = SIZE.exec(text.trim());
1613
1894
  if (match === null)
1614
1895
  return;
1615
- const suffix = match[2].toLowerCase();
1616
- return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1896
+ const suffix = match[2]?.toLowerCase();
1897
+ let unit = bareUnit;
1898
+ if (match[3] !== undefined)
1899
+ unit = 1;
1900
+ else if (suffix !== undefined)
1901
+ unit = 1024 ** POWERS[suffix];
1902
+ return Math.round(Number(match[1]) * unit);
1617
1903
  }
1618
1904
  function formatSize(bytes) {
1619
1905
  let value = bytes;
@@ -1622,11 +1908,17 @@ function formatSize(bytes) {
1622
1908
  value /= 1024;
1623
1909
  unit++;
1624
1910
  }
1625
- return unit === 0 ? `${value}B` : `${value.toFixed(value < 10 ? 1 : 0)}${UNITS2[unit]}`;
1911
+ if (unit === 0)
1912
+ return `${value}B`;
1913
+ if (Number(value.toFixed(value < 10 ? 1 : 0)) >= 1024 && unit < UNITS2.length - 1) {
1914
+ value /= 1024;
1915
+ unit++;
1916
+ }
1917
+ return `${value.toFixed(value < 10 ? 1 : 0)}${UNITS2[unit]}`;
1626
1918
  }
1627
1919
  var SIZE, POWERS, UNITS2;
1628
1920
  var init_size = __esm(() => {
1629
- SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
1921
+ SIZE = /^(\d+(?:\.\d+)?)\s*(?:([kmgt])i?b?|(b))?$/i;
1630
1922
  POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
1631
1923
  UNITS2 = ["B", "K", "M", "G", "T"];
1632
1924
  });
@@ -1676,8 +1968,8 @@ var init_src = __esm(() => {
1676
1968
  });
1677
1969
 
1678
1970
  // ../arc/src/proc.ts
1679
- import process17 from "process";
1680
- async function interactive(argv, cwd = process17.cwd()) {
1971
+ import process19 from "process";
1972
+ async function interactive(argv, cwd = process19.cwd()) {
1681
1973
  return Bun.spawn(argv, { cwd, stdin: "inherit", stdout: "inherit", stderr: "inherit" }).exited;
1682
1974
  }
1683
1975
  var init_proc = __esm(() => {
@@ -1685,7 +1977,7 @@ var init_proc = __esm(() => {
1685
1977
  });
1686
1978
 
1687
1979
  // ../arc/src/extract.ts
1688
- import { existsSync as existsSync3, rmSync, statSync as statSync2 } from "fs";
1980
+ import { existsSync as existsSync3, renameSync, rmSync, statSync as statSync2 } from "fs";
1689
1981
  import { basename, join as join6, resolve as resolve4 } from "path";
1690
1982
  function archiveSuffix(file) {
1691
1983
  return extractorOf(file)?.[0];
@@ -1693,14 +1985,14 @@ function archiveSuffix(file) {
1693
1985
  function extractorOf(file) {
1694
1986
  return EXTRACTORS.find(([suffix]) => file.toLowerCase().endsWith(suffix));
1695
1987
  }
1696
- async function extractArchive(file, cwd) {
1988
+ async function extractArchive(file, cwd, overwrite = false) {
1697
1989
  if (!existsSync3(file) || !statSync2(file).isFile())
1698
1990
  return fail(`'${file}' is not a file`, 1);
1699
1991
  const extractor = extractorOf(file);
1700
1992
  if (extractor === undefined)
1701
1993
  return fail(`'${file}' cannot be extracted: unknown extension`, 1);
1702
1994
  const [suffix, argvOf] = extractor;
1703
- const argv = argvOf(resolve4(file));
1995
+ const argv = argvOf(resolve4(file), overwrite);
1704
1996
  if (Bun.which(argv[0] ?? "") === null)
1705
1997
  return fail(`${argv[0]} is not on PATH`, 1);
1706
1998
  if (!LONE.has(suffix))
@@ -1709,79 +2001,210 @@ async function extractArchive(file, cwd) {
1709
2001
  if (name === "")
1710
2002
  return fail(`'${file}' has no name left once ${suffix} is taken off`, 1);
1711
2003
  const target = join6(cwd, name);
1712
- if (await Bun.spawn(argv, { stdin: "ignore", stdout: Bun.file(target), stderr: "inherit" }).exited === 0)
2004
+ if (existsSync3(target) && !overwrite)
2005
+ return fail(`'${target}' already exists, nothing written`, 1, "pass --overwrite to replace it");
2006
+ const partial = `${target}.arc-partial`;
2007
+ if (await Bun.spawn(argv, { stdin: "ignore", stdout: Bun.file(partial), stderr: "inherit" }).exited === 0) {
2008
+ renameSync(partial, target);
1713
2009
  return 0;
1714
- rmSync(target, { force: true });
2010
+ }
2011
+ rmSync(partial, { force: true });
1715
2012
  return 1;
1716
2013
  }
1717
- var EXTRACTORS, LONE;
2014
+ var keepOld = (overwrite) => overwrite ? [] : ["-k"], EXTRACTORS, LONE;
1718
2015
  var init_extract = __esm(() => {
1719
2016
  init_src();
1720
2017
  init_proc();
1721
2018
  EXTRACTORS = [
1722
- [".tar.bz2", (file) => ["tar", "xjf", file]],
1723
- [".tar.gz", (file) => ["tar", "xzf", file]],
1724
- [".tar.xz", (file) => ["tar", "xJf", file]],
1725
- [".tar.zst", (file) => ["tar", "--zstd", "-xf", file]],
1726
- [".tbz2", (file) => ["tar", "xjf", file]],
1727
- [".tgz", (file) => ["tar", "xzf", file]],
1728
- [".tar", (file) => ["tar", "xf", file]],
1729
- [".tbz", (file) => ["tar", "xjf", file]],
1730
- [".txz", (file) => ["tar", "xJf", file]],
1731
- [".tzst", (file) => ["tar", "--zstd", "-xf", file]],
2019
+ [".tar.bz2", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xjf", file]],
2020
+ [".tar.gz", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xzf", file]],
2021
+ [".tar.xz", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xJf", file]],
2022
+ [".tar.zst", (file, overwrite) => ["tar", ...keepOld(overwrite), "--zstd", "-xf", file]],
2023
+ [".tbz2", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xjf", file]],
2024
+ [".tgz", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xzf", file]],
2025
+ [".tar", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xf", file]],
2026
+ [".tbz", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xjf", file]],
2027
+ [".txz", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xJf", file]],
2028
+ [".tzst", (file, overwrite) => ["tar", ...keepOld(overwrite), "--zstd", "-xf", file]],
1732
2029
  [".bz2", (file) => ["bunzip2", "-c", file]],
1733
2030
  [".gz", (file) => ["gunzip", "-c", file]],
1734
2031
  [".xz", (file) => ["xz", "-dc", file]],
1735
2032
  [".zst", (file) => ["zstd", "-dc", file]],
1736
- [".zip", (file) => ["unzip", file]],
2033
+ [".zip", (file, overwrite) => ["unzip", overwrite ? "-o" : "-n", file]],
1737
2034
  [".z", (file) => ["gzip", "-dc", file]],
1738
- [".rar", (file) => ["unrar", "x", file]],
1739
- [".7z", (file) => ["7z", "x", file]]
2035
+ [".rar", (file, overwrite) => ["unrar", "x", overwrite ? "-o+" : "-o-", file]],
2036
+ [".7z", (file, overwrite) => ["7z", "x", overwrite ? "-aoa" : "-aos", file]]
1740
2037
  ];
1741
2038
  LONE = new Set([".bz2", ".gz", ".xz", ".zst", ".z"]);
1742
2039
  });
1743
2040
 
2041
+ // src/state.ts
2042
+ import { copyFileSync, existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync5, renameSync as renameSync2, rmSync as rmSync2, statSync as statSync3, writeFileSync } from "fs";
2043
+ import { dirname as dirname4, join as join7 } from "path";
2044
+ function stateDir() {
2045
+ return join7(stateHome(), CLI_FOLDER, "dl");
2046
+ }
2047
+ function seenDir(url) {
2048
+ return join7(stateDir(), "seen", new Bun.CryptoHasher("sha256").update(url).digest("hex").slice(0, 32));
2049
+ }
2050
+ function lastSeen(url) {
2051
+ const dir = seenDir(url);
2052
+ const meta = join7(dir, "seen.json");
2053
+ if (!existsSync4(meta))
2054
+ return;
2055
+ const content = join7(dir, "content");
2056
+ return { seen: JSON.parse(readFileSync5(meta, "utf8")), content: existsSync4(content) ? content : undefined };
2057
+ }
2058
+ function remember(url, file) {
2059
+ const dir = seenDir(url);
2060
+ const content = join7(dir, "content");
2061
+ mkdirSync2(dir, { recursive: true });
2062
+ rmSync2(content, { force: true });
2063
+ if (file.text && !file.html && file.size <= KEPT_TEXT)
2064
+ copyFileSync(file.path, content);
2065
+ writeJson(join7(dir, "seen.json"), { url, sha256: file.sha256, size: file.size, at: new Date().toISOString() });
2066
+ }
2067
+ function partOf(url) {
2068
+ const dir = seenDir(url);
2069
+ const file = join7(dir, "part");
2070
+ const meta = join7(dir, "part.json");
2071
+ if (!existsSync4(file) || !existsSync4(meta))
2072
+ return { file, kept: undefined };
2073
+ const part = JSON.parse(readFileSync5(meta, "utf8"));
2074
+ const size = statSync3(file).size;
2075
+ return { file, kept: part.url === url && size > 0 ? { ...part, size } : undefined };
2076
+ }
2077
+ function keepPart(part) {
2078
+ writeJson(join7(seenDir(part.url), "part.json"), part);
2079
+ }
2080
+ function dropPart(url) {
2081
+ rmSync2(join7(seenDir(url), "part"), { force: true });
2082
+ rmSync2(join7(seenDir(url), "part.json"), { force: true });
2083
+ }
2084
+ function dropStaleParts(now = Date.now()) {
2085
+ const seen = join7(stateDir(), "seen");
2086
+ if (!existsSync4(seen))
2087
+ return;
2088
+ for (const dir of readdirSync(seen)) {
2089
+ const file = join7(seen, dir, "part");
2090
+ if (existsSync4(file) && now - statSync3(file).mtimeMs > PART_LIFETIME) {
2091
+ rmSync2(file, { force: true });
2092
+ rmSync2(join7(seen, dir, "part.json"), { force: true });
2093
+ }
2094
+ }
2095
+ }
2096
+ function ledgerPath() {
2097
+ return join7(stateDir(), "ledger.json");
2098
+ }
2099
+ function readLedger() {
2100
+ const path = ledgerPath();
2101
+ return existsSync4(path) ? JSON.parse(readFileSync5(path, "utf8")) : [];
2102
+ }
2103
+ function record(entry) {
2104
+ writeJson(ledgerPath(), [...readLedger().filter((other) => other.kind !== entry.kind || other.name !== entry.name), entry]);
2105
+ }
2106
+ function writeJson(path, value) {
2107
+ mkdirSync2(dirname4(path), { recursive: true });
2108
+ writeFileSync(`${path}.tmp`, `${JSON.stringify(value, null, 2)}
2109
+ `);
2110
+ renameSync2(`${path}.tmp`, path);
2111
+ }
2112
+ var KEPT_TEXT, PART_LIFETIME;
2113
+ var init_state = __esm(() => {
2114
+ init_src();
2115
+ KEPT_TEXT = 1024 * 1024;
2116
+ PART_LIFETIME = 7 * 24 * 3600000;
2117
+ });
2118
+
1744
2119
  // src/download.ts
1745
- import { existsSync as existsSync4, rmSync as rmSync2 } from "fs";
1746
- import { basename as basename2, join as join7 } from "path";
2120
+ import { copyFileSync as copyFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync3, renameSync as renameSync3, rmSync as rmSync3 } from "fs";
2121
+ import { open } from "fs/promises";
2122
+ import { basename as basename2, dirname as dirname5, join as join8 } from "path";
2123
+ async function request(url, kept) {
2124
+ const headers = { "accept-encoding": "identity" };
2125
+ const validator = kept?.etag !== undefined && !kept.etag.startsWith("W/") ? kept.etag : kept?.lastModified;
2126
+ if (kept === undefined || validator === undefined)
2127
+ return { response: await reach(url, { headers, decompress: false }), offset: 0 };
2128
+ const response = await reach(url, { headers: { ...headers, range: `bytes=${kept.size}-`, "if-range": validator }, decompress: false }, [RANGE_NOT_SATISFIABLE]);
2129
+ const start = CONTENT_RANGE.exec(response.headers.get("content-range") ?? "")?.[1];
2130
+ if (response.status === 206 && Number(start) === kept.size)
2131
+ return { response, offset: kept.size };
2132
+ if (response.status === 200)
2133
+ return { response, offset: 0 };
2134
+ await response.body?.cancel();
2135
+ return { response: await reach(url, { headers, decompress: false }), offset: 0 };
2136
+ }
2137
+ async function replay(file, hasher) {
2138
+ for await (const chunk of Bun.file(file).stream())
2139
+ hasher.update(chunk);
2140
+ return Bun.file(file).slice(0, HEAD_BYTES).bytes();
2141
+ }
2142
+ function moveInto(from, to) {
2143
+ try {
2144
+ renameSync3(from, to);
2145
+ } catch {
2146
+ copyFileSync2(from, to);
2147
+ rmSync3(from, { force: true });
2148
+ }
2149
+ }
1747
2150
  async function download(url, dir, maxSize) {
1748
- const response = await reach(url);
1749
- const name = fileName(response, url);
1750
- const path = join7(dir, name);
1751
- if (existsSync4(path))
2151
+ dropStaleParts();
2152
+ const { file: partFile, kept } = partOf(url);
2153
+ const { response, offset } = await request(url, kept);
2154
+ const name = offset > 0 ? kept.name : fileName(response, url);
2155
+ const path = join8(dir, name);
2156
+ if (existsSync5(path)) {
2157
+ await response.body?.cancel();
1752
2158
  return fail(`'${path}' already exists`, 1, "download into another folder with -o, or none to get a new one");
2159
+ }
1753
2160
  const length = Number(response.headers.get("content-length") ?? Number.NaN);
1754
- const total = Number.isFinite(length) && length > 0 ? length : undefined;
1755
- if (total !== undefined && total > maxSize)
2161
+ const total = Number.isFinite(length) && length > 0 ? offset + length : undefined;
2162
+ if (total !== undefined && total > maxSize) {
2163
+ await response.body?.cancel();
1756
2164
  return fail(`${url} is ${formatSize(total)}, over --max-size ${formatSize(maxSize)}`, 1);
2165
+ }
2166
+ const part = { url, name, ...offset > 0 ? validators(kept) : {}, ...validators(response.headers) };
2167
+ const resumable = part.etag !== undefined || part.lastModified !== undefined;
2168
+ if (offset === 0)
2169
+ dropPart(url);
2170
+ if (resumable)
2171
+ keepPart(part);
1757
2172
  const line = progressLine();
1758
2173
  const hasher = new Bun.CryptoHasher("sha256");
1759
- const writer = Bun.file(path).writer();
1760
- const head = [];
1761
- let headSize = 0;
1762
- let size = 0;
1763
- line.update({ step: name, ...counted(0, total) });
2174
+ const head = offset > 0 ? [await replay(partFile, hasher)] : [];
2175
+ mkdirSync3(dirname5(partFile), { recursive: true });
2176
+ const handle = await open(partFile, offset > 0 ? "a" : "w");
2177
+ let headSize = head[0]?.length ?? 0;
2178
+ let size = offset;
2179
+ let overSize = false;
2180
+ line.update({ step: name, ...counted(size, total) });
1764
2181
  try {
1765
2182
  for await (const chunk of response.body ?? new ReadableStream) {
1766
2183
  size += chunk.length;
1767
- if (size > maxSize)
2184
+ overSize = size > maxSize;
2185
+ if (overSize)
1768
2186
  fail(`${url} goes over --max-size ${formatSize(maxSize)}`, 1);
1769
2187
  if (headSize < HEAD_BYTES) {
1770
2188
  head.push(chunk.subarray(0, HEAD_BYTES - headSize));
1771
2189
  headSize += head.at(-1).length;
1772
2190
  }
1773
2191
  hasher.update(chunk);
1774
- await writer.write(chunk);
2192
+ await handle.write(chunk);
1775
2193
  line.update({ step: name, ...counted(size, total) });
1776
2194
  }
1777
- await writer.end();
1778
2195
  } catch (error) {
1779
- await writer.end();
1780
- rmSync2(path, { force: true });
2196
+ await handle.close();
1781
2197
  line.failed(name);
1782
- throw error;
2198
+ if (overSize || !resumable) {
2199
+ dropPart(url);
2200
+ throw error;
2201
+ }
2202
+ return fail(`the download of ${url} broke off at ${formatSize(size)}: ${error instanceof Error ? error.message : String(error)}`, 1, "run the same dl again to resume it");
1783
2203
  }
1784
- line.done(`${name} ${formatSize(size)}`);
2204
+ await handle.close();
2205
+ moveInto(partFile, path);
2206
+ dropPart(url);
2207
+ line.done(`${name} ${formatSize(size)}${offset > 0 ? `, resumed at ${formatSize(offset)}` : ""}`);
1785
2208
  const start = Buffer.concat(head);
1786
2209
  return {
1787
2210
  path,
@@ -1791,17 +2214,35 @@ async function download(url, dir, maxSize) {
1791
2214
  type: response.headers.get("content-type") ?? "",
1792
2215
  sha256: hasher.digest("hex"),
1793
2216
  html: HTML_START.test(start.toString("utf8")),
1794
- text: !start.includes(0)
2217
+ text: !start.includes(0),
2218
+ ...validators(part)
1795
2219
  };
1796
2220
  }
1797
- async function reach(url) {
2221
+ function validators(from) {
2222
+ const etag = from instanceof Headers ? from.get("etag") ?? undefined : from.etag;
2223
+ const lastModified = from instanceof Headers ? from.get("last-modified") ?? undefined : from.lastModified;
2224
+ return { ...etag === undefined ? {} : { etag }, ...lastModified === undefined ? {} : { lastModified } };
2225
+ }
2226
+ async function smallFile(url) {
2227
+ const response = await reach(url);
2228
+ const chunks = [];
2229
+ let size = 0;
2230
+ for await (const chunk of response.body ?? new ReadableStream) {
2231
+ size += chunk.length;
2232
+ if (size > SMALL_FILE)
2233
+ fail(`${url} goes over ${formatSize(SMALL_FILE)}, too large for a signature or checksums file`, 1);
2234
+ chunks.push(chunk);
2235
+ }
2236
+ return Buffer.concat(chunks);
2237
+ }
2238
+ async function reach(url, init, allowed = []) {
1798
2239
  let response;
1799
2240
  try {
1800
- response = await fetch(url);
2241
+ response = await fetch(url, init);
1801
2242
  } catch (error) {
1802
2243
  return fail(`cannot reach ${url}: ${error instanceof Error ? error.message : String(error)}`, 1);
1803
2244
  }
1804
- return response.ok ? response : fail(`${url} answered ${response.status} ${response.statusText}`.trimEnd(), 1);
2245
+ return response.ok || allowed.includes(response.status) ? response : fail(`${url} answered ${response.status} ${response.statusText}`.trimEnd(), 1);
1805
2246
  }
1806
2247
  function fileName(response, requested) {
1807
2248
  const disposition = DISPOSITION_NAME.exec(response.headers.get("content-disposition") ?? "")?.[1];
@@ -1822,29 +2263,32 @@ function counted(done, total) {
1822
2263
  const [unit, scale] = total >= 1024 ** 2 ? ["MiB", 1024 ** 2] : ["KiB", 1024];
1823
2264
  return { done: Math.floor(done / scale), total: Math.ceil(total / scale), unit };
1824
2265
  }
1825
- var HEAD_BYTES = 8192, HTML_START, DISPOSITION_NAME;
2266
+ var HEAD_BYTES = 8192, HTML_START, DISPOSITION_NAME, CONTENT_RANGE, RANGE_NOT_SATISFIABLE = 416, SMALL_FILE;
1826
2267
  var init_download = __esm(() => {
1827
2268
  init_src();
1828
2269
  init_progress();
2270
+ init_state();
1829
2271
  HTML_START = /^\s*<(?:!doctype html|html)[\s>]/i;
1830
2272
  DISPOSITION_NAME = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i;
2273
+ CONTENT_RANGE = /^bytes (\d+)-\d+\/(?:\d+|\*)$/;
2274
+ SMALL_FILE = 16 * 1024 * 1024;
1831
2275
  });
1832
2276
 
1833
2277
  // src/install.ts
1834
- import { chmodSync, closeSync, copyFileSync, existsSync as existsSync5, mkdirSync as mkdirSync2, openSync, readSync, renameSync, statSync as statSync3 } from "fs";
2278
+ import { chmodSync, closeSync, copyFileSync as copyFileSync3, existsSync as existsSync6, mkdirSync as mkdirSync4, openSync, readSync, renameSync as renameSync4, statSync as statSync4 } from "fs";
1835
2279
  import { homedir as homedir4 } from "os";
1836
- import { basename as basename3, delimiter, join as join8, relative } from "path";
1837
- import process18 from "process";
2280
+ import { basename as basename3, delimiter, join as join9, relative } from "path";
2281
+ import process20 from "process";
1838
2282
  function binDir() {
1839
- return join8(homedir4(), ".local", "bin");
2283
+ return join9(homedir4(), ".local", "bin");
1840
2284
  }
1841
2285
  function binDirOnPath() {
1842
- return (process18.env.PATH ?? "").split(delimiter).includes(binDir());
2286
+ return (process20.env.PATH ?? "").split(delimiter).includes(binDir());
1843
2287
  }
1844
2288
  async function pickBinary(root, wanted) {
1845
2289
  const found = [];
1846
2290
  for await (const file of new Bun.Glob("**/*").scan({ cwd: root, onlyFiles: true, dot: true }))
1847
- found.push(join8(root, file));
2291
+ found.push(join9(root, file));
1848
2292
  const executables = found.filter(isExecutable).sort();
1849
2293
  const matching = wanted === undefined ? executables : executables.filter((file) => basename3(file) === wanted);
1850
2294
  const listed = executables.map((file) => relative(root, file)).join(", ");
@@ -1857,17 +2301,17 @@ async function pickBinary(root, wanted) {
1857
2301
  return fail(`the archive holds several executables: ${listed}`, 1, "name the one to install: --bin <name>");
1858
2302
  }
1859
2303
  function installBinary(source, name, force) {
1860
- const target = join8(binDir(), name);
1861
- if (existsSync5(target) && !force)
2304
+ const target = join9(binDir(), name);
2305
+ if (existsSync6(target) && !force)
1862
2306
  return fail(`'${target}' already exists`, 1, "pass --force to replace it");
1863
- mkdirSync2(binDir(), { recursive: true });
1864
- copyFileSync(source, `${target}.dl-tmp`);
2307
+ mkdirSync4(binDir(), { recursive: true });
2308
+ copyFileSync3(source, `${target}.dl-tmp`);
1865
2309
  chmodSync(`${target}.dl-tmp`, 493);
1866
- renameSync(`${target}.dl-tmp`, target);
2310
+ renameSync4(`${target}.dl-tmp`, target);
1867
2311
  return target;
1868
2312
  }
1869
2313
  function isExecutable(file) {
1870
- if ((statSync3(file).mode & 73) !== 0)
2314
+ if ((statSync4(file).mode & 73) !== 0)
1871
2315
  return true;
1872
2316
  const start = Buffer.alloc(4);
1873
2317
  const fd = openSync(file, "r");
@@ -1881,6 +2325,172 @@ var init_install = __esm(() => {
1881
2325
  ELF = Buffer.from([127, 69, 76, 70]);
1882
2326
  });
1883
2327
 
2328
+ // src/release.ts
2329
+ import { readdirSync as readdirSync2 } from "fs";
2330
+ import process21 from "process";
2331
+ function parseSpec(arg) {
2332
+ const [, forge, owner = "", repo = "", tag] = SPEC.exec(arg) ?? [];
2333
+ if (forge === undefined)
2334
+ return;
2335
+ return { forge, owner, repo, ...tag === undefined ? {} : { tag } };
2336
+ }
2337
+ function specName(spec) {
2338
+ return `${spec.forge}:${spec.owner}/${spec.repo}`;
2339
+ }
2340
+ function thisPlatform() {
2341
+ let musl = false;
2342
+ try {
2343
+ const glibc = process21.report.getReport().header?.glibcVersionRuntime;
2344
+ musl = process21.platform === "linux" && glibc === undefined && readdirSync2("/lib").some((file) => file.startsWith("ld-musl-"));
2345
+ } catch {}
2346
+ return { os: process21.platform, arch: process21.arch, musl };
2347
+ }
2348
+ function releasesUrl(spec) {
2349
+ const path = `repos/${spec.owner}/${spec.repo}/releases`;
2350
+ const tagged = spec.tag === undefined ? "" : `/tags/${encodeURIComponent(spec.tag)}`;
2351
+ if (spec.forge === "fj")
2352
+ return { url: `${process21.env.DL_FORGEJO_URL ?? "https://git.kaynooo.fr"}/api/v1/${path}${tagged || "?limit=30"}`, headers: { accept: "application/json" } };
2353
+ const token = process21.env.GITHUB_TOKEN ?? process21.env.GH_TOKEN;
2354
+ const headers = { accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28" };
2355
+ if (token !== undefined && token !== "")
2356
+ headers.authorization = `Bearer ${token}`;
2357
+ return { url: `${process21.env.DL_GITHUB_API ?? "https://api.github.com"}/${path}${tagged || "?per_page=30"}`, headers };
2358
+ }
2359
+ async function releases(spec) {
2360
+ const { url, headers } = releasesUrl(spec);
2361
+ let response;
2362
+ try {
2363
+ response = await fetch(url, { headers });
2364
+ } catch (error) {
2365
+ return fail(`cannot reach ${url}: ${error instanceof Error ? error.message : String(error)}`, 1);
2366
+ }
2367
+ if (response.status === 404)
2368
+ fail(`${specName(spec)} has no release${spec.tag === undefined ? "s" : ` ${spec.tag}`}`, 1);
2369
+ if (!response.ok) {
2370
+ const limited = response.headers.get("x-ratelimit-remaining") === "0";
2371
+ fail(`${url} answered ${response.status} ${response.statusText}`.trimEnd(), 1, limited ? "GitHub's hourly limit is reached: set GITHUB_TOKEN to a token to lift it" : undefined);
2372
+ }
2373
+ const body = await response.json();
2374
+ return (Array.isArray(body) ? body : [body]).filter((release) => !release.draft && (spec.tag !== undefined || !release.prerelease) && release.published_at !== null).map((release) => ({
2375
+ tag: release.tag_name,
2376
+ published: release.published_at,
2377
+ assets: release.assets.map((asset) => ({ name: asset.name, url: asset.browser_download_url, ...typeof asset.digest === "string" ? { digest: asset.digest } : {} }))
2378
+ }));
2379
+ }
2380
+ async function newestFirst(spec) {
2381
+ return (await releases(spec)).sort((a, b) => Date.parse(b.published) - Date.parse(a.published));
2382
+ }
2383
+ function oldEnough(release, now) {
2384
+ return now - Date.parse(release.published) >= MIN_AGE;
2385
+ }
2386
+ async function latestRelease(spec, now = Date.now()) {
2387
+ return (await newestFirst(spec)).find((release) => oldEnough(release, now));
2388
+ }
2389
+ async function pickRelease(spec, fresh, now = Date.now()) {
2390
+ const found = await newestFirst(spec);
2391
+ const newest = found[0] ?? fail(`${specName(spec)} has no published release`, 1);
2392
+ if (spec.tag !== undefined || fresh)
2393
+ return newest;
2394
+ const old = found.find((release) => oldEnough(release, now));
2395
+ const skipped = found.slice(0, old === undefined ? found.length : found.indexOf(old));
2396
+ const said = skipped.map((release) => `${release.tag} (${formatAge(release.published, now)})`).join(", ");
2397
+ if (old === undefined)
2398
+ return fail(`no release of ${specName(spec)} is two weeks old yet: ${said}`, 1, "--fresh takes the newest anyway");
2399
+ if (skipped.length > 0)
2400
+ warn(`${specName(spec)}: took ${old.tag}, skipped ${said} as under two weeks old; --fresh takes the newest`);
2401
+ return old;
2402
+ }
2403
+ function rank(items, score) {
2404
+ const best = Math.min(...items.map(score));
2405
+ return items.filter((item) => score(item) === best);
2406
+ }
2407
+ function libcRank(name, musl) {
2408
+ if (GNU.test(name))
2409
+ return 0;
2410
+ if (MUSL.test(name))
2411
+ return musl ? 0 : 2;
2412
+ return 1;
2413
+ }
2414
+ function pickAsset(assets, platform, wanted) {
2415
+ const builds = assets.filter((asset) => !NOT_A_BUILD.test(asset.name));
2416
+ const listed = (list) => list.map((asset) => asset.name).join(", ");
2417
+ if (wanted !== undefined) {
2418
+ const glob = new Bun.Glob(wanted);
2419
+ const matches = (asset) => wanted.includes("*") ? glob.match(asset.name) : asset.name.includes(wanted);
2420
+ const named = builds.some(matches) ? builds.filter(matches) : assets.filter(matches);
2421
+ if (named.length === 1)
2422
+ return named[0];
2423
+ return fail(named.length === 0 ? `no asset matches --asset ${wanted}: ${listed(builds)}` : `several assets match --asset ${wanted}: ${listed(named)}`, 1);
2424
+ }
2425
+ const osWord = OS_WORDS[platform.os];
2426
+ const archWord = ARCH_WORDS[platform.arch];
2427
+ const namesOs = builds.filter((asset) => Object.values(OS_WORDS).some((word) => word.test(asset.name)));
2428
+ let fit = namesOs.length === 0 ? builds : builds.filter((asset) => osWord?.test(asset.name) === true);
2429
+ const namesArch = fit.filter((asset) => Object.values(ARCH_WORDS).some((word) => word.test(asset.name)));
2430
+ fit = namesArch.length === 0 ? fit : fit.filter((asset) => archWord?.test(asset.name) === true || ANY_ARCH.test(asset.name));
2431
+ if (platform.musl)
2432
+ fit = fit.filter((asset) => !GNU.test(asset.name));
2433
+ if (fit.length === 0)
2434
+ return fail(`no asset is built for ${platform.os} ${platform.arch}${platform.musl ? " musl" : ""}: ${listed(builds)}`, 1, "pick one with --asset <part of its name>");
2435
+ fit = rank(fit, (asset) => libcRank(asset.name, platform.musl));
2436
+ fit = rank(fit, (asset) => ARCH_WORDS[platform.arch]?.test(asset.name) === true ? 0 : 1);
2437
+ fit = rank(fit, (asset) => {
2438
+ const format = FORMATS.findIndex((each) => each.test(asset.name));
2439
+ return format === -1 ? FORMATS.length : format;
2440
+ });
2441
+ return fit.length === 1 ? fit[0] : fail(`several assets fit ${platform.os} ${platform.arch}: ${listed(fit)}`, 1, "pick one with --asset <part of its name>");
2442
+ }
2443
+ function signatureOf(assets, target, key) {
2444
+ const suffixes = { gpg: [".asc", ".sig", ".gpg"], minisign: [".minisig"], cosign: [".sig"] }[key.tool];
2445
+ return suffixes.map((suffix) => assets.find((asset) => asset.name === `${target}${suffix}`)).find((asset) => asset !== undefined);
2446
+ }
2447
+ async function resolveRelease(spec, options) {
2448
+ const release = await pickRelease(spec, options.fresh);
2449
+ const asset = pickAsset(release.assets, options.platform ?? thisPlatform(), options.asset);
2450
+ const own = release.assets.find((each) => each.name.startsWith(`${asset.name}.sha256`));
2451
+ const sums = own ?? release.assets.find((each) => SUMS.test(each.name));
2452
+ const digest = DIGEST.exec(asset.digest ?? "")?.[1];
2453
+ const signature = options.key === undefined ? undefined : signatureOf(release.assets, (sums ?? asset).name, options.key);
2454
+ if (options.key !== undefined && signature === undefined)
2455
+ fail(`${specName(spec)} ${release.tag} ships no ${options.key.tool} signature of ${(sums ?? asset).name}`, 1);
2456
+ return {
2457
+ spec: specName(spec),
2458
+ ...spec.tag === undefined ? {} : { pinned: `${specName(spec)}@${spec.tag}` },
2459
+ tag: release.tag,
2460
+ published: release.published,
2461
+ asset,
2462
+ ...sums === undefined ? {} : { sums: sums.url },
2463
+ ...digest === undefined ? {} : { digest },
2464
+ ...signature === undefined ? {} : { sig: signature.url }
2465
+ };
2466
+ }
2467
+ function assertReleaseOptions(isRelease, values) {
2468
+ if (!isRelease && (values.fresh === true || values.asset !== undefined))
2469
+ badUsage("--fresh and --asset go with a release, gh:owner/repo or fj:owner/repo");
2470
+ }
2471
+ var SPEC, MIN_AGE, DIGEST, NOT_A_BUILD, SUMS, OS_WORDS, ARCH_WORDS, ANY_ARCH, GNU, MUSL, FORMATS;
2472
+ var init_release = __esm(() => {
2473
+ init_src();
2474
+ SPEC = /^(gh|fj):([\w.-]+)\/([\w.-]+)(?:@(\S+))?$/;
2475
+ MIN_AGE = 14 * 24 * 3600000;
2476
+ DIGEST = /^sha256:([0-9a-f]{64})$/;
2477
+ NOT_A_BUILD = /\.(?:sha256(?:sum)?|sha512(?:sum)?|md5|asc|sig|minisig|pem|crt|cert|sbom|spdx|cdx|json|jsonl|txt|deb|rpm|apk|msi|dmg|pkg|sh)$|(?:checksums?|sums?)$/i;
2478
+ SUMS = /(?:^|[-_.])(?:sha256sums?|checksums?)(?:\.txt)?$/i;
2479
+ OS_WORDS = {
2480
+ linux: /linux/i,
2481
+ darwin: /darwin|mac-?os|apple|osx/i,
2482
+ win32: /windows|(?<![a-z])win(?:32|64)?(?=[-_.]|$)/i
2483
+ };
2484
+ ARCH_WORDS = {
2485
+ x64: /x86[-_]64|amd64|x64(?!\d)/i,
2486
+ arm64: /aarch64|arm64/i
2487
+ };
2488
+ ANY_ARCH = /universal/i;
2489
+ GNU = /gnu|glibc/i;
2490
+ MUSL = /musl/i;
2491
+ FORMATS = [/\.(?:tar\.gz|tgz)$/i, /\.tar\.xz$/i, /\.tar\.(?:zst|bz2)$/i, /\.zip$/i];
2492
+ });
2493
+
1884
2494
  // src/script.ts
1885
2495
  function summarize(script) {
1886
2496
  const findings = [];
@@ -1915,57 +2525,114 @@ var init_script = __esm(() => {
1915
2525
  SHELL_OWN = new Set(["HOME", "PATH", "PWD", "OLDPWD", "SHELL", "USER", "IFS", "TERM", "LINENO", "RANDOM", "UID", "EUID", "BASH_SOURCE", "BASH_VERSION", "ZSH_VERSION"]);
1916
2526
  });
1917
2527
 
1918
- // src/state.ts
1919
- import { copyFileSync as copyFileSync2, existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync as renameSync2, rmSync as rmSync3, writeFileSync } from "fs";
1920
- import { dirname as dirname4, join as join9 } from "path";
1921
- function stateDir() {
1922
- return join9(stateHome(), CLI_FOLDER, "dl");
1923
- }
1924
- function seenDir(url) {
1925
- return join9(stateDir(), "seen", new Bun.CryptoHasher("sha256").update(url).digest("hex").slice(0, 32));
1926
- }
1927
- function lastSeen(url) {
1928
- const dir = seenDir(url);
1929
- const meta = join9(dir, "seen.json");
1930
- if (!existsSync6(meta))
1931
- return;
1932
- const content = join9(dir, "content");
1933
- return { seen: JSON.parse(readFileSync4(meta, "utf8")), content: existsSync6(content) ? content : undefined };
1934
- }
1935
- function remember(url, file) {
1936
- const dir = seenDir(url);
1937
- const content = join9(dir, "content");
1938
- mkdirSync3(dir, { recursive: true });
1939
- rmSync3(content, { force: true });
1940
- if (file.text && !file.html && file.size <= KEPT_TEXT)
1941
- copyFileSync2(file.path, content);
1942
- writeJson(join9(dir, "seen.json"), { url, sha256: file.sha256, size: file.size, at: new Date().toISOString() });
1943
- }
1944
- function ledgerPath() {
1945
- return join9(stateDir(), "ledger.json");
1946
- }
1947
- function readLedger() {
1948
- const path = ledgerPath();
1949
- return existsSync6(path) ? JSON.parse(readFileSync4(path, "utf8")) : [];
1950
- }
1951
- function record(entry) {
1952
- writeJson(ledgerPath(), [...readLedger().filter((other) => other.kind !== entry.kind || other.name !== entry.name), entry]);
1953
- }
1954
- function writeJson(path, value) {
1955
- mkdirSync3(dirname4(path), { recursive: true });
1956
- writeFileSync(`${path}.tmp`, `${JSON.stringify(value, null, 2)}
1957
- `);
1958
- renameSync2(`${path}.tmp`, path);
2528
+ // src/signature.ts
2529
+ import { existsSync as existsSync7, mkdirSync as mkdirSync5, mkdtempSync, readFileSync as readFileSync6, rmSync as rmSync4, statSync as statSync5, writeFileSync as writeFileSync2 } from "fs";
2530
+ import { tmpdir } from "os";
2531
+ import { join as join10 } from "path";
2532
+ function toolOfFile(path) {
2533
+ const bytes = readFileSync6(path);
2534
+ const text = bytes.subarray(0, 4096).toString("latin1");
2535
+ if (text.includes("-----BEGIN PGP PUBLIC KEY BLOCK-----") || ((bytes[0] ?? 0) & 128) !== 0)
2536
+ return "gpg";
2537
+ if (text.includes("minisign public key"))
2538
+ return "minisign";
2539
+ return text.includes("-----BEGIN PUBLIC KEY-----") ? "cosign" : undefined;
2540
+ }
2541
+ function readKey(key) {
2542
+ const fingerprint = key.replace(SPACES2, "").toUpperCase();
2543
+ let found;
2544
+ if (FINGERPRINT.test(fingerprint)) {
2545
+ found = { tool: "gpg", fingerprint };
2546
+ } else if (MINISIGN_KEY.test(key)) {
2547
+ found = { tool: "minisign", minisignKey: key };
2548
+ } else if (existsSync7(key) && statSync5(key).isFile()) {
2549
+ const tool = toolOfFile(key) ?? badUsage(`--key ${key} is no OpenPGP, minisign or cosign public key`);
2550
+ found = { tool, file: key };
2551
+ } else {
2552
+ return badUsage(`--key takes a gpg fingerprint, a minisign key or a public key file, not '${key}'`);
2553
+ }
2554
+ if (Bun.which(found.tool) === null)
2555
+ fail(`--key is a ${found.tool} key and ${found.tool} is not on PATH`, 1, `install it: ${GET[found.tool]}`);
2556
+ return found;
2557
+ }
2558
+ function statusFields(status, keyword) {
2559
+ const line = status.split(`
2560
+ `).find((each) => each.startsWith(`[GNUPG:] ${keyword} `));
2561
+ return line?.split(" ").slice(2);
2562
+ }
2563
+ async function gpgVerify(key, signature, signed, work) {
2564
+ const dir = join10(work, "gnupg");
2565
+ const home = key.file === undefined ? [] : ["--homedir", dir];
2566
+ if (key.file !== undefined) {
2567
+ mkdirSync5(dir, { mode: 448 });
2568
+ const imported = await runTool("gpg --import", ["gpg", "--batch", ...home, "--import", key.file]);
2569
+ if (imported.code !== 0)
2570
+ fail(`gpg could not import ${key.file}:
2571
+ ${imported.stderr.trim()}`, 1);
2572
+ }
2573
+ const verified = await runTool("gpg --verify", ["gpg", "--batch", ...home, "--status-fd", "1", "--verify", signature, signed]);
2574
+ const valid = statusFields(verified.stdout, "VALIDSIG");
2575
+ const by = [valid?.[0], valid?.at(-1)].filter((each) => each !== undefined).map((each) => each.toUpperCase());
2576
+ if (verified.code !== 0 || statusFields(verified.stdout, "GOODSIG") === undefined || valid === undefined)
2577
+ fail(`the gpg signature does not verify:
2578
+ ${verified.stderr.trim()}`, 1);
2579
+ if (key.fingerprint !== undefined && !by.includes(key.fingerprint))
2580
+ fail(`the gpg signature is by ${by.at(-1)}, not ${key.fingerprint}`, 1);
2581
+ return `gpg, by ${by.at(-1)}`;
2582
+ }
2583
+ async function toolVerify(key, signature, signed) {
2584
+ const argv = key.tool === "minisign" ? ["minisign", "-V", "-q", "-m", signed, "-x", signature, ...key.file === undefined ? ["-P", key.minisignKey] : ["-p", key.file]] : ["cosign", "verify-blob", "--key", key.file, "--signature", signature, signed];
2585
+ const verified = await runTool(`${key.tool} verify`, argv);
2586
+ if (verified.code !== 0)
2587
+ fail(`the ${key.tool} signature does not verify:
2588
+ ${`${verified.stderr}${verified.stdout}`.trim()}`, 1);
2589
+ return key.tool;
2590
+ }
2591
+ async function verifySignature(signed, url, key) {
2592
+ const work = mkdtempSync(join10(tmpdir(), "dl-sig-"));
2593
+ try {
2594
+ const signature = join10(work, "signature");
2595
+ const data = typeof signed === "string" ? signed : join10(work, "signed");
2596
+ writeFileSync2(signature, await smallFile(url));
2597
+ if (typeof signed !== "string")
2598
+ writeFileSync2(data, signed);
2599
+ return key.tool === "gpg" ? await gpgVerify(key, signature, data, work) : await toolVerify(key, signature, data);
2600
+ } finally {
2601
+ if (existsSync7(join10(work, "gnupg")))
2602
+ await runTool("gpgconf --kill", ["gpgconf", "--homedir", join10(work, "gnupg"), "--kill", "all"]);
2603
+ rmSync4(work, { recursive: true, force: true });
2604
+ }
1959
2605
  }
1960
- var KEPT_TEXT;
1961
- var init_state = __esm(() => {
2606
+ var FINGERPRINT, SPACES2, MINISIGN_KEY, GET;
2607
+ var init_signature = __esm(() => {
1962
2608
  init_src();
1963
- KEPT_TEXT = 1024 * 1024;
2609
+ init_download();
2610
+ FINGERPRINT = /^(?:[0-9A-F]{40}|[0-9A-F]{64})$/;
2611
+ SPACES2 = /\s+/g;
2612
+ MINISIGN_KEY = /^RW[A-Za-z0-9+/]{54}$/;
2613
+ GET = {
2614
+ gpg: "the gnupg package of the system",
2615
+ minisign: "https://jedisct1.github.io/minisign/",
2616
+ cosign: "https://docs.sigstore.dev/cosign/system_config/installation/"
2617
+ };
1964
2618
  });
1965
2619
 
1966
2620
  // src/sums.ts
1967
2621
  import { basename as basename4 } from "path";
1968
- function sumFor(text, name) {
2622
+ function pathUnder(sumsUrl, url) {
2623
+ const sums = new URL(sumsUrl);
2624
+ const file = new URL(url);
2625
+ const folder = sums.pathname.slice(0, sums.pathname.lastIndexOf("/") + 1);
2626
+ return sums.origin === file.origin && file.pathname.startsWith(folder) ? decoded2(file.pathname.slice(folder.length)) : undefined;
2627
+ }
2628
+ function decoded2(path) {
2629
+ try {
2630
+ return decodeURIComponent(path);
2631
+ } catch {
2632
+ return path;
2633
+ }
2634
+ }
2635
+ function sumFor(text, name, path) {
1969
2636
  const entries = [];
1970
2637
  for (const line of text.split(`
1971
2638
  `).map((line) => line.trim())) {
@@ -1976,34 +2643,45 @@ function sumFor(text, name) {
1976
2643
  else if (bsd !== null)
1977
2644
  entries.push([bsd[2], bsd[1]]);
1978
2645
  }
1979
- const named = entries.find(([, file]) => file !== undefined && basename4(file) === name);
1980
- if (named !== undefined)
1981
- return named[0].toLowerCase();
2646
+ const exact = path === undefined ? undefined : entries.find(([, file]) => file?.replace(DOT_SLASH, "") === path);
2647
+ if (exact !== undefined)
2648
+ return exact[0].toLowerCase();
2649
+ const named = entries.filter(([, file]) => file !== undefined && basename4(file) === name);
2650
+ const hashes = new Set(named.map(([hash]) => hash.toLowerCase()));
2651
+ if (hashes.size > 1)
2652
+ fail(`the checksums file lists ${name} as ${named.map(([, file]) => file).join(", ")}, none at the download's path`, 1);
2653
+ if (named[0] !== undefined)
2654
+ return named[0][0].toLowerCase();
1982
2655
  const [only] = entries;
1983
2656
  return entries.length === 1 && only[1] === undefined ? only[0].toLowerCase() : undefined;
1984
2657
  }
1985
- async function fetchSum(url, name) {
1986
- return sumFor(await (await reach(url)).text(), name) ?? fail(`${url} holds no sha256 for ${name}`, 1);
2658
+ async function fetchSums(url) {
2659
+ return smallFile(url);
2660
+ }
2661
+ function sumIn(sums, url, fileUrl, name) {
2662
+ return sumFor(new TextDecoder().decode(sums), name, pathUnder(url, fileUrl)) ?? fail(`${url} holds no sha256 for ${name}`, 1);
1987
2663
  }
1988
- var GNU_LINE, BSD_LINE;
2664
+ var GNU_LINE, BSD_LINE, DOT_SLASH;
1989
2665
  var init_sums = __esm(() => {
1990
2666
  init_src();
1991
2667
  init_download();
1992
2668
  GNU_LINE = /^([0-9a-f]{64})(?:\s+\*?(\S.*))?$/i;
1993
2669
  BSD_LINE = /^SHA256 \((.+)\) = ([0-9a-f]{64})$/i;
2670
+ DOT_SLASH = /^\.\//;
1994
2671
  });
1995
2672
 
1996
2673
  // src/get.ts
1997
2674
  var exports_get = {};
1998
2675
  __export(exports_get, {
2676
+ DEFAULT_MAX_SIZE: () => DEFAULT_MAX_SIZE,
1999
2677
  get: () => get
2000
2678
  });
2001
- import { chmodSync as chmodSync2, existsSync as existsSync7, mkdirSync as mkdirSync4, mkdtempSync, rmSync as rmSync4 } from "fs";
2002
- import { tmpdir } from "os";
2003
- import { basename as basename5, extname, join as join10, resolve as resolve5 } from "path";
2004
- import process19 from "process";
2679
+ import { chmodSync as chmodSync2, existsSync as existsSync8, mkdirSync as mkdirSync6, mkdtempSync as mkdtempSync2, rmSync as rmSync5 } from "fs";
2680
+ import { tmpdir as tmpdir2 } from "os";
2681
+ import { basename as basename5, extname, join as join11, resolve as resolve5 } from "path";
2682
+ import process22 from "process";
2005
2683
  async function get(args) {
2006
- const { values, positionals: [url], rest = [] } = parse(args, USAGE, OPTIONS, {
2684
+ const { values, positionals: [given], rest = [] } = parse(args, USAGE, OPTIONS, {
2007
2685
  positionals: ["<url>"],
2008
2686
  rest: true,
2009
2687
  exits: EXITS,
@@ -2012,11 +2690,15 @@ async function get(args) {
2012
2690
  ["dl https://bun.sh/install", "download it to read it"],
2013
2691
  ["dl https://bun.sh/install --exec --sha256 <sha>", "run the script that was read"],
2014
2692
  ["dl https://example.com/releases/tool-linux-amd64 --sums https://example.com/releases/SHA256SUMS --bin tool", "a checked binary, installed"],
2015
- ["dl https://example.com/tool.tar.gz -x", "download and unpack"]
2693
+ ["dl https://example.com/tool.tar.gz -x", "download and unpack"],
2694
+ ["dl https://example.com/tool.tar.gz --sums https://example.com/SHA256SUMS --sig https://example.com/SHA256SUMS.asc --key <fingerprint>", "checked against checksums its publisher signed"],
2695
+ ["dl gh:BurntSushi/ripgrep --bin rg", "the build of the latest release for this machine, installed"]
2016
2696
  ]
2017
2697
  });
2018
- if (!URL.canParse(url) || !["http:", "https:"].includes(new URL(url).protocol))
2019
- badUsage(`'${url}' is not an http or https URL`);
2698
+ const spec = parseSpec(given);
2699
+ assertReleaseOptions(spec !== undefined, values);
2700
+ if (spec === undefined && (!URL.canParse(given) || !["http:", "https:"].includes(new URL(given).protocol)))
2701
+ badUsage(`'${given}' is not an http or https URL, nor a release as gh:owner/repo or fj:owner/repo`);
2020
2702
  if (values.sha256 !== undefined && !SHA256.test(values.sha256))
2021
2703
  badUsage(`--sha256 takes 64 hex digits, not '${values.sha256}'`);
2022
2704
  if (values.yes === true && values.exec !== true)
@@ -2027,20 +2709,35 @@ async function get(args) {
2027
2709
  badUsage("arguments after -- go to an --exec script");
2028
2710
  if (values.bin !== undefined && (values.bin.includes("/") || values.bin === "." || values.bin === ".."))
2029
2711
  badUsage(`--bin takes a command name, not '${values.bin}'`);
2712
+ if (spec === undefined ? values.sig === undefined !== (values.key === undefined) : values.sig !== undefined && values.key === undefined)
2713
+ badUsage(spec === undefined ? "--sig and --key go together" : "--sig goes with --key");
2714
+ if (spec !== undefined && values.key !== undefined && values.sig === undefined && (values.sha256 !== undefined || values.sums !== undefined))
2715
+ badUsage("--key alone checks the release's own checksums file, which --sha256 and --sums replace: give --sig with it");
2716
+ if (values.sig !== undefined && (!URL.canParse(values.sig) || !["http:", "https:"].includes(new URL(values.sig).protocol)))
2717
+ badUsage(`--sig takes an http or https URL, not '${values.sig}'`);
2718
+ const key = values.key === undefined ? undefined : readKey(values.key);
2030
2719
  const maxSize = parseSize(values["max-size"] ?? DEFAULT_MAX_SIZE) ?? badUsage(`--max-size takes a size such as 500M or 2G, not '${values["max-size"]}'`);
2720
+ const release = spec === undefined ? undefined : await resolveRelease(spec, { fresh: values.fresh === true, asset: values.asset, key });
2721
+ const url = release?.asset.url ?? given;
2722
+ const pinned = values.sha256 !== undefined || values.sums !== undefined;
2723
+ const sums = values.sums ?? (pinned ? undefined : release?.sums);
2724
+ const digest = pinned ? undefined : release?.digest;
2725
+ const sig = values.sig ?? release?.sig;
2031
2726
  const created = values.output === undefined;
2032
- const dir = created ? mkdtempSync(join10(tmpdir(), "dl-")) : resolve5(values.output);
2033
- mkdirSync4(dir, { recursive: true });
2034
- const expectsFile = values.exec === true || values.bin !== undefined || values.extract === true;
2035
- const { file, verified } = await fetchChecked(url, dir, created, { maxSize, expectsFile, sha256: values.sha256?.toLowerCase(), sums: values.sums });
2727
+ const dir = created ? mkdtempSync2(join11(tmpdir2(), "dl-")) : resolve5(values.output);
2728
+ mkdirSync6(dir, { recursive: true });
2729
+ const expectsFile = release !== undefined || values.exec === true || values.bin !== undefined || values.extract === true;
2730
+ const { file, verified, signature } = await fetchChecked(url, dir, created, { maxSize, expectsFile, sha256: values.sha256?.toLowerCase(), sums, digest, sig, key });
2731
+ if (release !== undefined && !verified)
2732
+ warn(`${release.spec} ${release.tag} ships no checksums file and its forge gives no sha256 of ${release.asset.name}, so nothing checked it`);
2036
2733
  const last = lastSeen(url);
2037
- const report = { path: file.path, size: file.size, url: file.url, type: file.type, sha256: file.sha256, verified, seen: "first download" };
2734
+ const report = { path: file.path, size: file.size, url: file.url, type: file.type, sha256: file.sha256, verified, ...signature === undefined ? {} : { signature }, ...release === undefined ? {} : { release: releaseLine(release) }, seen: "first download" };
2038
2735
  if (last !== undefined && last.seen.sha256 === file.sha256)
2039
2736
  report.seen = `same as the download of ${formatAge(last.seen.at)}`;
2040
2737
  else if (last !== undefined)
2041
2738
  report.seen = `changed since the download of ${formatAge(last.seen.at)}, was ${last.seen.sha256.slice(0, 12)}`;
2042
2739
  if (last?.content !== undefined && last.seen.sha256 !== file.sha256 && file.text)
2043
- report.diff = await diff(last.content, file, values.json !== true);
2740
+ report.diff = await diff(last.content, file);
2044
2741
  remember(url, file);
2045
2742
  const extracted = values.extract === true || values.bin !== undefined && archiveSuffix(file.name) !== undefined;
2046
2743
  if (extracted)
@@ -2049,16 +2746,33 @@ async function get(args) {
2049
2746
  const source = report.extracted === undefined ? file.path : await pickBinary(report.extracted, values.bin === "" ? undefined : values.bin);
2050
2747
  const name = values.bin === "" ? basename5(source) : values.bin;
2051
2748
  report.installed = installBinary(source, name, values.force === true);
2052
- record({ kind: "bin", name, url, sha256: file.sha256, path: report.installed, at: new Date().toISOString() });
2749
+ record({ kind: "bin", name, url, sha256: file.sha256, path: report.installed, at: new Date().toISOString(), ...release === undefined ? checkedBy(file, values) : fromRelease(release, values) });
2053
2750
  }
2054
2751
  if (values.exec === true)
2055
2752
  report.script = summarize(await Bun.file(file.path).text());
2056
- print(report, url, values.json === true);
2753
+ print(report, given, values.json === true);
2057
2754
  if (values.exec !== true)
2058
2755
  return 0;
2059
2756
  if (!verified && values.yes !== true)
2060
- return fail("not run: no --sha256 or --sums pins this script", 1, `read ${file.path}, then: dl ${url} --exec --sha256 ${file.sha256}`);
2061
- return runScript(file, url, rest);
2757
+ return fail("not run: no --sha256, --sums or --sig pins this script", 1, `read ${file.path}, then: dl ${url} --exec --sha256 ${file.sha256}`);
2758
+ return runScript(file, url, rest, checkedBy(file, values));
2759
+ }
2760
+ function releaseLine(release) {
2761
+ return `${release.spec} ${release.tag}, published ${formatAge(release.published)}, ${release.asset.name}`;
2762
+ }
2763
+ function fromRelease(release, values) {
2764
+ const key = values.key !== undefined && existsSync8(values.key) ? resolve5(values.key) : values.key;
2765
+ return { release: release.pinned ?? release.spec, version: release.tag, released: release.published, ...values.asset === undefined ? {} : { asset: values.asset }, ...key === undefined ? {} : { key } };
2766
+ }
2767
+ function checkedBy(file, values) {
2768
+ const key = values.key !== undefined && existsSync8(values.key) ? resolve5(values.key) : values.key;
2769
+ const fields = { sums: values.sums, sig: values.sig, key, etag: file.etag, lastModified: file.lastModified };
2770
+ return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
2771
+ }
2772
+ function listedSum(sums, checks, url, name, signed) {
2773
+ if (sums === undefined)
2774
+ return;
2775
+ return checks.digest !== undefined && !signed ? sumFor(new TextDecoder().decode(sums), name, pathUnder(checks.sums, url)) : sumIn(sums, checks.sums, url, name);
2062
2776
  }
2063
2777
  async function fetchChecked(url, dir, created, checks) {
2064
2778
  let file;
@@ -2066,36 +2780,52 @@ async function fetchChecked(url, dir, created, checks) {
2066
2780
  file = await download(url, dir, checks.maxSize);
2067
2781
  if (file.html && (checks.expectsFile || !HTML_EXTENSIONS.has(extname(file.name).toLowerCase())))
2068
2782
  fail(`${url} answered an HTML page, not a file`, 1);
2069
- const expected = checks.sha256 ?? (checks.sums === undefined ? undefined : await fetchSum(checks.sums, file.name));
2783
+ const sums = checks.sums === undefined ? undefined : await fetchSums(checks.sums);
2784
+ const signed = checks.sig === undefined || checks.key === undefined ? undefined : await verifySignature(sums ?? file.path, checks.sig, checks.key);
2785
+ const expected = checks.sha256 ?? listedSum(sums, checks, url, file.name, signed !== undefined) ?? checks.digest;
2070
2786
  if (expected !== undefined && expected !== file.sha256)
2071
2787
  fail(`sha256 mismatch for ${file.name}: expected ${expected}, got ${file.sha256}; the file was deleted`, 1);
2072
- return { file, verified: expected !== undefined };
2788
+ return { file, verified: expected !== undefined || signed !== undefined, ...signed === undefined ? {} : { signature: signed } };
2073
2789
  } catch (error) {
2074
2790
  if (file !== undefined)
2075
- rmSync4(file.path, { force: true });
2791
+ rmSync5(file.path, { force: true });
2076
2792
  if (created)
2077
- rmSync4(dir, { recursive: true, force: true });
2793
+ rmSync5(dir, { recursive: true, force: true });
2078
2794
  throw error;
2079
2795
  }
2080
2796
  }
2081
- async function diff(last, file, colored) {
2797
+ async function diff(last, file) {
2082
2798
  if (Bun.which("git") === null)
2083
2799
  return "";
2084
- const color = colored && takesControlCodes(process19.stdout) ? "--color=always" : "--no-color";
2085
- const child = Bun.spawn(["git", "diff", "--no-index", color, "--", last, file.path], { stdin: "ignore", stdout: "pipe", stderr: "ignore" });
2800
+ const child = Bun.spawn(["git", "diff", "--no-index", "--no-color", "--", last, file.path], { stdin: "ignore", stdout: "pipe", stderr: "ignore" });
2086
2801
  const lines = (await child.stdout.text()).trimEnd().split(`
2087
2802
  `);
2088
2803
  await child.exited;
2089
- const hunks = lines.findIndex((line) => Bun.stripANSI(line).startsWith("@@"));
2804
+ const hunks = lines.findIndex((line) => line.startsWith("@@"));
2090
2805
  return hunks === -1 ? "" : ["--- last", `+++ ${file.name}`, ...lines.slice(hunks)].join(`
2091
2806
  `);
2092
2807
  }
2808
+ function coloredDiff(text) {
2809
+ const colors = paint(process22.stdout);
2810
+ return text.split(`
2811
+ `).map((raw, index) => {
2812
+ const line = escapeControls(raw);
2813
+ if (index < 2)
2814
+ return colors.bold(line);
2815
+ if (line.startsWith("@@"))
2816
+ return colors.cyan(line);
2817
+ if (line.startsWith("+"))
2818
+ return colors.green(line);
2819
+ return line.startsWith("-") ? colors.red(line) : line;
2820
+ }).join(`
2821
+ `);
2822
+ }
2093
2823
  async function extract(file) {
2094
2824
  const suffix = archiveSuffix(file.name) ?? fail(`${file.name} is no archive arc can extract`, 1);
2095
- const folder = join10(file.path, "..", file.name.slice(0, -suffix.length) || "extracted");
2096
- if (existsSync7(folder))
2825
+ const folder = join11(file.path, "..", file.name.slice(0, -suffix.length) || "extracted");
2826
+ if (existsSync8(folder))
2097
2827
  return fail(`'${folder}' already exists`, 1);
2098
- mkdirSync4(folder);
2828
+ mkdirSync6(folder);
2099
2829
  return await extractArchive(file.path, folder) !== 0 ? fail(`extracting ${file.name} failed`, 1) : folder;
2100
2830
  }
2101
2831
  function print(report, url, json) {
@@ -2108,67 +2838,75 @@ function print(report, url, json) {
2108
2838
  ["size", formatSize(report.size)],
2109
2839
  ...report.url === url ? [] : [["url", report.url]],
2110
2840
  ["type", report.type === "" ? "-" : report.type],
2841
+ ...report.release === undefined ? [] : [["release", report.release]],
2111
2842
  ["sha256", `${report.sha256}${report.verified ? " verified" : ""}`],
2843
+ ...report.signature === undefined ? [] : [["signature", `${report.signature}, verified`]],
2112
2844
  ["seen", report.seen],
2113
2845
  ...report.extracted === undefined ? [] : [["extracted", report.extracted]],
2114
2846
  ...report.installed === undefined ? [] : [["installed", report.installed]],
2115
2847
  ...report.installed === undefined || binDirOnPath() ? [] : [["note", `${binDir()} is not on PATH`]]
2116
2848
  ];
2117
- console.log(table(rows));
2849
+ console.log(table(rows.map(([name = "", value = ""]) => [name, escapeControls(value)])));
2118
2850
  if (report.diff !== undefined && report.diff !== "")
2119
2851
  console.log(`
2120
- ${report.diff}`);
2852
+ ${coloredDiff(report.diff)}`);
2121
2853
  if (report.script === undefined)
2122
2854
  return;
2123
2855
  const { findings, env } = report.script;
2124
2856
  console.log(findings.length === 0 ? `
2125
2857
  script: fetches, sudo, removes, profile, system and runs found nowhere` : `
2126
2858
  script:
2127
- ${table(findings.map(({ line, does, text }) => [`line ${line}`, does, truncate(text, LINE_WIDTH)]))}`);
2859
+ ${table(findings.map(({ line, does, text }) => [`line ${line}`, does, truncate(escapeControls(text), LINE_WIDTH)]))}`);
2128
2860
  if (env.length > 0)
2129
2861
  console.log(`reads: ${env.join(", ")}`);
2130
2862
  }
2131
- async function runScript(file, url, args) {
2863
+ async function runScript(file, url, args, checked) {
2132
2864
  const shebang = (await Bun.file(file.path).text()).startsWith("#!");
2133
2865
  chmodSync2(file.path, 448);
2134
2866
  const code = await Bun.spawn(shebang ? [file.path, ...args] : ["sh", file.path, ...args], { stdin: "inherit", stdout: "inherit", stderr: "inherit" }).exited;
2135
2867
  if (code !== 0)
2136
2868
  return fail(`the script exited ${code}`, 1);
2137
2869
  const { host, pathname } = new URL(url);
2138
- record({ kind: "script", name: `${host}${pathname}`, url, sha256: file.sha256, at: new Date().toISOString() });
2870
+ record({ kind: "script", name: `${host}${pathname}`, url, sha256: file.sha256, at: new Date().toISOString(), ...checked, ...args.length > 0 ? { args } : {} });
2139
2871
  return 0;
2140
2872
  }
2141
2873
  var USAGE = `dl [options] <url> [-- <script args>]: downloads a file into a new folder of its own, checks its sha256, then extracts it, installs it as a command or runs it as a script
2142
2874
 
2143
- Without -o the file lands in a new folder under the temp folder; with -o in that folder, created if missing, where nothing is overwritten.
2144
- Prints where the file went, its size, final URL, type and sha256, and how it compares with the last download of the same URL: a text file that changed since shows its diff.
2145
- --sha256 or --sums checks the file, which is deleted on a mismatch. An HTML page arriving where a file was expected fails, as does a download over --max-size.
2146
- --extract unpacks an archive into a new folder beside it, through arc's extractor. --bin installs the file, or the one executable its archive holds, in ~/.local/bin.
2147
- --exec lists what the script does (what it fetches, sudo, recursive removals, shell profiles and system folders it touches, code it runs in a shell, the variables it reads) and runs it only when --sha256 or --sums pins it, the content then being the one that was read, or with --yes. Arguments after -- go to the script.
2875
+ <url> is an http or https URL, or a release: gh:owner/repo on GitHub, fj:owner/repo on git.kaynooo.fr, with @tag for one release. A release is the newest at least two weeks old unless --fresh; its asset the one built for this OS and arch, or the one --asset names; it is checked against the checksums file the release ships, else the sha256 the forge gives, and --key alone finds the signature beside it.
2876
+ Without -o the file lands in a new folder under the temp folder. It prints where the file went, its size, final URL, type and sha256, and how it compares with the last download of the same URL (a changed text file shows its diff).
2877
+ An HTML page arriving where a file was expected fails, as does a download over --max-size.
2878
+ --sig checks a detached signature with --key: of the file, or of the checksums file when --sums names one. A gpg key is a fingerprint of your keyring or a key file, a minisign key its string or file, a cosign key its PEM file; the tool has to be on PATH.
2879
+ --exec lists what the script does and runs it only when --sha256, --sums or --sig pins it, or with --yes; arguments after -- go to the script.
2148
2880
  --bin and --exec record what they installed or ran in the ledger dl ls lists.`, EXITS, OPTIONS, SHA256, DEFAULT_MAX_SIZE = "2G", HTML_EXTENSIONS, LINE_WIDTH = 120;
2149
2881
  var init_get = __esm(() => {
2150
2882
  init_extract();
2151
2883
  init_src();
2152
2884
  init_download();
2153
2885
  init_install();
2886
+ init_release();
2154
2887
  init_script();
2888
+ init_signature();
2155
2889
  init_state();
2156
2890
  init_sums();
2157
2891
  EXITS = [
2158
2892
  [0, "downloaded, and extracted, installed or run as asked"],
2159
- [1, "an unreachable URL, an error status, a sha256 mismatch, an HTML page in place of a file, a download over --max-size, a script nothing pins, or one that failed"],
2893
+ [1, "an unreachable URL, an error status, a release with no asset for this machine, a sha256 mismatch, a signature that does not verify or a missing tool to check it, an HTML page in place of a file, a download over --max-size, a script nothing pins, or one that failed"],
2160
2894
  [2, "a usage error"]
2161
2895
  ];
2162
2896
  OPTIONS = {
2163
2897
  output: { type: "string", short: "o", description: "the folder to download into, created if missing, instead of a new one under the temp folder" },
2164
2898
  sha256: { type: "string", description: "the sha256 the file must have", conflicts: ["sums"] },
2165
2899
  sums: { type: "string", description: "the URL of a checksums file (SHA256SUMS) giving the file's sha256" },
2900
+ sig: { type: "string", description: "the URL of a detached signature of the file, or of the --sums file when there is one" },
2901
+ key: { type: "string", description: "the key --sig is checked with: a gpg fingerprint or key file, a minisign key or key file, a cosign PEM file" },
2166
2902
  extract: { type: "boolean", short: "x", description: "unpack the archive into a new folder beside it" },
2167
2903
  bin: { type: "string", optional: { bare: "" }, description: "install the file, or the one executable its archive holds, in ~/.local/bin, under the name given or its own", conflicts: ["exec"] },
2168
2904
  force: { type: "boolean", description: "let --bin replace a command of the same name" },
2169
- exec: { type: "boolean", description: "run the file as a script, once --sha256 or --sums pins it, or with --yes" },
2905
+ exec: { type: "boolean", description: "run the file as a script, once --sha256, --sums or --sig pins it, or with --yes" },
2170
2906
  yes: { type: "boolean", description: "run an --exec script that nothing pins" },
2171
2907
  "max-size": { type: "string", description: "the largest download taken, 2G by default" },
2908
+ fresh: { type: "boolean", description: "take a release under two weeks old" },
2909
+ asset: { type: "string", description: "the release asset to take, a part of its name or a glob, when the one for this machine cannot be told" },
2172
2910
  json: jsonOption()
2173
2911
  };
2174
2912
  SHA256 = /^[0-9a-f]{64}$/i;
@@ -2204,17 +2942,159 @@ var init_ls = __esm(() => {
2204
2942
  EXITS2 = [[0, "listed, even nothing"], [2, "a usage error"]];
2205
2943
  });
2206
2944
 
2945
+ // src/update.ts
2946
+ var exports_update = {};
2947
+ __export(exports_update, {
2948
+ outdated: () => outdated,
2949
+ update: () => update
2950
+ });
2951
+ async function releaseFreshness(entry, release) {
2952
+ try {
2953
+ const latest = await latestRelease(parseSpec(release));
2954
+ return latest !== undefined && Date.parse(latest.published) > Date.parse(entry.released ?? "") ? { state: "changed", now: latest.tag } : { state: "current" };
2955
+ } catch (error) {
2956
+ return { state: "unreachable", error: error instanceof Error ? error.message : String(error) };
2957
+ }
2958
+ }
2959
+ async function freshness(entry) {
2960
+ if (entry.release !== undefined)
2961
+ return releaseFreshness(entry, entry.release);
2962
+ const headers = { "accept-encoding": "identity" };
2963
+ if (entry.etag !== undefined)
2964
+ headers["if-none-match"] = entry.etag;
2965
+ else if (entry.lastModified !== undefined)
2966
+ headers["if-modified-since"] = entry.lastModified;
2967
+ try {
2968
+ const response = await fetch(entry.url, { headers, decompress: false });
2969
+ if (response.status === 304)
2970
+ return { state: "current" };
2971
+ if (!response.ok) {
2972
+ await response.body?.cancel();
2973
+ return { state: "unreachable", error: `answered ${response.status} ${response.statusText}`.trimEnd() };
2974
+ }
2975
+ const hasher = new Bun.CryptoHasher("sha256");
2976
+ let size = 0;
2977
+ for await (const chunk of response.body ?? new ReadableStream) {
2978
+ size += chunk.length;
2979
+ if (size > MAX_BYTES)
2980
+ return { state: "unreachable", error: `goes over ${formatSize(MAX_BYTES)}` };
2981
+ hasher.update(chunk);
2982
+ }
2983
+ const now = hasher.digest("hex");
2984
+ return now === entry.sha256 ? { state: "current" } : { state: "changed", now };
2985
+ } catch (error) {
2986
+ return { state: "unreachable", error: error instanceof Error ? error.message : String(error) };
2987
+ }
2988
+ }
2989
+ async function checkAll(names, bins) {
2990
+ const ledger = readLedger().filter((entry) => !bins || entry.kind === "bin").sort((a, b) => a.name.localeCompare(b.name));
2991
+ const unknown = names.filter((name) => !ledger.some((entry) => entry.name === name));
2992
+ if (unknown.length > 0)
2993
+ fail(`dl installed or ran nothing named ${unknown.join(", ")}`, 2, "dl ls lists what it did");
2994
+ const entries = names.length === 0 ? ledger : ledger.filter((entry) => names.includes(entry.name));
2995
+ const checked = [];
2996
+ for (let at = 0;at < entries.length; at += AT_ONCE)
2997
+ checked.push(...await Promise.all(entries.slice(at, at + AT_ONCE).map(async (entry) => ({ entry, freshness: await freshness(entry) }))));
2998
+ return checked;
2999
+ }
3000
+ function said(freshness, entry) {
3001
+ if (freshness.state === "changed")
3002
+ return entry.version === undefined ? `changed, ${entry.sha256.slice(0, 12)} now ${freshness.now.slice(0, 12)}` : `changed, ${entry.version} now ${freshness.now}`;
3003
+ return freshness.state === "unreachable" ? `unreachable: ${freshness.error}` : "current";
3004
+ }
3005
+ async function outdated(args) {
3006
+ const { values, positionals } = parse(args, OUTDATED_USAGE, { bins: { type: "boolean", description: "only the commands --bin installed" }, json: jsonOption("[{name, kind, url, at, sha256, version?, state, now?, error?}], state current, changed or unreachable, now a release's tag or a sha256") }, {
3007
+ positionals: ["[name...]"],
3008
+ exits: OUTDATED_EXITS,
3009
+ replaces: "checking by hand whether a tool installed from a URL has a newer build",
3010
+ examples: ["dl outdated", ["dl outdated --bins", "the installed commands only"]]
3011
+ });
3012
+ const checked = await checkAll(positionals, values.bins === true);
3013
+ const behind = checked.filter(({ freshness }) => freshness.state !== "current");
3014
+ if (values.json === true) {
3015
+ printJson(checked.map(({ entry, freshness }) => ({ name: entry.name, kind: entry.kind, url: entry.url, at: entry.at, sha256: entry.sha256, ...entry.version === undefined ? {} : { version: entry.version }, ...freshness })));
3016
+ return behind.length === 0 ? 0 : 1;
3017
+ }
3018
+ if (behind.length === 0) {
3019
+ console.log(checked.length === 0 ? "nothing installed or run through dl yet" : `all ${checked.length} current`);
3020
+ return 0;
3021
+ }
3022
+ const changed = behind.filter(({ freshness }) => freshness.state === "changed").map(({ entry }) => entry.name);
3023
+ console.log(table([["name", "kind", "installed", "source"], ...behind.map(({ entry, freshness }) => [entry.name, entry.kind, formatAge(entry.at), said(freshness, entry)])], { header: true }));
3024
+ if (changed.length > 0)
3025
+ console.log(`
3026
+ update them: dl update ${changed.join(" ")}`);
3027
+ return 1;
3028
+ }
3029
+ function argvOf(entry, yes) {
3030
+ if (entry.release !== undefined)
3031
+ return [entry.release, "--bin", entry.name, "--force", ...entry.asset === undefined ? [] : ["--asset", entry.asset], ...entry.key === undefined ? [] : ["--key", entry.key]];
3032
+ const checks = [...entry.sums === undefined ? [] : ["--sums", entry.sums], ...entry.sig === undefined || entry.key === undefined ? [] : ["--sig", entry.sig, "--key", entry.key]];
3033
+ if (entry.kind === "bin")
3034
+ return [entry.url, "--bin", entry.name, "--force", ...checks];
3035
+ return [entry.url, "--exec", ...checks, ...yes ? ["--yes"] : [], ...entry.args === undefined ? [] : ["--", ...entry.args]];
3036
+ }
3037
+ async function update(args) {
3038
+ const { values, positionals } = parse(args, UPDATE_USAGE, { yes: { type: "boolean", description: "run a changed script that no checksums file or signature pins" } }, {
3039
+ positionals: ["[name...]"],
3040
+ exits: UPDATE_EXITS,
3041
+ examples: [["dl update", "everything that changed"], ["dl update tool", "one command"]]
3042
+ });
3043
+ const checked = await checkAll(positionals, false);
3044
+ const changed = checked.filter(({ freshness }) => freshness.state === "changed");
3045
+ let code = 0;
3046
+ for (const { entry, freshness } of checked) {
3047
+ if (freshness.state === "unreachable") {
3048
+ printError("dl update", `${entry.name}: ${entry.release ?? entry.url} ${freshness.error}`);
3049
+ code = 1;
3050
+ }
3051
+ }
3052
+ if (changed.length === 0) {
3053
+ console.log("nothing changed");
3054
+ return code;
3055
+ }
3056
+ for (const { entry } of changed) {
3057
+ console.log(`
3058
+ updating ${entry.name}`);
3059
+ try {
3060
+ code = Math.max(code, await get(argvOf(entry, values.yes === true)));
3061
+ } catch (error) {
3062
+ if (!(error instanceof Exit))
3063
+ throw error;
3064
+ printError("dl update", `${entry.name}: ${error.message}`, error.hint);
3065
+ code = 1;
3066
+ }
3067
+ }
3068
+ return code;
3069
+ }
3070
+ var AT_ONCE = 4, MAX_BYTES, OUTDATED_USAGE = `dl outdated [name...] [options]: asks the source of each command dl installed and script it ran whether it changed since
3071
+
3072
+ A server that gives an ETag or Last-Modified answers without sending the file again; otherwise the file is downloaded and its sha256 compared. A command installed from a release is behind once a release published after it is two weeks old.`, OUTDATED_EXITS, UPDATE_USAGE = `dl update [name...] [options]: downloads again what changed of the commands dl installed and the scripts it ran, checked as it was the first time, then installs or runs it
3073
+
3074
+ Without names, every one whose source changed. A checksums file or a signature given at install is checked again; a sha256 given at install cannot pin a new file, so a script it pinned runs only with --yes. A script shows its diff and what it does, and runs with the arguments it had.`, UPDATE_EXITS;
3075
+ var init_update = __esm(() => {
3076
+ init_src();
3077
+ init_get();
3078
+ init_release();
3079
+ init_state();
3080
+ MAX_BYTES = parseSize(DEFAULT_MAX_SIZE);
3081
+ OUTDATED_EXITS = [[0, "every one is current"], [1, "one changed, or its source cannot be reached"], [2, "a usage error"]];
3082
+ UPDATE_EXITS = [[0, "every one updated, or nothing changed"], [1, "one failed to download, check, install or run"], [2, "a usage error"]];
3083
+ });
3084
+
2207
3085
  // src/cli.ts
2208
3086
  init_src();
2209
- import process20 from "process";
2210
- process20.exitCode = await runCli({
3087
+ import process23 from "process";
3088
+ process23.exitCode = await runCli({
2211
3089
  name: "dl",
2212
3090
  about: "downloads a file into a folder of its own, checks its sha256, then extracts it, installs it as a command or runs it as a script once it is pinned",
2213
3091
  replaces: "curl -fsSL <url> | sh, curl -LO then sha256sum -c by hand, and unpacking a release to copy its binary into ~/.local/bin",
2214
- examples: [["dl https://bun.sh/install", "download a script to read it"], ["dl https://bun.sh/install --exec --sha256 <sha>", "run the script that was read"], ["dl https://example.com/tool.tar.gz --sums https://example.com/SHA256SUMS --bin tool", "a checked binary, installed"], ["dl ls", "what dl installed or ran"]],
3092
+ examples: [["dl https://bun.sh/install", "download a script to read it"], ["dl https://bun.sh/install --exec --sha256 <sha>", "run the script that was read"], ["dl https://example.com/tool.tar.gz --sums https://example.com/SHA256SUMS --bin tool", "a checked binary, installed"], ["dl ls", "what dl installed or ran"], ["dl outdated", "what changed at its source"], ["dl update", "install it again"]],
2215
3093
  defaultCommand: "get",
2216
3094
  commands: {
2217
3095
  get: { summary: "download a file, check it, then extract, install or run it as asked", run: async (args) => (await Promise.resolve().then(() => (init_get(), exports_get))).get(args) },
2218
- ls: { summary: "list the commands dl installed and the scripts it ran", run: async (args) => (await Promise.resolve().then(() => (init_ls(), exports_ls))).ls(args) }
3096
+ ls: { summary: "list the commands dl installed and the scripts it ran", run: async (args) => (await Promise.resolve().then(() => (init_ls(), exports_ls))).ls(args) },
3097
+ outdated: { summary: "list the commands and scripts whose source changed since", run: async (args) => (await Promise.resolve().then(() => (init_update(), exports_update))).outdated(args) },
3098
+ update: { summary: "download, check and install or run again what changed", run: async (args) => (await Promise.resolve().then(() => (init_update(), exports_update))).update(args) }
2219
3099
  }
2220
3100
  });