@kaynooo/cli-dev 0.4.0 → 0.5.1

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 +1 -0
  2. package/dist/cli.js +124 -56
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -16,6 +16,7 @@ bun add -g @kaynooo/cli-dev
16
16
  | `dev b64 [-d] [--url] [text]` | base64 of the text, or with `-d` the text behind it (either alphabet, padding optional) |
17
17
  | `dev url [url]` | the parts of a URL and its decoded query |
18
18
  | `dev hash <sha256\|sha1\|md5\|sha512> [file]` | the hex digest of a file or of stdin |
19
+ | `dev ip [-4\|-6]` | the public IP address of this host, over IPv4 or IPv6 only when asked (needs `curl`) |
19
20
 
20
21
  `--json` prints the structured result of every command. `jwt` and `ts` take `--zone <IANA zone>` for the local dates instead of the host's.
21
22
 
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process10 from "process";
5
+ import process11 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process6 from "process";
8
8
  import { parseArgs } from "util";
@@ -129,18 +129,14 @@ var FULL_STOP = /\.$/;
129
129
  function usageLine(usage, colors = paint(process5.stdout)) {
130
130
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
131
131
  }
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(`
132
+ function helpText(usage, options, colors = paint(process5.stdout), { examples = [], exits = [] } = {}) {
133
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
134
134
  `);
135
135
  }
136
136
  function exitRows(exits, colors = paint(process5.stdout)) {
137
137
  if (exits.length === 0)
138
138
  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}`];
139
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
144
140
  }
145
141
  function wantsHelpJson(env = process5.env) {
146
142
  return env.KIT_HELP === "json";
@@ -430,6 +426,30 @@ function nearestOption(message, options, allowNegative) {
430
426
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
431
427
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
432
428
  }
429
+ // ../kit/src/argv.ts
430
+ import { readFileSync, realpathSync } from "fs";
431
+ import { resolve } from "path";
432
+ import process7 from "process";
433
+ function commandLine() {
434
+ try {
435
+ return readFileSync("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
436
+ } catch {
437
+ return;
438
+ }
439
+ }
440
+ function realPath(word) {
441
+ try {
442
+ return realpathSync(resolve(word));
443
+ } catch {
444
+ return;
445
+ }
446
+ }
447
+ function scriptArgs(argv = process7.argv.slice(2), cmdline = commandLine(), script = process7.argv[1]) {
448
+ const target = script === undefined ? undefined : realPath(script) ?? script;
449
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve(word) === script || realPath(word) === target));
450
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
451
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
452
+ }
433
453
  // ../kit/src/process.ts
434
454
  var CLIPBOARDS = [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"], ["pbcopy"], ["clip.exe"]];
435
455
  async function copyText(text, which = Bun.which) {
@@ -455,15 +475,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
455
475
  var RESET_STYLE = `${ESC}[0m`;
456
476
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
457
477
  // ../kit/src/cli.ts
458
- import { readFileSync, realpathSync } from "fs";
478
+ import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
459
479
  import { dirname as dirname2, join as join2 } from "path";
460
- import process8 from "process";
480
+ import process9 from "process";
461
481
 
462
482
  // ../kit/src/usage.ts
463
483
  import { appendFileSync, mkdirSync } from "fs";
464
484
  import { homedir } from "os";
465
485
  import { dirname, isAbsolute, join } from "path";
466
- import process7 from "process";
486
+ import process8 from "process";
467
487
 
468
488
  // ../kit/src/logs.ts
469
489
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -477,14 +497,14 @@ var usageError;
477
497
  function noteUsageError(message) {
478
498
  usageError = message;
479
499
  }
480
- function stateHome(env = process7.env) {
500
+ function stateHome(env = process8.env) {
481
501
  const dir = env.XDG_STATE_HOME;
482
502
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
483
503
  }
484
- function usagePath(env = process7.env) {
504
+ function usagePath(env = process8.env) {
485
505
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
486
506
  }
487
- function usageRecorded(env = process7.env) {
507
+ function usageRecorded(env = process8.env) {
488
508
  const off = env.KAYNOOO_CLI_NO_USAGE;
489
509
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
490
510
  }
@@ -498,7 +518,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
498
518
  usageError = undefined;
499
519
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
500
520
  }
501
- function recordUsage(entry, env = process7.env) {
521
+ function recordUsage(entry, env = process8.env) {
502
522
  if (!usageRecorded(env))
503
523
  return;
504
524
  try {
@@ -575,7 +595,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
575
595
  header(colors, summary),
576
596
  "",
577
597
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
578
- ...replacesRows(replaces, colors),
579
598
  "",
580
599
  ...await commandRows(commands, colors),
581
600
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -589,8 +608,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
589
608
  `);
590
609
  }
591
610
  function printError(prefix, message, hint, cause) {
592
- const colors = paint(process8.stderr);
593
- const styled = takesControlCodes(process8.stderr);
611
+ const colors = paint(process9.stderr);
612
+ const styled = takesControlCodes(process9.stderr);
594
613
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
595
614
  const under = (label, text, tint) => text === undefined ? "" : `
596
615
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -633,11 +652,11 @@ async function dispatch(level, typed, { version, redact }) {
633
652
  }
634
653
  }
635
654
  if (name === undefined && level.path.length > 1) {
636
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
655
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
637
656
  return 2;
638
657
  }
639
658
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
640
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
659
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
641
660
  return 0;
642
661
  }
643
662
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -693,24 +712,24 @@ function candidateLine(candidate) {
693
712
  }
694
713
  function positionalBeingTyped(before, { options, positionals }) {
695
714
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
696
- let index = 0;
715
+ const typed = [];
697
716
  let at = 0;
698
717
  while (at < before.length) {
699
718
  const word = before[at];
700
719
  if (word === "--") {
701
- index += before.length - at - 1;
720
+ typed.push(...before.slice(at + 1));
702
721
  break;
703
722
  }
704
723
  if (!word.startsWith("-"))
705
- index++;
724
+ typed.push(word);
706
725
  else if (takesValue(word))
707
726
  at++;
708
727
  at++;
709
728
  }
710
729
  const last = positionals.at(-1);
711
- if (index < positionals.length)
712
- return positionals[index];
713
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
730
+ if (typed.length < positionals.length)
731
+ return { name: positionals[typed.length], typed };
732
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
714
733
  }
715
734
  async function leafCandidates(run, words) {
716
735
  const completing = await completingOf(run);
@@ -718,12 +737,12 @@ async function leafCandidates(run, words) {
718
737
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
719
738
  const flag = words.at(-2);
720
739
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
740
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
721
741
  if (option?.type === "string") {
722
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
742
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
723
743
  return values === undefined ? [FILES] : values.map(candidateLine);
724
744
  }
725
- const name = positionalBeingTyped(words.slice(0, -1), completing);
726
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
745
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
727
746
  return values === undefined ? [FILES] : values.map(candidateLine);
728
747
  }
729
748
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -754,9 +773,13 @@ async function printCandidates(found) {
754
773
  return 0;
755
774
  }
756
775
  function packageVersion(entry = Bun.main) {
757
- for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
776
+ let resolved = entry;
777
+ try {
778
+ resolved = realpathSync2(entry);
779
+ } catch {}
780
+ for (let dir = dirname2(resolved);; dir = dirname2(dir)) {
758
781
  try {
759
- const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
782
+ const { version } = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
760
783
  if (typeof version === "string")
761
784
  return version;
762
785
  } catch {}
@@ -764,7 +787,7 @@ function packageVersion(entry = Bun.main) {
764
787
  return "0.0.0";
765
788
  }
766
789
  }
767
- async function runCli(cli, argv = process8.argv.slice(2)) {
790
+ async function runCli(cli, argv = scriptArgs()) {
768
791
  const version = cli.version ?? packageVersion();
769
792
  if (argv[0] === COMPLETE)
770
793
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -847,6 +870,16 @@ function uuidV4() {
847
870
  return crypto.randomUUID();
848
871
  }
849
872
 
873
+ // src/ip.ts
874
+ var IP_SERVICE = "https://ipecho.net/plain";
875
+ async function publicIp(family, service = IP_SERVICE) {
876
+ const child = Bun.spawn(["curl", "--silent", "--show-error", "--fail", "--max-time", "10", ...family === undefined ? [] : [`-${family}`], service], { stdout: "pipe", stderr: "pipe" });
877
+ const [out, err, code] = await Promise.all([child.stdout.text(), child.stderr.text(), child.exited]);
878
+ if (code !== 0)
879
+ throw new Error(err.trim() === "" ? `curl exited ${code}` : err.trim());
880
+ return out.trim();
881
+ }
882
+
850
883
  // src/time.ts
851
884
  var UNITS = [["d", 86400000], ["h", 3600000], ["m", 60000], ["s", 1000]];
852
885
  var DURATION_UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
@@ -1042,15 +1075,15 @@ async function bytesInput(argument, what) {
1042
1075
  return new Uint8Array(await Bun.stdin.arrayBuffer());
1043
1076
  }
1044
1077
  function printRows(rows) {
1045
- const { cyan } = paint(process10.stdout);
1078
+ const { cyan } = paint(process11.stdout);
1046
1079
  const width = Math.max(...rows.map(([label]) => label.length));
1047
1080
  for (const [label, value] of rows)
1048
1081
  console.log(`${cyan(label.padEnd(width))} ${value}`);
1049
1082
  }
1050
1083
  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
1051
1084
 
1052
- 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.
1053
- Exits 0 when it printed the password or hash, 2 on a usage error.`;
1085
+ 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.`;
1086
+ var PASSWORD_EXITS = [[0, "it printed the password or hash"], [2, "a usage error"]];
1054
1087
  var PASSWORD_OPTIONS = {
1055
1088
  bcrypt: { type: "string", short: "b", optional: { bare: "" }, description: "print the bcrypt hash of the password given, or of a generated one" },
1056
1089
  "no-copy": { type: "boolean", description: "leave the clipboard alone" },
@@ -1059,6 +1092,7 @@ var PASSWORD_OPTIONS = {
1059
1092
  var FORMAT_NOTES = { hex: "hexadecimal", base64: "base64", base64url: "url-safe base64" };
1060
1093
  async function password(args) {
1061
1094
  const { values, positionals } = parse(args, PASSWORD_USAGE, PASSWORD_OPTIONS, {
1095
+ exits: PASSWORD_EXITS,
1062
1096
  positionals: ["[length]", "[format]"],
1063
1097
  candidates: { "[length]": () => ["16", "24", "32", "48", "64"], "[format]": () => FORMATS.map((format) => [format, FORMAT_NOTES[format]]) },
1064
1098
  replaces: 'openssl rand -base64 32 and htpasswd -bnBC 10 "" <password>',
@@ -1077,7 +1111,7 @@ async function password(args) {
1077
1111
  return 0;
1078
1112
  }
1079
1113
  if (copied)
1080
- console.error(paint(process10.stderr).dim("copied to clipboard"));
1114
+ console.error(paint(process11.stderr).dim("copied to clipboard"));
1081
1115
  if (hash !== undefined && given === undefined)
1082
1116
  console.error(secret);
1083
1117
  console.log(hash ?? secret);
@@ -1085,14 +1119,15 @@ async function password(args) {
1085
1119
  }
1086
1120
  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
1087
1121
 
1088
- The token is the argument or what is piped on stdin, a leading "Bearer " is ignored. The signature is not verified.
1089
- Exits 0 when it decoded the token, 1 when it is not a JWT, 2 on a usage error.`;
1122
+ The token is the argument or what is piped on stdin, a leading "Bearer " is ignored. The signature is not verified.`;
1123
+ var JWT_EXITS = [[0, "it decoded the token"], [1, "it is not a JWT"], [2, "a usage error"]];
1090
1124
  var JWT_OPTIONS = {
1091
1125
  zone: ZONE_OPTION,
1092
1126
  json: jsonOption("{header, payload, claims: [{claim, epoch, local, utc, relative}], signatureBytes}")
1093
1127
  };
1094
1128
  async function jwt(args) {
1095
1129
  const { values, positionals } = parse(args, JWT_USAGE, JWT_OPTIONS, {
1130
+ exits: JWT_EXITS,
1096
1131
  positionals: ["[token]"],
1097
1132
  replaces: "pasting a token into jwt.io or decoding its segments with base64 and jq",
1098
1133
  examples: ["dev jwt eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDAwMDAwMDB9.c2ln", ["pbpaste | dev jwt --json", "for a script"]]
@@ -1105,7 +1140,7 @@ async function jwt(args) {
1105
1140
  printJson({ header: decoded.header, payload: decoded.payload, claims, signatureBytes: decoded.signatureBytes });
1106
1141
  return 0;
1107
1142
  }
1108
- const { bold } = paint(process10.stdout);
1143
+ const { bold } = paint(process11.stdout);
1109
1144
  console.log(`${bold("header")}
1110
1145
  ${JSON.stringify(decoded.header, null, 2)}
1111
1146
 
@@ -1119,14 +1154,15 @@ ${JSON.stringify(decoded.payload, null, 2)}`);
1119
1154
  }
1120
1155
  var TS_USAGE = `dev ts [value]: a time as local and UTC dates, whatever it is written as
1121
1156
 
1122
- 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.
1123
- Exits 0 when it converted the value, 1 when it is none of those, 2 on a usage error.`;
1157
+ 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.`;
1158
+ var TS_EXITS = [[0, "it converted the value"], [1, "it is none of those"], [2, "a usage error"]];
1124
1159
  var TS_OPTIONS = {
1125
1160
  zone: ZONE_OPTION,
1126
1161
  json: jsonOption("{kind, ms, seconds, local, utc, relative} or, for a duration, {kind, ms, seconds, human, fromNow}")
1127
1162
  };
1128
1163
  async function ts(args) {
1129
1164
  const { values, positionals } = parse(args, TS_USAGE, TS_OPTIONS, {
1165
+ exits: TS_EXITS,
1130
1166
  positionals: ["[value]"],
1131
1167
  replaces: "date -d @<seconds> and date -u, and doing the milliseconds division by hand",
1132
1168
  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"]]
@@ -1145,12 +1181,12 @@ async function ts(args) {
1145
1181
  printRows([["local", converted.local], ["utc", converted.utc], ["seconds", String(converted.seconds)], ["ms", String(converted.ms)], ["relative", converted.relative]]);
1146
1182
  return 0;
1147
1183
  }
1148
- var UUID_USAGE = `dev uuid [-n <count>] [--v7]: random UUIDs, version 4 or, with --v7, version 7 (time-ordered)
1149
-
1150
- Exits 0 when it printed them, 2 on a usage error.`;
1184
+ var UUID_USAGE = `dev uuid [-n <count>] [--v7]: random UUIDs, version 4 or, with --v7, version 7 (time-ordered)`;
1185
+ var UUID_EXITS = [[0, "it printed them"], [2, "a usage error"]];
1151
1186
  var COUNT_OPTION = { type: "string", short: "n", description: "how many to print (default 1)" };
1152
1187
  function uuid(args) {
1153
1188
  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"]') }, {
1189
+ exits: UUID_EXITS,
1154
1190
  positionals: [],
1155
1191
  replaces: 'uuidgen and python -c "import uuid"',
1156
1192
  examples: ["dev uuid", ["dev uuid -n 5 --v7", "five time-ordered UUIDs"]]
@@ -1159,11 +1195,11 @@ function uuid(args) {
1159
1195
  printIds(ids, values.json === true);
1160
1196
  return 0;
1161
1197
  }
1162
- var ULID_USAGE = `dev ulid [-n <count>]: random ULIDs, 26 sortable characters of time and randomness
1163
-
1164
- Exits 0 when it printed them, 2 on a usage error.`;
1198
+ var ULID_USAGE = `dev ulid [-n <count>]: random ULIDs, 26 sortable characters of time and randomness`;
1199
+ var ULID_EXITS = [[0, "it printed them"], [2, "a usage error"]];
1165
1200
  function ulidCommand(args) {
1166
1201
  const { values } = parse(args, ULID_USAGE, { n: COUNT_OPTION, json: jsonOption('["ulid"]') }, {
1202
+ exits: ULID_EXITS,
1167
1203
  positionals: [],
1168
1204
  replaces: "installing a ulid package to mint one",
1169
1205
  examples: ["dev ulid", ["dev ulid -n 3", "three ULIDs"]]
@@ -1180,8 +1216,8 @@ function printIds(ids, json) {
1180
1216
  }
1181
1217
  var B64_USAGE = `dev b64 [-d] [--url] [text]: base64 of the text, or with -d the text behind a base64 one
1182
1218
 
1183
- 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.
1184
- Exits 0 when it printed the result, 1 when -d is given text that is not base64, 2 on a usage error.`;
1219
+ 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.`;
1220
+ var B64_EXITS = [[0, "it printed the result"], [1, "-d is given text that is not base64"], [2, "a usage error"]];
1185
1221
  var B64_OPTIONS = {
1186
1222
  decode: { type: "boolean", short: "d", description: "decode instead of encode" },
1187
1223
  url: { type: "boolean", description: "URL-safe alphabet without padding, when encoding" },
@@ -1189,6 +1225,7 @@ var B64_OPTIONS = {
1189
1225
  };
1190
1226
  async function b64(args) {
1191
1227
  const { values, positionals } = parse(args, B64_USAGE, B64_OPTIONS, {
1228
+ exits: B64_EXITS,
1192
1229
  positionals: ["[text]"],
1193
1230
  replaces: "base64 and base64 -d, which leave the URL-safe alphabet to tr",
1194
1231
  examples: ["dev b64 hello", ["echo aGVsbG8 | dev b64 -d", "decoded, padding optional"]]
@@ -1211,10 +1248,11 @@ async function b64(args) {
1211
1248
  }
1212
1249
  var URL_USAGE = `dev url [url]: the parts of a URL and its query decoded, one per line
1213
1250
 
1214
- The URL is the argument or what is piped on stdin, and has to include its scheme.
1215
- Exits 0 when it printed the parts, 1 when the text is not a URL, 2 on a usage error.`;
1251
+ The URL is the argument or what is piped on stdin, and has to include its scheme.`;
1252
+ var URL_EXITS = [[0, "it printed the parts"], [1, "the text is not a URL"], [2, "a usage error"]];
1216
1253
  async function url(args) {
1217
1254
  const { values, positionals } = parse(args, URL_USAGE, { json: jsonOption("{href, protocol, username, password, host, hostname, port, pathname, query: [{key, value}], hash}") }, {
1255
+ exits: URL_EXITS,
1218
1256
  positionals: ["[url]"],
1219
1257
  replaces: "reading a long query string by eye or decoding it with python urllib",
1220
1258
  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"]]
@@ -1230,11 +1268,11 @@ async function url(args) {
1230
1268
  printRows([...shown, ...query.map(({ key, value }) => [`?${key}`, value])]);
1231
1269
  return 0;
1232
1270
  }
1233
- var HASH_USAGE = `dev hash <sha256|sha1|md5|sha512> [file]: the hex digest of a file, or of what is piped on stdin
1234
-
1235
- Exits 0 when it printed the digest, 1 when the file does not exist, 2 on a usage error.`;
1271
+ var HASH_USAGE = `dev hash <sha256|sha1|md5|sha512> [file]: the hex digest of a file, or of what is piped on stdin`;
1272
+ var HASH_EXITS = [[0, "it printed the digest"], [1, "the file does not exist"], [2, "a usage error"]];
1236
1273
  async function hash(args) {
1237
1274
  const { values, positionals } = parse(args, HASH_USAGE, { json: jsonOption("{algorithm, hash, bytes}") }, {
1275
+ exits: HASH_EXITS,
1238
1276
  positionals: ["<algorithm>", "[file]"],
1239
1277
  candidates: { "<algorithm>": () => [...ALGORITHMS] },
1240
1278
  replaces: "sha256sum, sha1sum and md5sum, which print the file name beside the digest",
@@ -1258,8 +1296,36 @@ async function hash(args) {
1258
1296
  console.log(digest);
1259
1297
  return 0;
1260
1298
  }
1299
+ var IP_USAGE = `dev ip [-4|-6]: the public IP address of this host, as a web service sees it
1300
+
1301
+ -4 or -6 asks over that IP family only, which fails when the host has no route over it.`;
1302
+ var IP_EXITS = [[0, "it printed the address"], [1, "the service could not be reached"], [2, "a usage error"]];
1303
+ async function ip(args) {
1304
+ 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?}") }, {
1305
+ exits: IP_EXITS,
1306
+ replaces: "curl https://ipecho.net/plain typed from memory",
1307
+ examples: ["dev ip", ["dev ip -6", "the IPv6 address"]]
1308
+ });
1309
+ if (values[4] === true && values[6] === true)
1310
+ badUsage("-4 and -6 cannot be combined");
1311
+ let family;
1312
+ if (values[4] === true)
1313
+ family = 4;
1314
+ else if (values[6] === true)
1315
+ family = 6;
1316
+ try {
1317
+ const address = await publicIp(family);
1318
+ if (values.json === true)
1319
+ printJson(family === undefined ? { ip: address } : { ip: address, family });
1320
+ else
1321
+ console.log(address);
1322
+ return 0;
1323
+ } catch (error) {
1324
+ return fail(`could not read the public address: ${error instanceof Error ? error.message : String(error)}`, 1);
1325
+ }
1326
+ }
1261
1327
  if (import.meta.main) {
1262
- process10.exitCode = await runCli({
1328
+ process11.exitCode = await runCli({
1263
1329
  name: "dev",
1264
1330
  about: "small developer utilities: passwords and bcrypt hashes, JWTs, timestamps, UUIDs, base64, URLs and file hashes",
1265
1331
  replaces: "openssl rand, htpasswd, jwt.io, date -d, uuidgen, base64, sha256sum and one-off scripts for each",
@@ -1272,13 +1338,15 @@ if (import.meta.main) {
1272
1338
  ulid: { summary: "random ULIDs", run: async (args) => Promise.resolve(ulidCommand(args)) },
1273
1339
  b64: { summary: "base64 encode or decode, standard or URL-safe", run: b64 },
1274
1340
  url: { summary: "the parts of a URL and its decoded query", run: url },
1275
- hash: { summary: "sha256, sha1, md5 or sha512 of a file or stdin", run: hash }
1341
+ hash: { summary: "sha256, sha1, md5 or sha512 of a file or stdin", run: hash },
1342
+ ip: { summary: "the public IP address of this host, IPv4 or IPv6", run: ip }
1276
1343
  }
1277
1344
  });
1278
1345
  }
1279
1346
  export {
1280
1347
  b64,
1281
1348
  hash,
1349
+ ip,
1282
1350
  jwt,
1283
1351
  password,
1284
1352
  ts,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-dev",
3
3
  "type": "module",
4
- "version": "0.4.0",
4
+ "version": "0.5.1",
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.35.0"
39
+ "@kaynooo/cli-kit": "0.38.2"
40
40
  }
41
41
  }