@agledger/cli 2.1.0 → 2.2.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 (48) hide show
  1. package/README.md +64 -22
  2. package/SKILL.md +15 -14
  3. package/bin/run.js +2 -2
  4. package/dist/api-client.d.ts +7 -0
  5. package/dist/api-client.js +44 -8
  6. package/dist/base.d.ts +91 -22
  7. package/dist/base.js +76 -47
  8. package/dist/cli/command.d.ts +58 -0
  9. package/dist/cli/command.js +44 -0
  10. package/dist/cli/flags.d.ts +76 -0
  11. package/dist/cli/flags.js +12 -0
  12. package/dist/cli/help.d.ts +6 -0
  13. package/dist/cli/help.js +107 -0
  14. package/dist/cli/index.d.ts +3 -0
  15. package/dist/cli/index.js +3 -0
  16. package/dist/cli/main.d.ts +22 -0
  17. package/dist/cli/main.js +223 -0
  18. package/dist/cli/parse.d.ts +20 -0
  19. package/dist/cli/parse.js +138 -0
  20. package/dist/commands/api.d.ts +106 -18
  21. package/dist/commands/api.js +103 -12
  22. package/dist/commands/auth.d.ts +35 -6
  23. package/dist/commands/auth.js +1 -1
  24. package/dist/commands/config.d.ts +43 -8
  25. package/dist/commands/config.js +9 -8
  26. package/dist/commands/discover.d.ts +35 -6
  27. package/dist/commands/docs.d.ts +41 -7
  28. package/dist/commands/docs.js +4 -4
  29. package/dist/commands/help-json.d.ts +39 -7
  30. package/dist/commands/help-json.js +27 -45
  31. package/dist/commands/list-commands.d.ts +36 -7
  32. package/dist/commands/list-commands.js +2 -2
  33. package/dist/commands/login.d.ts +66 -10
  34. package/dist/commands/login.js +30 -9
  35. package/dist/commands/logout.d.ts +41 -7
  36. package/dist/commands/logout.js +8 -8
  37. package/dist/commands/verify.d.ts +97 -13
  38. package/dist/commands/verify.js +84 -27
  39. package/dist/oidc.d.ts +47 -0
  40. package/dist/oidc.js +162 -3
  41. package/dist/util/config.d.ts +16 -1
  42. package/dist/util/config.js +50 -14
  43. package/dist/util/field-parser.d.ts +3 -1
  44. package/dist/util/field-parser.js +11 -5
  45. package/package.json +9 -21
  46. package/dist/hooks/command-not-found.d.ts +0 -3
  47. package/dist/hooks/command-not-found.js +0 -63
  48. package/oclif.manifest.json +0 -872
package/dist/base.js CHANGED
@@ -5,14 +5,14 @@
5
5
  *
6
6
  * NO_COLOR (no-color.org): the CLI emits plain JSON to both stdout (results)
7
7
  * and stderr (errors) with no ANSI escapes of its own, so it is trivially
8
- * NO_COLOR-conformant by construction. oclif's own help/error rendering also
9
- * honors NO_COLOR via chalk's built-in detection, so no explicit check needed.
8
+ * NO_COLOR-conformant by construction, as is the help text.
10
9
  */
11
10
  import { readFileSync } from 'node:fs';
12
- import { Command, Errors, Flags } from '@oclif/core';
11
+ import { resolve } from 'node:path';
12
+ import { Command, ExitError, Flags, beforeTerminator } from './cli/index.js';
13
13
  import { ApiClient } from './api-client.js';
14
- import { DelegationToken, OIDC_ENV, ON_BEHALF_OF_ENV, OidcCertCredential, OidcExchangeError, OidcTokenSourceError, } from './oidc.js';
15
- import { readConfig } from './util/config.js';
14
+ import { AgentKeysFileError, DelegationToken, OIDC_ENV, ON_BEHALF_OF_ENV, OidcCertCredential, OidcExchangeError, OidcTokenSourceError, } from './oidc.js';
15
+ import { ConfigFileError, getProfile, readConfig } from './util/config.js';
16
16
  /** Semantic exit codes for agent consumption. Stable across releases. */
17
17
  export const ExitCode = {
18
18
  SUCCESS: 0,
@@ -48,6 +48,10 @@ export const ErrorCode = {
48
48
  INVALID_METHOD: 'INVALID_METHOD',
49
49
  INVALID_FIELD: 'INVALID_FIELD',
50
50
  FILE_READ_ERROR: 'FILE_READ_ERROR',
51
+ /** The `--output` file cannot be written. */
52
+ FILE_WRITE_ERROR: 'FILE_WRITE_ERROR',
53
+ /** `--paginate` on a response that is not a list. */
54
+ NOT_PAGINATED: 'NOT_PAGINATED',
51
55
  TIMEOUT: 'TIMEOUT',
52
56
  NETWORK_ERROR: 'NETWORK_ERROR',
53
57
  UNKNOWN_ERROR: 'UNKNOWN_ERROR',
@@ -58,8 +62,8 @@ export const ErrorCode = {
58
62
  * was made, so an agent holding only a URL had to shell out to curl for exactly
59
63
  * the bootstrap arc the product optimizes for.
60
64
  *
61
- * Read-only by construction: only GET qualifies, so this can never wave through
62
- * a write. Anything not listed still requires a key, and the Server remains the
65
+ * Read-only by construction: only GET qualifies, so this can never let
66
+ * a write through. Anything not listed still requires a key, and the Server remains the
63
67
  * authority: a path that starts requiring auth simply answers 401.
64
68
  */
65
69
  const PUBLIC_GET_PATHS = new Set([
@@ -104,9 +108,9 @@ export function envOnBehalfOfSource() {
104
108
  return undefined;
105
109
  }
106
110
  /** Whether a flag was passed on the command line (`--flag value` or `--flag=value`),
107
- * as opposed to reaching oclif through its `env` binding. */
111
+ * as opposed to reaching the parser through a flag's `env` binding. */
108
112
  export function argvHasFlag(flag) {
109
- return process.argv.some((a) => a === flag || a.startsWith(`${flag}=`));
113
+ return beforeTerminator(process.argv).some((a) => a === flag || a.startsWith(`${flag}=`));
110
114
  }
111
115
  /**
112
116
  * Why an API URL cannot be used, or undefined when it can. Only an absolute
@@ -124,8 +128,15 @@ export function apiUrlProblem(url) {
124
128
  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
125
129
  return `has scheme '${parsed.protocol}', and only http: and https: are supported`;
126
130
  }
131
+ if (parsed.username !== '' || parsed.password !== '') {
132
+ return 'carries credentials in the URL, which are not accepted (pass the key with --api-key or AGLEDGER_API_KEY)';
133
+ }
127
134
  return undefined;
128
135
  }
136
+ /** A URL with anything before an `@` in its authority masked, so a password never reaches a message. */
137
+ export function redactUrl(url) {
138
+ return url.replace(/(\/\/)[^/?#@\s]*@/, '$1<redacted>@');
139
+ }
129
140
  /** Where the API URL in use came from, for a CONFIG_ERROR that has to name it. */
130
141
  function apiUrlOrigin(fromFlagOrEnv, profileName) {
131
142
  if (!fromFlagOrEnv)
@@ -179,25 +190,32 @@ export class BaseCommand extends Command {
179
190
  default: false,
180
191
  }),
181
192
  };
193
+ /**
194
+ * The base flags for a command that makes no API call: the credential flags
195
+ * stay accepted (a script may pass them to every command) but are left out of --help.
196
+ */
197
+ static offlineFlags = {
198
+ json: BaseCommand.baseFlags.json,
199
+ quiet: BaseCommand.baseFlags.quiet,
200
+ 'api-key': { ...BaseCommand.baseFlags['api-key'], hidden: true },
201
+ 'api-url': { ...BaseCommand.baseFlags['api-url'], hidden: true },
202
+ profile: { ...BaseCommand.baseFlags.profile, hidden: true },
203
+ verbose: { ...BaseCommand.baseFlags.verbose, hidden: true },
204
+ };
182
205
  get isJson() {
183
- return process.argv.includes('--json') || !process.stdout.isTTY;
206
+ return this.parsedOutputFlags().json || !process.stdout.isTTY;
184
207
  }
185
208
  get isQuiet() {
186
- return process.argv.includes('--quiet');
209
+ return this.parsedOutputFlags().quiet;
187
210
  }
188
- /**
189
- * oclif's own refusals (an unknown flag, a missing argument, a bad enum
190
- * value) reach here before any command code runs. Under --quiet they exit
191
- * as a usage error with nothing written, as every other error does; an
192
- * explicit `this.exit(code)` passes through untouched, since it already
193
- * carries the code the command chose.
194
- */
195
- async catch(err) {
196
- if (this.isQuiet && !(err instanceof Errors.ExitError)) {
197
- const exit = err.oclif?.exit;
198
- this.exit(typeof exit === 'number' ? exit : ExitCode.GENERAL_ERROR);
199
- }
200
- return super.catch(err);
211
+ /** --json and --quiet as the parser read them, so a value such as `--data --quiet` is not a flag. */
212
+ parsedOutputFlags() {
213
+ const flags = this.parsedFlags;
214
+ if (flags)
215
+ return { json: flags.json === true, quiet: flags.quiet === true };
216
+ // Before parsing (or when parsing refused the line) the best reading is the raw argv.
217
+ const argv = beforeTerminator(this.argv);
218
+ return { json: argv.includes('--json'), quiet: argv.includes('--quiet') };
201
219
  }
202
220
  /** Write one diagnostic line to stderr under --verbose. Callers pass no secrets. */
203
221
  verboseLog(flags, event) {
@@ -208,7 +226,7 @@ export class BaseCommand extends Command {
208
226
  * Resolve which credential a command uses, without calling anything.
209
227
  *
210
228
  * Precedence, highest first:
211
- * 1. An API key from `--api-key` or `AGLEDGER_API_KEY` (oclif merges the
229
+ * 1. An API key from `--api-key` or `AGLEDGER_API_KEY` (the parser merges the
212
230
  * two into `flags['api-key']`).
213
231
  * 2. `AGLEDGER_OIDC_TOKEN_CMD`, then `AGLEDGER_OIDC_TOKEN_FILE`.
214
232
  * 3. The selected profile (`--profile <name>`, else the active one): its
@@ -222,8 +240,10 @@ export class BaseCommand extends Command {
222
240
  resolveCredential(flags) {
223
241
  const config = readConfig();
224
242
  const profileName = flags.profile ?? config.activeProfile;
225
- const profile = profileName ? config.profiles[profileName] : undefined;
243
+ const profile = profileName ? getProfile(config, profileName) : undefined;
226
244
  const envAgentId = process.env[OIDC_ENV.AGENT_ID] || undefined;
245
+ const envKeysPath = process.env[OIDC_ENV.AGENT_KEYS_FILE];
246
+ const envKeysFile = envKeysPath ? resolve(envKeysPath) : undefined;
227
247
  // Treat an empty-string flag/env (e.g. AGLEDGER_API_KEY="") as absent so the
228
248
  // later sources still apply.
229
249
  const flagKey = flags['api-key'] || undefined;
@@ -234,7 +254,13 @@ export class BaseCommand extends Command {
234
254
  const fromEnv = envOidcSource();
235
255
  if (fromEnv) {
236
256
  return {
237
- credential: { kind: 'oidc', source: fromEnv, ...(envAgentId ? { agentId: envAgentId } : {}), from: 'env' },
257
+ credential: {
258
+ kind: 'oidc',
259
+ source: fromEnv,
260
+ ...(envAgentId ? { agentId: envAgentId } : {}),
261
+ ...(envKeysFile ? { agentKeysFile: envKeysFile } : {}),
262
+ from: 'env',
263
+ },
238
264
  profileName,
239
265
  profile,
240
266
  };
@@ -249,8 +275,15 @@ export class BaseCommand extends Command {
249
275
  const fromProfile = profileName ? profileOidcSource(profileName, profile) : undefined;
250
276
  if (fromProfile) {
251
277
  const agentId = envAgentId ?? profile?.oidc?.agentId;
278
+ const agentKeysFile = envKeysFile ?? profile?.oidc?.agentKeysFile;
252
279
  return {
253
- credential: { kind: 'oidc', source: fromProfile, ...(agentId ? { agentId } : {}), from: 'profile' },
280
+ credential: {
281
+ kind: 'oidc',
282
+ source: fromProfile,
283
+ ...(agentId ? { agentId } : {}),
284
+ ...(agentKeysFile ? { agentKeysFile } : {}),
285
+ from: 'profile',
286
+ },
254
287
  profileName,
255
288
  profile,
256
289
  };
@@ -321,7 +354,7 @@ export class BaseCommand extends Command {
321
354
  requireUsableApiUrl(apiUrl, origin) {
322
355
  const problem = apiUrlProblem(apiUrl);
323
356
  if (problem) {
324
- this.failWith(ErrorCode.CONFIG_ERROR, `The API URL from ${origin} (${JSON.stringify(apiUrl)}) ${problem}.`, ExitCode.USAGE_ERROR, 'Give the full base URL of your AGLedger Server, scheme included, for example https://agledger.internal or http://localhost:3000.');
357
+ this.failWith(ErrorCode.CONFIG_ERROR, `The API URL from ${origin} (${JSON.stringify(redactUrl(apiUrl))}) ${problem}.`, ExitCode.USAGE_ERROR, 'Give the full base URL of your AGLedger Server, scheme included, for example https://agledger.internal or http://localhost:3000.');
325
358
  }
326
359
  }
327
360
  /** Build a cert credential for one invocation. Its key pair never leaves memory. */
@@ -329,6 +362,7 @@ export class BaseCommand extends Command {
329
362
  return new OidcCertCredential({
330
363
  source: credential.source,
331
364
  ...(credential.agentId ? { agentId: credential.agentId } : {}),
365
+ ...(credential.agentKeysFile ? { agentKeysFile: credential.agentKeysFile } : {}),
332
366
  userAgent: `agledger-cli/${this.config.version}`,
333
367
  log: (event) => this.verboseLog(flags, event),
334
368
  });
@@ -344,6 +378,7 @@ export class BaseCommand extends Command {
344
378
  source: credential.source.origin,
345
379
  ...(credential.source.kind === 'file' ? { tokenFile: credential.source.path } : {}),
346
380
  ...(credential.agentId ? { agentId: credential.agentId } : {}),
381
+ ...(credential.agentKeysFile ? { agentKeysFile: credential.agentKeysFile } : {}),
347
382
  };
348
383
  case 'none':
349
384
  return { credential: 'none' };
@@ -359,18 +394,16 @@ export class BaseCommand extends Command {
359
394
  const { credential, profileName, profile } = this.resolveCredential(flags);
360
395
  this.requireNamedProfile(flags, profile);
361
396
  const flagUrl = flags['api-url'] || undefined;
362
- // Null, not a placeholder. `agledger.example.com` was removed from
363
- // `createApiClient`, which now refuses to build a client without a URL, but
364
- // this sibling kept it. The whole job of --dry-run is to report what the
365
- // real call would do, and it was reporting a host the real call refuses to
366
- // use: the unconfigured case printed agledger.example.com and exited 0
367
- // while the same invocation without --dry-run exited 2 with CONFIG_ERROR.
397
+ // Null, not a placeholder host. `createApiClient` refuses to build a client
398
+ // without a URL, and --dry-run reports what the real call would do, so an
399
+ // unconfigured run reports `apiUrl: null` and the CONFIG_ERROR the real
400
+ // call raises (exit 2).
368
401
  const apiUrl = flagUrl ?? profile?.apiUrl ?? null;
369
402
  const problem = apiUrl === null ? undefined : apiUrlProblem(apiUrl);
370
403
  const mask = (k) => (k.length <= 4 ? '****' : `****${k.slice(-4)}`);
371
404
  const source = credential.kind === 'none' ? 'none' : credential.from;
372
405
  return {
373
- apiUrl,
406
+ apiUrl: apiUrl === null ? null : redactUrl(apiUrl),
374
407
  apiKey: credential.kind === 'api-key' ? mask(credential.key) : null,
375
408
  source,
376
409
  credential: credential.kind === 'oidc' ? 'oidc-cert' : credential.kind,
@@ -422,12 +455,7 @@ export class BaseCommand extends Command {
422
455
  output(data) {
423
456
  if (this.isQuiet)
424
457
  return;
425
- if (this.isJson) {
426
- process.stdout.write(JSON.stringify(data) + '\n');
427
- }
428
- else {
429
- process.stdout.write(JSON.stringify(data, null, 2) + '\n');
430
- }
458
+ process.stdout.write(this.isJson ? JSON.stringify(data) + '\n' : JSON.stringify(data, null, 2) + '\n');
431
459
  }
432
460
  outputNdjson(item) {
433
461
  if (this.isQuiet)
@@ -458,11 +486,9 @@ export class BaseCommand extends Command {
458
486
  return JSON.parse(source);
459
487
  }
460
488
  catch (err) {
461
- if (err instanceof Error && err.message.startsWith('EEXIT:'))
462
- throw err;
463
489
  this.failWith(ErrorCode.INVALID_JSON_INPUT, `${fieldName} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`, ExitCode.USAGE_ERROR, suggestion ??
464
490
  'Check that the JSON is properly quoted. For complex payloads, use --input <file> instead of --data.');
465
- throw new Error('unreachable');
491
+ throw new Error('unreachable', { cause: err });
466
492
  }
467
493
  }
468
494
  /** Read and parse a JSON file with structured errors. `-` reads from stdin. */
@@ -481,7 +507,7 @@ export class BaseCommand extends Command {
481
507
  // Same reason the parse suggestion is overridable: the default names
482
508
  // --input, which only the `api` command has.
483
509
  suggestion ?? 'Check that the path exists and is readable, or pipe JSON to stdin with --input -.');
484
- throw new Error('unreachable');
510
+ throw new Error('unreachable', { cause: err });
485
511
  }
486
512
  return this.parseJsonInput(content, path === '-' ? 'stdin' : `${fieldName} ${path}`, suggestion);
487
513
  }
@@ -519,13 +545,16 @@ export class BaseCommand extends Command {
519
545
  throw new Error('unreachable');
520
546
  }
521
547
  handleError(err) {
522
- if (err instanceof Error && err.message.startsWith('EEXIT:'))
548
+ if (err instanceof ExitError || err instanceof ConfigFileError)
523
549
  throw err;
524
550
  if (err instanceof OidcTokenSourceError) {
525
551
  this.failWith(ErrorCode.OIDC_TOKEN_SOURCE_FAILED, err.message, ExitCode.AUTH_ERROR, err.kind === 'command'
526
552
  ? `Run the command in ${err.origin} by hand and check it prints one JWT on stdout and exits 0.`
527
553
  : `Check the file named by ${err.origin} exists, is readable, and holds one JWT.`);
528
554
  }
555
+ if (err instanceof AgentKeysFileError) {
556
+ this.failWith(ErrorCode.FILE_WRITE_ERROR, err.message, ExitCode.GENERAL_ERROR, `Fix or move ${err.path} (named by ${OIDC_ENV.AGENT_KEYS_FILE} or the profile's oidc.agentKeysFile), or unset it. Nothing was signed under the new cert.`);
557
+ }
529
558
  if (err instanceof OidcExchangeError) {
530
559
  // The Server's error body is forwarded as it came (its recoveryHint is
531
560
  // the useful part), with the OIDC token scrubbed out of it.
@@ -0,0 +1,58 @@
1
+ import type { ArgDef, FlagDef, ParsedArgs, ParsedFlags } from './flags.js';
2
+ /** What a command needs to know about the program it runs in. */
3
+ export interface CliConfig {
4
+ /** The executable name, as the usage lines print it. */
5
+ readonly bin: string;
6
+ /** The package name. */
7
+ readonly name: string;
8
+ readonly version: string;
9
+ /** The package description, printed at the top of the root help. */
10
+ readonly description: string;
11
+ }
12
+ /** Thrown by `exit()` to unwind to the entry point, which ends the process with the code. */
13
+ export declare class ExitError extends Error {
14
+ readonly exitCode: number;
15
+ constructor(exitCode: number);
16
+ }
17
+ /** The static side of a command: what `parse` and `--help` read. */
18
+ export interface CommandClass {
19
+ readonly description?: string;
20
+ readonly examples?: readonly string[];
21
+ /** A usage line that replaces the generated one. */
22
+ readonly usage?: string;
23
+ readonly args?: Record<string, ArgDef>;
24
+ readonly flags?: Record<string, FlagDef>;
25
+ readonly baseFlags?: Record<string, FlagDef>;
26
+ new (argv: readonly string[], config: CliConfig): Command;
27
+ }
28
+ /** A command's flags: the base flags, then its own (which may redefine one in place). */
29
+ export declare function allFlags(command: {
30
+ flags?: Record<string, FlagDef>;
31
+ baseFlags?: Record<string, FlagDef>;
32
+ }): Record<string, FlagDef>;
33
+ export declare abstract class Command {
34
+ protected readonly argv: readonly string[];
35
+ readonly config: CliConfig;
36
+ static description?: string;
37
+ static examples?: readonly string[];
38
+ static usage?: string;
39
+ static args?: Record<string, ArgDef>;
40
+ static flags?: Record<string, FlagDef>;
41
+ /** Flags every command accepts, listed before the command's own. */
42
+ static baseFlags?: Record<string, FlagDef>;
43
+ /** The flags `parse` read, kept so a command reads --json and --quiet from them rather than from raw argv. */
44
+ protected parsedFlags?: Record<string, unknown>;
45
+ constructor(argv: readonly string[], config: CliConfig);
46
+ abstract run(): Promise<void>;
47
+ /** Parse this invocation's argv against the command's own definitions. */
48
+ protected parse<C extends {
49
+ args?: Record<string, ArgDef>;
50
+ flags?: Record<string, FlagDef>;
51
+ baseFlags?: Record<string, FlagDef>;
52
+ }>(command: C): Promise<{
53
+ args: ParsedArgs<NonNullable<C['args']>>;
54
+ flags: ParsedFlags<NonNullable<C['baseFlags']> & NonNullable<C['flags']>>;
55
+ }>;
56
+ /** End the command with an exit code. Never returns. */
57
+ protected exit(code?: number): never;
58
+ }
@@ -0,0 +1,44 @@
1
+ import { parse } from './parse.js';
2
+ /** Thrown by `exit()` to unwind to the entry point, which ends the process with the code. */
3
+ export class ExitError extends Error {
4
+ exitCode;
5
+ constructor(exitCode) {
6
+ super(`exit ${exitCode}`);
7
+ this.name = 'ExitError';
8
+ this.exitCode = exitCode;
9
+ }
10
+ }
11
+ /** A command's flags: the base flags, then its own (which may redefine one in place). */
12
+ export function allFlags(command) {
13
+ return { ...command.baseFlags, ...command.flags };
14
+ }
15
+ export class Command {
16
+ argv;
17
+ config;
18
+ static description;
19
+ static examples;
20
+ static usage;
21
+ static args;
22
+ static flags;
23
+ /** Flags every command accepts, listed before the command's own. */
24
+ static baseFlags;
25
+ /** The flags `parse` read, kept so a command reads --json and --quiet from them rather than from raw argv. */
26
+ parsedFlags;
27
+ constructor(argv, config) {
28
+ this.argv = argv;
29
+ this.config = config;
30
+ }
31
+ /** Parse this invocation's argv against the command's own definitions. */
32
+ parse(command) {
33
+ const { args, flags } = parse(this.argv, command.args ?? {}, allFlags(command));
34
+ this.parsedFlags = flags;
35
+ return Promise.resolve({
36
+ args: args,
37
+ flags: flags,
38
+ });
39
+ }
40
+ /** End the command with an exit code. Never returns. */
41
+ exit(code = 0) {
42
+ throw new ExitError(code);
43
+ }
44
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Flag and argument definitions for the CLI's commands. A definition is plain
3
+ * data: `parse.ts` reads it to turn argv into typed values and `help.ts` reads
4
+ * it to render `--help`, so a flag is described once.
5
+ */
6
+ /** A flag that takes a value (`--name value`, `--name=value`, `-n value`). */
7
+ export interface OptionFlag {
8
+ readonly type: 'option';
9
+ readonly description?: string;
10
+ /** One-letter alias, used as `-F`. */
11
+ readonly char?: string;
12
+ /** Repeatable: every occurrence is collected into an array. */
13
+ readonly multiple?: boolean;
14
+ /**
15
+ * With `multiple`: take only the next argument per occurrence. Without it,
16
+ * a repeatable flag also takes the positional arguments that follow it.
17
+ */
18
+ readonly multipleNonGreedy?: boolean;
19
+ /** Environment variable that supplies the value when the flag is absent. */
20
+ readonly env?: string;
21
+ readonly default?: string;
22
+ readonly hidden?: boolean;
23
+ readonly required?: boolean;
24
+ /** Accepted values; anything else is a usage error. */
25
+ readonly options?: readonly string[];
26
+ }
27
+ /** A flag that takes no value. Absent means false. */
28
+ export interface BooleanFlag {
29
+ readonly type: 'boolean';
30
+ readonly description?: string;
31
+ readonly char?: string;
32
+ readonly default?: boolean;
33
+ readonly hidden?: boolean;
34
+ }
35
+ export type FlagDef = OptionFlag | BooleanFlag;
36
+ /** A positional argument. Positionals are matched in declaration order. */
37
+ export interface ArgDef {
38
+ readonly description?: string;
39
+ readonly required?: boolean;
40
+ readonly options?: readonly string[];
41
+ }
42
+ export declare const Flags: {
43
+ string: <const O extends Omit<OptionFlag, 'type'>>(opts?: O) => O & {
44
+ readonly type: 'option';
45
+ };
46
+ boolean: <const O extends Omit<BooleanFlag, 'type'>>(opts?: O) => O & {
47
+ readonly type: 'boolean';
48
+ };
49
+ };
50
+ export declare const Args: {
51
+ string: <const O extends ArgDef>(opts?: O) => O;
52
+ };
53
+ type OptionValue<F> = F extends {
54
+ multiple: true;
55
+ } ? F extends {
56
+ default: string;
57
+ } | {
58
+ required: true;
59
+ } ? string[] : string[] | undefined : F extends {
60
+ default: string;
61
+ } | {
62
+ required: true;
63
+ } ? string : string | undefined;
64
+ /** The value a parsed flag takes, from its definition. */
65
+ export type FlagValue<F> = F extends {
66
+ type: 'boolean';
67
+ } ? boolean : OptionValue<F>;
68
+ export type ParsedFlags<D extends Record<string, FlagDef>> = {
69
+ [K in keyof D]: FlagValue<D[K]>;
70
+ };
71
+ export type ParsedArgs<D extends Record<string, ArgDef>> = {
72
+ [K in keyof D]: D[K] extends {
73
+ required: true;
74
+ } ? string : string | undefined;
75
+ };
76
+ export {};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Flag and argument definitions for the CLI's commands. A definition is plain
3
+ * data: `parse.ts` reads it to turn argv into typed values and `help.ts` reads
4
+ * it to render `--help`, so a flag is described once.
5
+ */
6
+ export const Flags = {
7
+ string: (opts) => ({ ...opts, type: 'option' }),
8
+ boolean: (opts) => ({ ...opts, type: 'boolean' }),
9
+ };
10
+ export const Args = {
11
+ string: (opts) => ({ ...opts }),
12
+ };
@@ -0,0 +1,6 @@
1
+ import { type CliConfig, type CommandClass } from './command.js';
2
+ /** `agledger <command> --help`. */
3
+ export declare function commandHelp(config: CliConfig, id: string, command: CommandClass): string;
4
+ /** `agledger --help`: the package description and every command. */
5
+ export declare function rootHelp(config: CliConfig, commands: Record<string, CommandClass>): string;
6
+ export declare function versionLine(config: CliConfig): string;
@@ -0,0 +1,107 @@
1
+ import { allFlags } from './command.js';
2
+ function width() {
3
+ const columns = process.stdout.columns || Number(process.env.COLUMNS) || 80;
4
+ return Math.min(Math.max(columns, 40), 100);
5
+ }
6
+ /** Wrap text to `max` columns; continuation lines start with `indent`. */
7
+ function wrap(text, max, indent, first = indent) {
8
+ const lines = [];
9
+ let line = first;
10
+ let empty = true;
11
+ for (const word of text.split(/\s+/).filter(Boolean)) {
12
+ if (!empty && line.length + 1 + word.length > max) {
13
+ lines.push(line);
14
+ line = indent;
15
+ empty = true;
16
+ }
17
+ line += (empty ? '' : ' ') + word;
18
+ empty = false;
19
+ }
20
+ lines.push(line);
21
+ return lines.join('\n');
22
+ }
23
+ /** Rows of `name description`, with the descriptions aligned and wrapped. */
24
+ function table(rows, indent) {
25
+ const max = width();
26
+ const pad = Math.max(...rows.map(([name]) => name.length)) + 2;
27
+ return rows
28
+ .map(([name, text]) => {
29
+ const gap = ' '.repeat(pad - name.length);
30
+ return wrap(text, max, indent + ' '.repeat(pad), `${indent}${name}${gap}`);
31
+ })
32
+ .join('\n');
33
+ }
34
+ function visible(flags) {
35
+ return Object.entries(flags).filter(([, def]) => !def.hidden);
36
+ }
37
+ function flagUsage(name, def) {
38
+ const long = def.type === 'boolean' ? `--${name}` : `--${name} <value>`;
39
+ const short = def.char ? (def.type === 'boolean' ? `-${def.char}` : `-${def.char} <value>`) : undefined;
40
+ const repeat = def.type === 'option' && def.multiple ? '...' : '';
41
+ return `[${short ?? long}${repeat}]`;
42
+ }
43
+ function usageLine(bin, id, command) {
44
+ if (command.usage)
45
+ return wrap(command.usage, width(), ' ', ` $ ${bin} `);
46
+ const args = Object.entries(command.args ?? {}).map(([name, def]) => def.required ? name.toUpperCase() : `[${name.toUpperCase()}]`);
47
+ const flags = visible(allFlags(command)).map(([name, def]) => flagUsage(name, def));
48
+ return wrap([id, ...args, ...flags].join(' '), width(), ' ', ` $ ${bin} `);
49
+ }
50
+ function flagHeading(name, def) {
51
+ const long = def.type === 'boolean' ? `--${name}` : `--${name}=<value>${def.multiple ? '...' : ''}`;
52
+ return def.char ? `-${def.char}, ${long}` : long;
53
+ }
54
+ function flagNotes(def) {
55
+ const notes = [];
56
+ if (def.type === 'option') {
57
+ if (def.env)
58
+ notes.push(`[env: ${def.env}]`);
59
+ if (def.default !== undefined)
60
+ notes.push(`[default: ${def.default}]`);
61
+ if (def.options)
62
+ notes.push(`(${def.options.join('|')})`);
63
+ }
64
+ return notes.join(' ');
65
+ }
66
+ /** `agledger <command> --help`. */
67
+ export function commandHelp(config, id, command) {
68
+ const sections = [];
69
+ if (command.description)
70
+ sections.push(wrap(command.description, width(), ''));
71
+ sections.push(`USAGE\n${usageLine(config.bin, id, command)}`);
72
+ const args = Object.entries(command.args ?? {});
73
+ if (args.length > 0) {
74
+ const rows = args.map(([name, def]) => [
75
+ def.required ? name.toUpperCase() : `[${name.toUpperCase()}]`,
76
+ [def.options ? `(${def.options.join('|')})` : '', def.description ?? ''].filter(Boolean).join(' '),
77
+ ]);
78
+ sections.push(`ARGUMENTS\n${table(rows, ' ')}`);
79
+ }
80
+ const flags = visible(allFlags(command)).sort(([a], [b]) => a.localeCompare(b));
81
+ if (flags.length > 0) {
82
+ const body = flags.map(([name, def]) => {
83
+ const text = [flagNotes(def), def.description ?? ''].filter(Boolean).join(' ');
84
+ return ` ${flagHeading(name, def)}\n${wrap(text, width(), ' ')}`;
85
+ });
86
+ sections.push(`FLAGS\n${body.join('\n\n')}`);
87
+ }
88
+ if (command.examples && command.examples.length > 0) {
89
+ sections.push(`EXAMPLES\n${command.examples.map((example) => ` $ ${example}`).join('\n\n')}`);
90
+ }
91
+ return sections.join('\n\n') + '\n';
92
+ }
93
+ /** `agledger --help`: the package description and every command. */
94
+ export function rootHelp(config, commands) {
95
+ const rows = Object.entries(commands)
96
+ .sort(([a], [b]) => a.localeCompare(b))
97
+ .map(([id, command]) => [id, command.description ?? '']);
98
+ return ([
99
+ wrap(config.description, width(), ''),
100
+ `VERSION\n ${versionLine(config)}`,
101
+ `USAGE\n $ ${config.bin} [COMMAND]`,
102
+ `COMMANDS\n${table(rows, ' ')}`,
103
+ ].join('\n\n') + '\n');
104
+ }
105
+ export function versionLine(config) {
106
+ return `${config.name}/${config.version} ${process.platform}-${process.arch} node-${process.version}`;
107
+ }
@@ -0,0 +1,3 @@
1
+ export { Command, allFlags, ExitError, type CliConfig, type CommandClass } from './command.js';
2
+ export { Args, Flags } from './flags.js';
3
+ export { UsageError, beforeTerminator } from './parse.js';
@@ -0,0 +1,3 @@
1
+ export { Command, allFlags, ExitError } from './command.js';
2
+ export { Args, Flags } from './flags.js';
3
+ export { UsageError, beforeTerminator } from './parse.js';
@@ -0,0 +1,22 @@
1
+ import { type CliConfig, type CommandClass } from './command.js';
2
+ /**
3
+ * Every command, loaded on demand so `agledger verify` does not pay for the
4
+ * modules of the commands it does not run. `tests/commands.test.ts` holds
5
+ * this list to the files in `src/commands`.
6
+ */
7
+ export declare const COMMANDS: Record<string, () => Promise<{
8
+ default: CommandClass;
9
+ }>>;
10
+ /** Load one command's class by id, or undefined for an id that names none. */
11
+ export declare function loadCommand(id: string): Promise<CommandClass | undefined>;
12
+ export declare function loadConfig(): CliConfig;
13
+ /**
14
+ * The entry point: `--version`, `--help`, command lookup and dispatch. Exit
15
+ * codes: a command's own through `exit()`, 2 for a command line the parser
16
+ * refuses or a command that does not exist, 1 for anything unexpected.
17
+ *
18
+ * Global flags may come before the command (`agledger --json api GET /health`):
19
+ * the command is the first word that names one, and what surrounds it is the
20
+ * command's own argv.
21
+ */
22
+ export declare function main(argv: readonly string[]): Promise<void>;