@kaynooo/cli-dev 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -0
  2. package/dist/cli.js +92 -29
  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";
@@ -430,6 +430,30 @@ function nearestOption(message, options, allowNegative) {
430
430
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
431
431
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
432
432
  }
433
+ // ../kit/src/argv.ts
434
+ import { readFileSync, realpathSync } from "fs";
435
+ import { resolve } from "path";
436
+ import process7 from "process";
437
+ function commandLine() {
438
+ try {
439
+ return readFileSync("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
440
+ } catch {
441
+ return;
442
+ }
443
+ }
444
+ function realPath(word) {
445
+ try {
446
+ return realpathSync(resolve(word));
447
+ } catch {
448
+ return;
449
+ }
450
+ }
451
+ function scriptArgs(argv = process7.argv.slice(2), cmdline = commandLine(), script = process7.argv[1]) {
452
+ const target = script === undefined ? undefined : realPath(script) ?? script;
453
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve(word) === script || realPath(word) === target));
454
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
455
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
456
+ }
433
457
  // ../kit/src/process.ts
434
458
  var CLIPBOARDS = [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"], ["pbcopy"], ["clip.exe"]];
435
459
  async function copyText(text, which = Bun.which) {
@@ -455,15 +479,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
455
479
  var RESET_STYLE = `${ESC}[0m`;
456
480
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
457
481
  // ../kit/src/cli.ts
458
- import { readFileSync, realpathSync } from "fs";
482
+ import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
459
483
  import { dirname as dirname2, join as join2 } from "path";
460
- import process8 from "process";
484
+ import process9 from "process";
461
485
 
462
486
  // ../kit/src/usage.ts
463
487
  import { appendFileSync, mkdirSync } from "fs";
464
488
  import { homedir } from "os";
465
489
  import { dirname, isAbsolute, join } from "path";
466
- import process7 from "process";
490
+ import process8 from "process";
467
491
 
468
492
  // ../kit/src/logs.ts
469
493
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -477,14 +501,14 @@ var usageError;
477
501
  function noteUsageError(message) {
478
502
  usageError = message;
479
503
  }
480
- function stateHome(env = process7.env) {
504
+ function stateHome(env = process8.env) {
481
505
  const dir = env.XDG_STATE_HOME;
482
506
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
483
507
  }
484
- function usagePath(env = process7.env) {
508
+ function usagePath(env = process8.env) {
485
509
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
486
510
  }
487
- function usageRecorded(env = process7.env) {
511
+ function usageRecorded(env = process8.env) {
488
512
  const off = env.KAYNOOO_CLI_NO_USAGE;
489
513
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
490
514
  }
@@ -498,7 +522,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
498
522
  usageError = undefined;
499
523
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
500
524
  }
501
- function recordUsage(entry, env = process7.env) {
525
+ function recordUsage(entry, env = process8.env) {
502
526
  if (!usageRecorded(env))
503
527
  return;
504
528
  try {
@@ -589,8 +613,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
589
613
  `);
590
614
  }
591
615
  function printError(prefix, message, hint, cause) {
592
- const colors = paint(process8.stderr);
593
- const styled = takesControlCodes(process8.stderr);
616
+ const colors = paint(process9.stderr);
617
+ const styled = takesControlCodes(process9.stderr);
594
618
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
595
619
  const under = (label, text, tint) => text === undefined ? "" : `
596
620
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -633,11 +657,11 @@ async function dispatch(level, typed, { version, redact }) {
633
657
  }
634
658
  }
635
659
  if (name === undefined && level.path.length > 1) {
636
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
660
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
637
661
  return 2;
638
662
  }
639
663
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
640
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
664
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
641
665
  return 0;
642
666
  }
643
667
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -693,24 +717,24 @@ function candidateLine(candidate) {
693
717
  }
694
718
  function positionalBeingTyped(before, { options, positionals }) {
695
719
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
696
- let index = 0;
720
+ const typed = [];
697
721
  let at = 0;
698
722
  while (at < before.length) {
699
723
  const word = before[at];
700
724
  if (word === "--") {
701
- index += before.length - at - 1;
725
+ typed.push(...before.slice(at + 1));
702
726
  break;
703
727
  }
704
728
  if (!word.startsWith("-"))
705
- index++;
729
+ typed.push(word);
706
730
  else if (takesValue(word))
707
731
  at++;
708
732
  at++;
709
733
  }
710
734
  const last = positionals.at(-1);
711
- if (index < positionals.length)
712
- return positionals[index];
713
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
735
+ if (typed.length < positionals.length)
736
+ return { name: positionals[typed.length], typed };
737
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
714
738
  }
715
739
  async function leafCandidates(run, words) {
716
740
  const completing = await completingOf(run);
@@ -718,12 +742,12 @@ async function leafCandidates(run, words) {
718
742
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
719
743
  const flag = words.at(-2);
720
744
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
745
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
721
746
  if (option?.type === "string") {
722
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
747
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
723
748
  return values === undefined ? [FILES] : values.map(candidateLine);
724
749
  }
725
- const name = positionalBeingTyped(words.slice(0, -1), completing);
726
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
750
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
727
751
  return values === undefined ? [FILES] : values.map(candidateLine);
728
752
  }
729
753
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -754,9 +778,9 @@ async function printCandidates(found) {
754
778
  return 0;
755
779
  }
756
780
  function packageVersion(entry = Bun.main) {
757
- for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
781
+ for (let dir = dirname2(realpathSync2(entry));; dir = dirname2(dir)) {
758
782
  try {
759
- const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
783
+ const { version } = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
760
784
  if (typeof version === "string")
761
785
  return version;
762
786
  } catch {}
@@ -764,7 +788,7 @@ function packageVersion(entry = Bun.main) {
764
788
  return "0.0.0";
765
789
  }
766
790
  }
767
- async function runCli(cli, argv = process8.argv.slice(2)) {
791
+ async function runCli(cli, argv = scriptArgs()) {
768
792
  const version = cli.version ?? packageVersion();
769
793
  if (argv[0] === COMPLETE)
770
794
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -847,6 +871,16 @@ function uuidV4() {
847
871
  return crypto.randomUUID();
848
872
  }
849
873
 
874
+ // src/ip.ts
875
+ var IP_SERVICE = "https://ipecho.net/plain";
876
+ async function publicIp(family, service = IP_SERVICE) {
877
+ const child = Bun.spawn(["curl", "--silent", "--show-error", "--fail", "--max-time", "10", ...family === undefined ? [] : [`-${family}`], service], { stdout: "pipe", stderr: "pipe" });
878
+ const [out, err, code] = await Promise.all([child.stdout.text(), child.stderr.text(), child.exited]);
879
+ if (code !== 0)
880
+ throw new Error(err.trim() === "" ? `curl exited ${code}` : err.trim());
881
+ return out.trim();
882
+ }
883
+
850
884
  // src/time.ts
851
885
  var UNITS = [["d", 86400000], ["h", 3600000], ["m", 60000], ["s", 1000]];
852
886
  var DURATION_UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
@@ -1042,7 +1076,7 @@ async function bytesInput(argument, what) {
1042
1076
  return new Uint8Array(await Bun.stdin.arrayBuffer());
1043
1077
  }
1044
1078
  function printRows(rows) {
1045
- const { cyan } = paint(process10.stdout);
1079
+ const { cyan } = paint(process11.stdout);
1046
1080
  const width = Math.max(...rows.map(([label]) => label.length));
1047
1081
  for (const [label, value] of rows)
1048
1082
  console.log(`${cyan(label.padEnd(width))} ${value}`);
@@ -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);
@@ -1105,7 +1139,7 @@ async function jwt(args) {
1105
1139
  printJson({ header: decoded.header, payload: decoded.payload, claims, signatureBytes: decoded.signatureBytes });
1106
1140
  return 0;
1107
1141
  }
1108
- const { bold } = paint(process10.stdout);
1142
+ const { bold } = paint(process11.stdout);
1109
1143
  console.log(`${bold("header")}
1110
1144
  ${JSON.stringify(decoded.header, null, 2)}
1111
1145
 
@@ -1258,8 +1292,35 @@ async function hash(args) {
1258
1292
  console.log(digest);
1259
1293
  return 0;
1260
1294
  }
1295
+ var IP_USAGE = `dev ip [-4|-6]: the public IP address of this host, as a web service sees it
1296
+
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.`;
1299
+ async function ip(args) {
1300
+ 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?}") }, {
1301
+ replaces: "curl https://ipecho.net/plain typed from memory",
1302
+ examples: ["dev ip", ["dev ip -6", "the IPv6 address"]]
1303
+ });
1304
+ if (values[4] === true && values[6] === true)
1305
+ badUsage("-4 and -6 cannot be combined");
1306
+ let family;
1307
+ if (values[4] === true)
1308
+ family = 4;
1309
+ else if (values[6] === true)
1310
+ family = 6;
1311
+ try {
1312
+ const address = await publicIp(family);
1313
+ if (values.json === true)
1314
+ printJson(family === undefined ? { ip: address } : { ip: address, family });
1315
+ else
1316
+ console.log(address);
1317
+ return 0;
1318
+ } catch (error) {
1319
+ return fail(`could not read the public address: ${error instanceof Error ? error.message : String(error)}`, 1);
1320
+ }
1321
+ }
1261
1322
  if (import.meta.main) {
1262
- process10.exitCode = await runCli({
1323
+ process11.exitCode = await runCli({
1263
1324
  name: "dev",
1264
1325
  about: "small developer utilities: passwords and bcrypt hashes, JWTs, timestamps, UUIDs, base64, URLs and file hashes",
1265
1326
  replaces: "openssl rand, htpasswd, jwt.io, date -d, uuidgen, base64, sha256sum and one-off scripts for each",
@@ -1272,13 +1333,15 @@ if (import.meta.main) {
1272
1333
  ulid: { summary: "random ULIDs", run: async (args) => Promise.resolve(ulidCommand(args)) },
1273
1334
  b64: { summary: "base64 encode or decode, standard or URL-safe", run: b64 },
1274
1335
  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 }
1336
+ hash: { summary: "sha256, sha1, md5 or sha512 of a file or stdin", run: hash },
1337
+ ip: { summary: "the public IP address of this host, IPv4 or IPv6", run: ip }
1276
1338
  }
1277
1339
  });
1278
1340
  }
1279
1341
  export {
1280
1342
  b64,
1281
1343
  hash,
1344
+ ip,
1282
1345
  jwt,
1283
1346
  password,
1284
1347
  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.0",
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.1"
40
40
  }
41
41
  }