@kaynooo/cli-dev 0.5.0 → 0.5.2

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 (2) hide show
  1. package/dist/cli.js +126 -62
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process11 from "process";
5
+ import process12 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process6 from "process";
8
8
  import { parseArgs } from "util";
@@ -109,6 +109,23 @@ var STATUS_WORDS = {
109
109
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
110
110
 
111
111
  // ../kit/src/format.ts
112
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
113
+ function formatSeconds(total) {
114
+ let rest = Math.max(0, Math.round(total));
115
+ const amounts = UNITS.map(([unit, size]) => {
116
+ const amount = Math.floor(rest / size);
117
+ rest -= amount * size;
118
+ return `${amount}${unit}`;
119
+ });
120
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
121
+ if (first === -1)
122
+ return "0s";
123
+ const next = amounts[first + 1];
124
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
125
+ }
126
+ function formatDuration(ms) {
127
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
128
+ }
112
129
  function upTo(text, separator) {
113
130
  const end = text.indexOf(separator);
114
131
  return end === -1 ? text : text.slice(0, end);
@@ -123,24 +140,20 @@ function printJson(value) {
123
140
 
124
141
  // ../kit/src/help.ts
125
142
  import process5 from "process";
126
- var OPTIONAL = /\[[^\]]+\]/g;
143
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
127
144
  var USAGE_PREFIX = /^usage:\s*/i;
128
145
  var FULL_STOP = /\.$/;
129
146
  function usageLine(usage, colors = paint(process5.stdout)) {
130
147
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
131
148
  }
132
- function helpText(usage, options, colors = paint(process5.stdout), { examples = [], replaces, exits = [] } = {}) {
133
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
149
+ function helpText(usage, options, colors = paint(process5.stdout), { examples = [], exits = [] } = {}) {
150
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
134
151
  `);
135
152
  }
136
153
  function exitRows(exits, colors = paint(process5.stdout)) {
137
154
  if (exits.length === 0)
138
155
  return [];
139
- const width = Math.max(...exits.map(([code]) => String(code).length));
140
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
141
- }
142
- function replacesRows(replaces, colors = paint(process5.stdout)) {
143
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
156
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
144
157
  }
145
158
  function wantsHelpJson(env = process5.env) {
146
159
  return env.KIT_HELP === "json";
@@ -166,29 +179,40 @@ function exampleRows(examples, colors = paint(process5.stdout)) {
166
179
  return [];
167
180
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
168
181
  }
182
+ var MAX_INLINE_CHOICES = 24;
169
183
  function optionRows(options, colors = paint(process5.stdout)) {
170
184
  const rows = Object.entries(options).map(([name, option]) => {
171
185
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
172
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
186
+ const choices = option.choices?.join("|");
187
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
188
+ const named = inline ? `<${choices}>` : "<value>";
173
189
  const placeholder = option.optional === undefined ? named : `[${named}]`;
174
190
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
175
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
191
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
192
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
176
193
  });
177
194
  const width = Math.max(0, ...rows.map((row) => row.width));
178
195
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
179
196
  }
180
197
 
181
198
  // ../kit/src/text.ts
182
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
183
199
  function distance(a, b) {
184
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
185
- for (const [i, left] of [...a].entries()) {
200
+ const left = [...a];
201
+ const right = [...b];
202
+ let before = [];
203
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
204
+ for (const [i, x] of left.entries()) {
186
205
  const current = [i + 1];
187
- for (const [j, right] of [...b].entries())
188
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
206
+ for (const [j, y] of right.entries()) {
207
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
208
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
209
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
210
+ current.push(cost);
211
+ }
212
+ before = previous;
189
213
  previous = current;
190
214
  }
191
- return previous[b.length] ?? 0;
215
+ return previous[right.length] ?? 0;
192
216
  }
193
217
  function closest(name, names) {
194
218
  const started = names.find((known) => known.startsWith(name));
@@ -481,13 +505,31 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
481
505
  // ../kit/src/cli.ts
482
506
  import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
483
507
  import { dirname as dirname2, join as join2 } from "path";
484
- import process9 from "process";
508
+ import process10 from "process";
509
+
510
+ // ../kit/src/notify.ts
511
+ import process8 from "process";
512
+ var NOTIFY_AFTER_MS = 1e4;
513
+ var CANCELLED = 130;
514
+ function base64(text) {
515
+ return Buffer.from(text).toString("base64");
516
+ }
517
+ function notification(title, body, env = process8.env) {
518
+ const id = `kit${process8.pid}`;
519
+ 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\\`];
520
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
521
+ }
522
+ function notifyEnd(command, code, ms, { stream = process8.stderr, env = process8.env } = {}) {
523
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
524
+ return;
525
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
526
+ }
485
527
 
486
528
  // ../kit/src/usage.ts
487
529
  import { appendFileSync, mkdirSync } from "fs";
488
530
  import { homedir } from "os";
489
531
  import { dirname, isAbsolute, join } from "path";
490
- import process8 from "process";
532
+ import process9 from "process";
491
533
 
492
534
  // ../kit/src/logs.ts
493
535
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -501,14 +543,14 @@ var usageError;
501
543
  function noteUsageError(message) {
502
544
  usageError = message;
503
545
  }
504
- function stateHome(env = process8.env) {
546
+ function stateHome(env = process9.env) {
505
547
  const dir = env.XDG_STATE_HOME;
506
548
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
507
549
  }
508
- function usagePath(env = process8.env) {
550
+ function usagePath(env = process9.env) {
509
551
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
510
552
  }
511
- function usageRecorded(env = process8.env) {
553
+ function usageRecorded(env = process9.env) {
512
554
  const off = env.KAYNOOO_CLI_NO_USAGE;
513
555
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
514
556
  }
@@ -522,7 +564,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
522
564
  usageError = undefined;
523
565
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
524
566
  }
525
- function recordUsage(entry, env = process8.env) {
567
+ function recordUsage(entry, env = process9.env) {
526
568
  if (!usageRecorded(env))
527
569
  return;
528
570
  try {
@@ -599,7 +641,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
599
641
  header(colors, summary),
600
642
  "",
601
643
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
602
- ...replacesRows(replaces, colors),
603
644
  "",
604
645
  ...await commandRows(commands, colors),
605
646
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -613,8 +654,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
613
654
  `);
614
655
  }
615
656
  function printError(prefix, message, hint, cause) {
616
- const colors = paint(process9.stderr);
617
- const styled = takesControlCodes(process9.stderr);
657
+ const colors = paint(process10.stderr);
658
+ const styled = takesControlCodes(process10.stderr);
618
659
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
619
660
  const under = (label, text, tint) => text === undefined ? "" : `
620
661
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -657,11 +698,11 @@ async function dispatch(level, typed, { version, redact }) {
657
698
  }
658
699
  }
659
700
  if (name === undefined && level.path.length > 1) {
660
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
701
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stderr));
661
702
  return 2;
662
703
  }
663
704
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
664
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
705
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stdout));
665
706
  return 0;
666
707
  }
667
708
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -778,7 +819,11 @@ async function printCandidates(found) {
778
819
  return 0;
779
820
  }
780
821
  function packageVersion(entry = Bun.main) {
781
- for (let dir = dirname2(realpathSync2(entry));; dir = dirname2(dir)) {
822
+ let resolved = entry;
823
+ try {
824
+ resolved = realpathSync2(entry);
825
+ } catch {}
826
+ for (let dir = dirname2(resolved);; dir = dirname2(dir)) {
782
827
  try {
783
828
  const { version } = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
784
829
  if (typeof version === "string")
@@ -792,10 +837,13 @@ async function runCli(cli, argv = scriptArgs()) {
792
837
  const version = cli.version ?? packageVersion();
793
838
  if (argv[0] === COMPLETE)
794
839
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
840
+ const started = performance.now();
795
841
  const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
842
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
843
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
796
844
  if (cli.usage !== false) {
797
845
  try {
798
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
846
+ recordUsage(usageEntry(cli.name, command, argv, code));
799
847
  } catch {}
800
848
  }
801
849
  return code;
@@ -842,6 +890,15 @@ var ALGORITHMS = ["sha256", "sha1", "md5", "sha512"];
842
890
  function hashHex(algorithm, bytes) {
843
891
  return new Bun.CryptoHasher(algorithm).update(bytes).digest("hex");
844
892
  }
893
+ async function hashStream(algorithm, stream) {
894
+ const hasher = new Bun.CryptoHasher(algorithm);
895
+ let bytes = 0;
896
+ for await (const chunk of stream) {
897
+ hasher.update(chunk);
898
+ bytes += chunk.length;
899
+ }
900
+ return { digest: hasher.digest("hex"), bytes };
901
+ }
845
902
 
846
903
  // src/ids.ts
847
904
  var CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
@@ -882,7 +939,7 @@ async function publicIp(family, service = IP_SERVICE) {
882
939
  }
883
940
 
884
941
  // src/time.ts
885
- var UNITS = [["d", 86400000], ["h", 3600000], ["m", 60000], ["s", 1000]];
942
+ var UNITS2 = [["d", 86400000], ["h", 3600000], ["m", 60000], ["s", 1000]];
886
943
  var DURATION_UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
887
944
  function parts(ms, timeZone) {
888
945
  const formatter = new Intl.DateTimeFormat("en-US", { timeZone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", timeZoneName: "longOffset" });
@@ -903,7 +960,7 @@ function offsetAt(ms, timeZone) {
903
960
  function humanDuration(ms) {
904
961
  let rest = Math.floor(Math.abs(ms) / 1000) * 1000;
905
962
  const out = [];
906
- for (const [name, size] of UNITS) {
963
+ for (const [name, size] of UNITS2) {
907
964
  const count = Math.floor(rest / size);
908
965
  if (count > 0) {
909
966
  out.push(`${count}${name}`);
@@ -1076,15 +1133,15 @@ async function bytesInput(argument, what) {
1076
1133
  return new Uint8Array(await Bun.stdin.arrayBuffer());
1077
1134
  }
1078
1135
  function printRows(rows) {
1079
- const { cyan } = paint(process11.stdout);
1136
+ const { cyan } = paint(process12.stdout);
1080
1137
  const width = Math.max(...rows.map(([label]) => label.length));
1081
1138
  for (const [label, value] of rows)
1082
1139
  console.log(`${cyan(label.padEnd(width))} ${value}`);
1083
1140
  }
1084
1141
  var PASSWORD_USAGE = `dev password [length] [format] [-b|--bcrypt [password]]: a random password of <length> bytes (default ${DEFAULT_LENGTH}) as hex, base64 (default) or base64url
1085
1142
 
1086
- Printed on stdout and copied to the clipboard when a tool for it (wl-copy, xclip, xsel, pbcopy) exists (the copy is said on stderr). With --bcrypt it is the bcrypt hash (cost 10) that prints: of the password given, or of a generated one, which then prints on stderr and is the one copied. Bun writes bcrypt as $2b$, the hash prints with the $2y$ prefix htpasswd -B writes, the one Apache, nginx and traefik basic auth all accept.
1087
- Exits 0 when it printed the password or hash, 2 on a usage error.`;
1143
+ Printed on stdout and copied to the clipboard when a tool for it (wl-copy, xclip, xsel, pbcopy) exists (the copy is said on stderr). With --bcrypt it is the bcrypt hash (cost 10) that prints: of the password given, or of a generated one, which then prints on stderr and is the one copied. Bun writes bcrypt as $2b$, the hash prints with the $2y$ prefix htpasswd -B writes, the one Apache, nginx and traefik basic auth all accept.`;
1144
+ var PASSWORD_EXITS = [[0, "it printed the password or hash"], [2, "a usage error"]];
1088
1145
  var PASSWORD_OPTIONS = {
1089
1146
  bcrypt: { type: "string", short: "b", optional: { bare: "" }, description: "print the bcrypt hash of the password given, or of a generated one" },
1090
1147
  "no-copy": { type: "boolean", description: "leave the clipboard alone" },
@@ -1093,6 +1150,7 @@ var PASSWORD_OPTIONS = {
1093
1150
  var FORMAT_NOTES = { hex: "hexadecimal", base64: "base64", base64url: "url-safe base64" };
1094
1151
  async function password(args) {
1095
1152
  const { values, positionals } = parse(args, PASSWORD_USAGE, PASSWORD_OPTIONS, {
1153
+ exits: PASSWORD_EXITS,
1096
1154
  positionals: ["[length]", "[format]"],
1097
1155
  candidates: { "[length]": () => ["16", "24", "32", "48", "64"], "[format]": () => FORMATS.map((format) => [format, FORMAT_NOTES[format]]) },
1098
1156
  replaces: 'openssl rand -base64 32 and htpasswd -bnBC 10 "" <password>',
@@ -1111,7 +1169,7 @@ async function password(args) {
1111
1169
  return 0;
1112
1170
  }
1113
1171
  if (copied)
1114
- console.error(paint(process11.stderr).dim("copied to clipboard"));
1172
+ console.error(paint(process12.stderr).dim("copied to clipboard"));
1115
1173
  if (hash !== undefined && given === undefined)
1116
1174
  console.error(secret);
1117
1175
  console.log(hash ?? secret);
@@ -1119,14 +1177,15 @@ async function password(args) {
1119
1177
  }
1120
1178
  var JWT_USAGE = `dev jwt [token]: the header and payload of a JWT, with iat, nbf and exp as local and UTC dates and how far from now
1121
1179
 
1122
- The token is the argument or what is piped on stdin, a leading "Bearer " is ignored. The signature is not verified.
1123
- Exits 0 when it decoded the token, 1 when it is not a JWT, 2 on a usage error.`;
1180
+ The token is the argument or what is piped on stdin, a leading "Bearer " is ignored. The signature is not verified.`;
1181
+ var JWT_EXITS = [[0, "it decoded the token"], [1, "it is not a JWT"], [2, "a usage error"]];
1124
1182
  var JWT_OPTIONS = {
1125
1183
  zone: ZONE_OPTION,
1126
1184
  json: jsonOption("{header, payload, claims: [{claim, epoch, local, utc, relative}], signatureBytes}")
1127
1185
  };
1128
1186
  async function jwt(args) {
1129
1187
  const { values, positionals } = parse(args, JWT_USAGE, JWT_OPTIONS, {
1188
+ exits: JWT_EXITS,
1130
1189
  positionals: ["[token]"],
1131
1190
  replaces: "pasting a token into jwt.io or decoding its segments with base64 and jq",
1132
1191
  examples: ["dev jwt eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDAwMDAwMDB9.c2ln", ["pbpaste | dev jwt --json", "for a script"]]
@@ -1139,7 +1198,7 @@ async function jwt(args) {
1139
1198
  printJson({ header: decoded.header, payload: decoded.payload, claims, signatureBytes: decoded.signatureBytes });
1140
1199
  return 0;
1141
1200
  }
1142
- const { bold } = paint(process11.stdout);
1201
+ const { bold } = paint(process12.stdout);
1143
1202
  console.log(`${bold("header")}
1144
1203
  ${JSON.stringify(decoded.header, null, 2)}
1145
1204
 
@@ -1153,14 +1212,15 @@ ${JSON.stringify(decoded.payload, null, 2)}`);
1153
1212
  }
1154
1213
  var TS_USAGE = `dev ts [value]: a time as local and UTC dates, whatever it is written as
1155
1214
 
1156
- The value is epoch seconds or milliseconds (told apart by size: from 1e11 up it is milliseconds), an ISO date or date-time (read in the local zone when it gives none), or a duration such as 90m or 2h30m, shown with the date that far from now. Without a value it is now; "-" reads the value on stdin.
1157
- Exits 0 when it converted the value, 1 when it is none of those, 2 on a usage error.`;
1215
+ The value is epoch seconds or milliseconds (told apart by size: from 1e11 up it is milliseconds), an ISO date or date-time (read in the local zone when it gives none), or a duration such as 90m or 2h30m, shown with the date that far from now. Without a value it is now; "-" reads the value on stdin.`;
1216
+ var TS_EXITS = [[0, "it converted the value"], [1, "it is none of those"], [2, "a usage error"]];
1158
1217
  var TS_OPTIONS = {
1159
1218
  zone: ZONE_OPTION,
1160
1219
  json: jsonOption("{kind, ms, seconds, local, utc, relative} or, for a duration, {kind, ms, seconds, human, fromNow}")
1161
1220
  };
1162
1221
  async function ts(args) {
1163
1222
  const { values, positionals } = parse(args, TS_USAGE, TS_OPTIONS, {
1223
+ exits: TS_EXITS,
1164
1224
  positionals: ["[value]"],
1165
1225
  replaces: "date -d @<seconds> and date -u, and doing the milliseconds division by hand",
1166
1226
  examples: ["dev ts 1700000000", ["dev ts 2h30m", "the date 2h30m from now"], ["dev ts 2024-05-06T08:09:10Z --zone Europe/Paris", "that instant in Paris"]]
@@ -1179,12 +1239,12 @@ async function ts(args) {
1179
1239
  printRows([["local", converted.local], ["utc", converted.utc], ["seconds", String(converted.seconds)], ["ms", String(converted.ms)], ["relative", converted.relative]]);
1180
1240
  return 0;
1181
1241
  }
1182
- var UUID_USAGE = `dev uuid [-n <count>] [--v7]: random UUIDs, version 4 or, with --v7, version 7 (time-ordered)
1183
-
1184
- Exits 0 when it printed them, 2 on a usage error.`;
1242
+ var UUID_USAGE = `dev uuid [-n <count>] [--v7]: random UUIDs, version 4 or, with --v7, version 7 (time-ordered)`;
1243
+ var UUID_EXITS = [[0, "it printed them"], [2, "a usage error"]];
1185
1244
  var COUNT_OPTION = { type: "string", short: "n", description: "how many to print (default 1)" };
1186
1245
  function uuid(args) {
1187
1246
  const { values } = parse(args, UUID_USAGE, { n: COUNT_OPTION, v7: { type: "boolean", description: "a version 7 UUID, which sorts by creation time" }, json: jsonOption('["uuid"]') }, {
1247
+ exits: UUID_EXITS,
1188
1248
  positionals: [],
1189
1249
  replaces: 'uuidgen and python -c "import uuid"',
1190
1250
  examples: ["dev uuid", ["dev uuid -n 5 --v7", "five time-ordered UUIDs"]]
@@ -1193,11 +1253,11 @@ function uuid(args) {
1193
1253
  printIds(ids, values.json === true);
1194
1254
  return 0;
1195
1255
  }
1196
- var ULID_USAGE = `dev ulid [-n <count>]: random ULIDs, 26 sortable characters of time and randomness
1197
-
1198
- Exits 0 when it printed them, 2 on a usage error.`;
1256
+ var ULID_USAGE = `dev ulid [-n <count>]: random ULIDs, 26 sortable characters of time and randomness`;
1257
+ var ULID_EXITS = [[0, "it printed them"], [2, "a usage error"]];
1199
1258
  function ulidCommand(args) {
1200
1259
  const { values } = parse(args, ULID_USAGE, { n: COUNT_OPTION, json: jsonOption('["ulid"]') }, {
1260
+ exits: ULID_EXITS,
1201
1261
  positionals: [],
1202
1262
  replaces: "installing a ulid package to mint one",
1203
1263
  examples: ["dev ulid", ["dev ulid -n 3", "three ULIDs"]]
@@ -1214,8 +1274,8 @@ function printIds(ids, json) {
1214
1274
  }
1215
1275
  var B64_USAGE = `dev b64 [-d] [--url] [text]: base64 of the text, or with -d the text behind a base64 one
1216
1276
 
1217
- The text is the argument or what is piped on stdin, taken as is (a piped trailing newline is encoded, as base64 does). With --url the output is URL-safe and unpadded. Decoding takes either alphabet, padded or not, and writes the raw bytes.
1218
- Exits 0 when it printed the result, 1 when -d is given text that is not base64, 2 on a usage error.`;
1277
+ The text is the argument or what is piped on stdin, taken as is (a piped trailing newline is encoded, as base64 does). With --url the output is URL-safe and unpadded. Decoding takes either alphabet, padded or not, and writes the raw bytes.`;
1278
+ var B64_EXITS = [[0, "it printed the result"], [1, "-d is given text that is not base64"], [2, "a usage error"]];
1219
1279
  var B64_OPTIONS = {
1220
1280
  decode: { type: "boolean", short: "d", description: "decode instead of encode" },
1221
1281
  url: { type: "boolean", description: "URL-safe alphabet without padding, when encoding" },
@@ -1223,6 +1283,7 @@ var B64_OPTIONS = {
1223
1283
  };
1224
1284
  async function b64(args) {
1225
1285
  const { values, positionals } = parse(args, B64_USAGE, B64_OPTIONS, {
1286
+ exits: B64_EXITS,
1226
1287
  positionals: ["[text]"],
1227
1288
  replaces: "base64 and base64 -d, which leave the URL-safe alphabet to tr",
1228
1289
  examples: ["dev b64 hello", ["echo aGVsbG8 | dev b64 -d", "decoded, padding optional"]]
@@ -1245,10 +1306,11 @@ async function b64(args) {
1245
1306
  }
1246
1307
  var URL_USAGE = `dev url [url]: the parts of a URL and its query decoded, one per line
1247
1308
 
1248
- The URL is the argument or what is piped on stdin, and has to include its scheme.
1249
- Exits 0 when it printed the parts, 1 when the text is not a URL, 2 on a usage error.`;
1309
+ The URL is the argument or what is piped on stdin, and has to include its scheme.`;
1310
+ var URL_EXITS = [[0, "it printed the parts"], [1, "the text is not a URL"], [2, "a usage error"]];
1250
1311
  async function url(args) {
1251
1312
  const { values, positionals } = parse(args, URL_USAGE, { json: jsonOption("{href, protocol, username, password, host, hostname, port, pathname, query: [{key, value}], hash}") }, {
1313
+ exits: URL_EXITS,
1252
1314
  positionals: ["[url]"],
1253
1315
  replaces: "reading a long query string by eye or decoding it with python urllib",
1254
1316
  examples: ['dev url "https://example.com:8443/a%20b?q=x%26y&page=2#top"', ['dev url "https://example.com/?a=1" --json', "for a script"]]
@@ -1264,11 +1326,11 @@ async function url(args) {
1264
1326
  printRows([...shown, ...query.map(({ key, value }) => [`?${key}`, value])]);
1265
1327
  return 0;
1266
1328
  }
1267
- var HASH_USAGE = `dev hash <sha256|sha1|md5|sha512> [file]: the hex digest of a file, or of what is piped on stdin
1268
-
1269
- Exits 0 when it printed the digest, 1 when the file does not exist, 2 on a usage error.`;
1329
+ var HASH_USAGE = `dev hash <sha256|sha1|md5|sha512> [file]: the hex digest of a file, or of what is piped on stdin`;
1330
+ var HASH_EXITS = [[0, "it printed the digest"], [1, "the file does not exist"], [2, "a usage error"]];
1270
1331
  async function hash(args) {
1271
1332
  const { values, positionals } = parse(args, HASH_USAGE, { json: jsonOption("{algorithm, hash, bytes}") }, {
1333
+ exits: HASH_EXITS,
1272
1334
  positionals: ["<algorithm>", "[file]"],
1273
1335
  candidates: { "<algorithm>": () => [...ALGORITHMS] },
1274
1336
  replaces: "sha256sum, sha1sum and md5sum, which print the file name beside the digest",
@@ -1276,28 +1338,30 @@ async function hash(args) {
1276
1338
  });
1277
1339
  const algorithm = oneOf(positionals[0] ?? "", "<algorithm>", ALGORITHMS);
1278
1340
  const file = positionals[1];
1279
- let bytes;
1341
+ let result;
1280
1342
  if (file === undefined) {
1281
- bytes = await bytesInput(undefined, "a file");
1343
+ const input = await bytesInput(undefined, "a file");
1344
+ result = { digest: hashHex(algorithm, input), bytes: input.length };
1282
1345
  } else {
1283
1346
  const source = Bun.file(file);
1284
1347
  if (!await source.exists())
1285
1348
  return fail(`no file ${file}`, 1);
1286
- bytes = new Uint8Array(await source.arrayBuffer());
1349
+ result = await hashStream(algorithm, source.stream());
1287
1350
  }
1288
- const digest = hashHex(algorithm, bytes);
1351
+ const digest = result.digest;
1289
1352
  if (values.json === true)
1290
- printJson({ algorithm, hash: digest, bytes: bytes.length });
1353
+ printJson({ algorithm, hash: digest, bytes: result.bytes });
1291
1354
  else
1292
1355
  console.log(digest);
1293
1356
  return 0;
1294
1357
  }
1295
1358
  var IP_USAGE = `dev ip [-4|-6]: the public IP address of this host, as a web service sees it
1296
1359
 
1297
- -4 or -6 asks over that IP family only, which fails when the host has no route over it.
1298
- Exits 0 when it printed the address, 1 when the service could not be reached, 2 on a usage error.`;
1360
+ -4 or -6 asks over that IP family only, which fails when the host has no route over it.`;
1361
+ var IP_EXITS = [[0, "it printed the address"], [1, "the service could not be reached"], [2, "a usage error"]];
1299
1362
  async function ip(args) {
1300
1363
  const { values } = parse(args, IP_USAGE, { 4: { type: "boolean", short: "4", description: "over IPv4 only" }, 6: { type: "boolean", short: "6", description: "over IPv6 only" }, json: jsonOption("{ip, family?}") }, {
1364
+ exits: IP_EXITS,
1301
1365
  replaces: "curl https://ipecho.net/plain typed from memory",
1302
1366
  examples: ["dev ip", ["dev ip -6", "the IPv6 address"]]
1303
1367
  });
@@ -1320,7 +1384,7 @@ async function ip(args) {
1320
1384
  }
1321
1385
  }
1322
1386
  if (import.meta.main) {
1323
- process11.exitCode = await runCli({
1387
+ process12.exitCode = await runCli({
1324
1388
  name: "dev",
1325
1389
  about: "small developer utilities: passwords and bcrypt hashes, JWTs, timestamps, UUIDs, base64, URLs and file hashes",
1326
1390
  replaces: "openssl rand, htpasswd, jwt.io, date -d, uuidgen, base64, sha256sum and one-off scripts for each",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-dev",
3
3
  "type": "module",
4
- "version": "0.5.0",
4
+ "version": "0.5.2",
5
5
  "description": "dev: small developer utilities in one bin: random passwords and bcrypt hashes, JWT decoding, timestamps, UUIDs and ULIDs, base64, URL parts and file hashes.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -36,6 +36,6 @@
36
36
  "dev": "$npm_execpath src/cli.ts"
37
37
  },
38
38
  "devDependencies": {
39
- "@kaynooo/cli-kit": "0.38.1"
39
+ "@kaynooo/cli-kit": "0.39.0"
40
40
  }
41
41
  }