@kjanat/dreamcli 3.0.0-rc.13 → 3.0.0-rc.15

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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,31 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [3.0.0-rc.15] - 2026-07-20
11
+
12
+ ### Added
13
+
14
+ - **Configurable flag order in help** — `.help({ flagOrder })` controls the
15
+ `Flags:` table order: `'alphabetical'` (default, short-aliased flags first
16
+ then alphabetical) or `'declaration'` (the order `.flag()` was called). For
17
+ full control, `.help({ sortFlags: (a, b) => number })` supplies a custom
18
+ comparator over flag names that wins over `flagOrder`. Both are also
19
+ accepted at runtime via `execute`/`run` `help` options.
20
+
21
+ ## [3.0.0-rc.14] - 2026-07-20
22
+
23
+ ### Added
24
+
25
+ - **Function-form examples** — `.example()` now accepts a
26
+ `(meta) => string` builder alongside the literal string. `meta` carries the
27
+ invoked program `name` (`help.binName`, falling back to the command name) and
28
+ `version`, resolved at render time, so examples reference the real program
29
+ name instead of hardcoding it and stay truthful under symlinks, `inheritName`,
30
+ and `npx x` vs a global install. The thunk resolves in both `--help` text
31
+ (composing with example highlighting) and `--json`/definition-schema output.
32
+ - **`ExampleMeta`** and **`ExampleCommand`** public types for annotating
33
+ function-form example builders.
34
+
10
35
  ## [3.0.0-rc.13] - 2026-07-20
11
36
 
12
37
  ### Changed
@@ -1275,7 +1300,9 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
1275
1300
  - MIT License.
1276
1301
  - Markdownlint configuration.
1277
1302
 
1278
- [Unreleased]: https://github.com/kjanat/dreamcli/compare/v3.0.0-rc.13...HEAD
1303
+ [Unreleased]: https://github.com/kjanat/dreamcli/compare/v3.0.0-rc.15...HEAD
1304
+ [3.0.0-rc.15]: https://github.com/kjanat/dreamcli/compare/v3.0.0-rc.14...v3.0.0-rc.15
1305
+ [3.0.0-rc.14]: https://github.com/kjanat/dreamcli/compare/v3.0.0-rc.13...v3.0.0-rc.14
1279
1306
  [3.0.0-rc.13]: https://github.com/kjanat/dreamcli/compare/v3.0.0-rc.12...v3.0.0-rc.13
1280
1307
  [3.0.0-rc.12]: https://github.com/kjanat/dreamcli/compare/v3.0.0-rc.11...v3.0.0-rc.12
1281
1308
  [3.0.0-rc.11]: https://github.com/kjanat/dreamcli/compare/v3.0.0-rc.10...v3.0.0-rc.11
@@ -153,6 +153,24 @@ interface HelpConfig {
153
153
  readonly width?: number;
154
154
  /** Emit OSC 8 hyperlinks in the header when supported. */
155
155
  readonly hyperlinks?: boolean;
156
+ /**
157
+ * Order of flags in the `Flags:` table.
158
+ *
159
+ * - `'alphabetical'` — short-aliased flags first, then alphabetical by name.
160
+ * - `'declaration'` — the order `.flag()` was called.
161
+ *
162
+ * Ignored when {@link HelpConfig.sortFlags} is set.
163
+ *
164
+ * @defaultValue `'alphabetical'`
165
+ */
166
+ readonly flagOrder?: 'alphabetical' | 'declaration';
167
+ /**
168
+ * Custom comparator over flag long names for the `Flags:` table. When set,
169
+ * it wins over {@link HelpConfig.flagOrder}.
170
+ *
171
+ * @defaultValue `undefined` (use `flagOrder`)
172
+ */
173
+ readonly sortFlags?: (a: string, b: string) => number;
156
174
  /**
157
175
  * Theme overrides for help output, merged over the built-in theme.
158
176
  *
@@ -562,12 +562,14 @@ var CLIBuilder = class CLIBuilder {
562
562
  };
563
563
  } else [out, captured] = createCaptureOutput(Object.keys(captureOptions).length > 0 ? captureOptions : void 0);
564
564
  clearRequestedExitCode(out);
565
+ const resolvedVersion = options?.help?.version ?? this.schema.version;
565
566
  const helpOptions = {
566
567
  ...this.schema.helpConfig,
567
568
  ...options?.help,
568
569
  binName: options?.help?.binName ?? this.schema.name,
569
570
  hyperlinks: options?.help?.hyperlinks ?? this.schema.helpConfig?.hyperlinks ?? out.isHyperlinkSupported,
570
- colors: options?.help?.colors ?? out.color
571
+ colors: options?.help?.colors ?? out.color,
572
+ ...resolvedVersion !== void 0 ? { version: resolvedVersion } : {}
571
573
  };
572
574
  const flagSettings = options?.flags ?? this.schema.flagSettings;
573
575
  const effectiveOptions = {
@@ -629,7 +631,10 @@ var CLIBuilder = class CLIBuilder {
629
631
  }, captured);
630
632
  }
631
633
  case "root-help":
632
- if (jsonMode) out.json(generateSchema(this.schema));
634
+ if (jsonMode) out.json(generateSchema(this.schema, void 0, {
635
+ name: planned.help.binName ?? this.schema.name,
636
+ version: planned.help.version ?? this.schema.version
637
+ }));
633
638
  else {
634
639
  const helpText = formatRootHelp(resolveHelpLinksSchema(this.schema), planned.help);
635
640
  out.log(helpText);
@@ -649,7 +654,10 @@ var CLIBuilder = class CLIBuilder {
649
654
  error: planned.error
650
655
  }, captured);
651
656
  case "needs-subcommand":
652
- if (jsonMode) out.json(generateCommandSchema(planned.command.schema));
657
+ if (jsonMode) out.json(generateCommandSchema(planned.command.schema, void 0, {
658
+ name: planned.help.binName ?? planned.command.schema.name,
659
+ version: planned.help.version
660
+ }));
653
661
  else {
654
662
  const helpText = formatHelp(planned.command.schema, planned.help);
655
663
  out.log(helpText);
@@ -19,7 +19,10 @@ async function executeCommand(request) {
19
19
  try {
20
20
  if (includesBeforeSeparator(argv, "--help") || includesBeforeSeparator(argv, "-h")) {
21
21
  if (out.jsonMode || options?.jsonMode === true) {
22
- out.json(generateCommandSchema(schema));
22
+ out.json(generateCommandSchema(schema, void 0, {
23
+ name: options?.help?.binName ?? schema.name,
24
+ version: options?.help?.version
25
+ }));
23
26
  return {
24
27
  exitCode: 0,
25
28
  error: void 0
@@ -10,6 +10,26 @@ interface HelpOptions {
10
10
  readonly width?: number;
11
11
  /** Binary/program name shown in the usage line. Defaults to command name. */
12
12
  readonly binName?: string;
13
+ /** Program version passed to function-form examples as `meta.version`. */
14
+ readonly version?: string;
15
+ /**
16
+ * Order of flags in the `Flags:` table.
17
+ *
18
+ * - `'alphabetical'` — short-aliased flags first, then alphabetical by name.
19
+ * - `'declaration'` — the order `.flag()` was called.
20
+ *
21
+ * Ignored when {@link HelpOptions.sortFlags} is set.
22
+ *
23
+ * @defaultValue `'alphabetical'`
24
+ */
25
+ readonly flagOrder?: 'alphabetical' | 'declaration';
26
+ /**
27
+ * Custom comparator over flag long names for the `Flags:` table. When set,
28
+ * it wins over {@link HelpOptions.flagOrder}.
29
+ *
30
+ * @defaultValue `undefined` (use `flagOrder`)
31
+ */
32
+ readonly sortFlags?: (a: string, b: string) => number;
13
33
  /**
14
34
  * Emit OSC 8 hyperlinks where link metadata is available (currently the
15
35
  * root-help header name/version configured via `CLIBuilder.links()`).
@@ -1,4 +1,5 @@
1
1
  import { getFlagAliasNames } from "../schema/flag.mjs";
2
+ import { resolveExampleCommand } from "../schema/command.mjs";
2
3
  import { formatDisplayValue } from "../output/display-value.mjs";
3
4
  import { osc8, padEnd, visibleWidth, wrapText } from "./ansi.mjs";
4
5
  import { resolveHelpTheme } from "./theme.mjs";
@@ -14,6 +15,9 @@ function resolveOptions(options) {
14
15
  return {
15
16
  width: options?.width ?? DEFAULT_WIDTH,
16
17
  binName: options?.binName,
18
+ version: options?.version,
19
+ flagOrder: options?.flagOrder ?? "alphabetical",
20
+ sortFlags: options?.sortFlags,
17
21
  isDefaultHelp: options?.isDefaultHelp ?? false,
18
22
  theme: resolveHelpTheme(options?.colors, options?.theme)
19
23
  };
@@ -96,32 +100,45 @@ function formatFlagDescription(schema, theme) {
96
100
  return parts.join(" ");
97
101
  }
98
102
  /**
99
- * Build the flag entries sorted: short-aliased first, then alphabetical.
103
+ * Default flag order: short-aliased flags first, then alphabetical by name.
104
+ */
105
+ function defaultFlagOrder(a, b, flags) {
106
+ const aSchema = flags[a];
107
+ const bSchema = flags[b];
108
+ if (aSchema === void 0 || bSchema === void 0) return 0;
109
+ const aHasShort = getFlagAliasNames(aSchema, { kind: "short" }).length > 0;
110
+ const bHasShort = getFlagAliasNames(bSchema, { kind: "short" }).length > 0;
111
+ if (aHasShort && !bHasShort) return -1;
112
+ if (!aHasShort && bHasShort) return 1;
113
+ return a.localeCompare(b);
114
+ }
115
+ /**
116
+ * Order flag names for the table: an explicit `sortFlags` comparator wins,
117
+ * then `'declaration'` preserves `.flag()` call order, otherwise the default
118
+ * short-first alphabetical order.
119
+ */
120
+ function orderFlagNames(names, flags, opts) {
121
+ if (opts.sortFlags !== void 0) return [...names].sort(opts.sortFlags);
122
+ if (opts.flagOrder === "declaration") return names;
123
+ return [...names].sort((a, b) => defaultFlagOrder(a, b, flags));
124
+ }
125
+ /**
126
+ * Build the flag entries in the configured order.
100
127
  *
101
128
  * @param flags - Map of flag names to {@link FlagSchema} definitions.
102
- * @param theme - Theme threaded into the per-flag formatters.
103
- * @returns Sorted array of {@link FlagEntry} objects for the flags table.
129
+ * @param opts - Resolved help options (theme + flag ordering).
130
+ * @returns Array of {@link FlagEntry} objects for the flags table.
104
131
  */
105
- function buildFlagEntries(flags, theme) {
132
+ function buildFlagEntries(flags, opts) {
106
133
  const names = Object.keys(flags);
107
134
  if (names.length === 0) return [];
108
- const sorted = [...names].sort((a, b) => {
109
- const aSchema = flags[a];
110
- const bSchema = flags[b];
111
- if (aSchema === void 0 || bSchema === void 0) return 0;
112
- const aHasShort = getFlagAliasNames(aSchema, { kind: "short" }).length > 0;
113
- const bHasShort = getFlagAliasNames(bSchema, { kind: "short" }).length > 0;
114
- if (aHasShort && !bHasShort) return -1;
115
- if (!aHasShort && bHasShort) return 1;
116
- return a.localeCompare(b);
117
- });
118
135
  const entries = [];
119
- for (const name of sorted) {
136
+ for (const name of orderFlagNames(names, flags, opts)) {
120
137
  const schema = flags[name];
121
138
  if (schema === void 0) continue;
122
139
  entries.push({
123
- left: formatFlagLeft(name, schema, theme),
124
- description: formatFlagDescription(schema, theme)
140
+ left: formatFlagLeft(name, schema, opts.theme),
141
+ description: formatFlagDescription(schema, opts.theme)
125
142
  });
126
143
  }
127
144
  return entries;
@@ -171,7 +188,13 @@ function formatHelpSections(schema, options) {
171
188
  if (visibleCommands.length > 0) sections.push(formatCommandsSection(visibleCommands, opts));
172
189
  if (schema.args.length > 0) sections.push(formatArgsSection(schema.args, opts));
173
190
  if (Object.keys(schema.flags).length > 0) sections.push(formatFlagsSection(schema.flags, opts));
174
- if (schema.examples.length > 0) sections.push(formatExamplesSection(schema.examples, opts.theme));
191
+ if (schema.examples.length > 0) {
192
+ const meta = {
193
+ name: opts.binName ?? schema.name,
194
+ version: opts.version
195
+ };
196
+ sections.push(formatExamplesSection(schema.examples, opts.theme, meta));
197
+ }
175
198
  return sections;
176
199
  }
177
200
  /**
@@ -259,7 +282,7 @@ function formatArgsSection(args, opts) {
259
282
  * @returns Multi-line flags section string.
260
283
  */
261
284
  function formatFlagsSection(flags, opts) {
262
- return formatFlagEntriesBlock(opts.theme.sectionTitle("Flags:"), buildFlagEntries(flags, opts.theme), opts.width);
285
+ return formatFlagEntriesBlock(opts.theme.sectionTitle("Flags:"), buildFlagEntries(flags, opts), opts.width);
263
286
  }
264
287
  /**
265
288
  * Render a titled two-column flag block from pre-built {@link FlagEntry} rows.
@@ -349,13 +372,14 @@ function highlightExampleCommand(command, theme) {
349
372
  * @param examples - Array of {@link CommandExample} entries.
350
373
  * @param theme - Theme applied to the section title, `$` prompt marker, and
351
374
  * per-token command highlighting.
375
+ * @param meta - Program name/version passed to function-form example commands.
352
376
  * @returns Multi-line examples section string.
353
377
  */
354
- function formatExamplesSection(examples, theme) {
378
+ function formatExamplesSection(examples, theme, meta) {
355
379
  const lines = [theme.sectionTitle("Examples:")];
356
380
  const prompt = theme.examplePrompt("$");
357
381
  for (const example of examples) {
358
- const command = highlightExampleCommand(example.command, theme);
382
+ const command = highlightExampleCommand(resolveExampleCommand(example.command, meta), theme);
359
383
  if (example.description !== void 0) {
360
384
  lines.push(` ${example.description}:`);
361
385
  lines.push(` ${prompt} ${command}`);
@@ -1,4 +1,4 @@
1
- import { CommandSchema } from "../schema/command.mjs";
1
+ import { CommandSchema, ExampleMeta } from "../schema/command.mjs";
2
2
  import "../schema/index.mjs";
3
3
  import { CLISchema } from "../cli/index.mjs";
4
4
  //#region src/core/json-schema/index.d.ts
@@ -43,6 +43,8 @@ interface JsonSchemaOptions {
43
43
  *
44
44
  * @param schema - The CLI schema from `CLIBuilder.schema`.
45
45
  * @param options - Generation options.
46
+ * @param meta - Program name/version for function-form examples; defaults to
47
+ * the CLI schema's own `name`/`version`.
46
48
  * @returns A plain object suitable for `JSON.stringify()`.
47
49
  *
48
50
  * @example
@@ -52,7 +54,7 @@ interface JsonSchemaOptions {
52
54
  * writeFileSync('cli-schema.json', JSON.stringify(definition, null, 2));
53
55
  * ```
54
56
  */
55
- declare function generateSchema(schema: CLISchema, options?: JsonSchemaOptions): Record<string, unknown>;
57
+ declare function generateSchema(schema: CLISchema, options?: JsonSchemaOptions, meta?: ExampleMeta): Record<string, unknown>;
56
58
  /**
57
59
  * Generate the definition metadata document for a single command.
58
60
  *
@@ -63,9 +65,11 @@ declare function generateSchema(schema: CLISchema, options?: JsonSchemaOptions):
63
65
  *
64
66
  * @param schema - The command schema to serialize.
65
67
  * @param options - Generation options.
68
+ * @param meta - Program name/version for function-form examples; defaults to
69
+ * the command's own name with no version.
66
70
  * @returns A plain object suitable for `JSON.stringify()`.
67
71
  */
68
- declare function generateCommandSchema(schema: CommandSchema, options?: JsonSchemaOptions): Record<string, unknown>;
72
+ declare function generateCommandSchema(schema: CommandSchema, options?: JsonSchemaOptions, meta?: ExampleMeta): Record<string, unknown>;
69
73
  /**
70
74
  * Generate a JSON Schema (draft 2020-12) for validating CLI input as JSON.
71
75
  *
@@ -1,4 +1,5 @@
1
1
  import { getFlagAliasNames } from "../schema/flag.mjs";
2
+ import { resolveExampleCommand } from "../schema/command.mjs";
2
3
  import { definitionMetaSchemaDescriptions } from "./meta-descriptions.generated.mjs";
3
4
  //#region src/core/json-schema/index.ts
4
5
  /**
@@ -36,6 +37,8 @@ function isRecord(value) {
36
37
  *
37
38
  * @param schema - The CLI schema from `CLIBuilder.schema`.
38
39
  * @param options - Generation options.
40
+ * @param meta - Program name/version for function-form examples; defaults to
41
+ * the CLI schema's own `name`/`version`.
39
42
  * @returns A plain object suitable for `JSON.stringify()`.
40
43
  *
41
44
  * @example
@@ -45,16 +48,20 @@ function isRecord(value) {
45
48
  * writeFileSync('cli-schema.json', JSON.stringify(definition, null, 2));
46
49
  * ```
47
50
  */
48
- function generateSchema(schema, options) {
51
+ function generateSchema(schema, options, meta) {
49
52
  const opts = resolveOptions(options);
53
+ const resolvedMeta = meta ?? {
54
+ name: schema.name,
55
+ version: schema.version
56
+ };
50
57
  const result = {
51
58
  $schema: DEFINITION_SCHEMA_URL,
52
59
  name: schema.name
53
60
  };
54
61
  if (schema.version !== void 0) result.version = schema.version;
55
62
  if (schema.description !== void 0) result.description = schema.description;
56
- if (schema.defaultCommand !== void 0 && (opts.includeHidden || !schema.defaultCommand.schema.hidden)) result.defaultCommand = serializeCommand(schema.defaultCommand.schema, opts);
57
- result.commands = schema.commands.filter((cmd) => opts.includeHidden || !cmd.schema.hidden).map((cmd) => serializeCommand(cmd.schema, opts));
63
+ if (schema.defaultCommand !== void 0 && (opts.includeHidden || !schema.defaultCommand.schema.hidden)) result.defaultCommand = serializeCommand(schema.defaultCommand.schema, opts, resolvedMeta);
64
+ result.commands = schema.commands.filter((cmd) => opts.includeHidden || !cmd.schema.hidden).map((cmd) => serializeCommand(cmd.schema, opts, resolvedMeta));
58
65
  return result;
59
66
  }
60
67
  /**
@@ -67,10 +74,16 @@ function generateSchema(schema, options) {
67
74
  *
68
75
  * @param schema - The command schema to serialize.
69
76
  * @param options - Generation options.
77
+ * @param meta - Program name/version for function-form examples; defaults to
78
+ * the command's own name with no version.
70
79
  * @returns A plain object suitable for `JSON.stringify()`.
71
80
  */
72
- function generateCommandSchema(schema, options) {
73
- return serializeCommand(schema, resolveOptions(options));
81
+ function generateCommandSchema(schema, options, meta) {
82
+ const resolvedMeta = meta ?? {
83
+ name: schema.name,
84
+ version: void 0
85
+ };
86
+ return serializeCommand(schema, resolveOptions(options), resolvedMeta);
74
87
  }
75
88
  /**
76
89
  * Serialize a single {@link CommandSchema} into a plain object.
@@ -79,17 +92,17 @@ function generateCommandSchema(schema, options) {
79
92
  * @param opts - Resolved generation options (hidden/prompt inclusion).
80
93
  * @returns JSON-serializable object representing the command.
81
94
  */
82
- function serializeCommand(schema, opts) {
95
+ function serializeCommand(schema, opts, meta) {
83
96
  const result = { name: schema.name };
84
97
  if (schema.description !== void 0) result.description = schema.description;
85
98
  if (schema.aliases.length > 0) result.aliases = [...schema.aliases];
86
99
  if (schema.hidden) result.hidden = true;
87
- if (schema.examples.length > 0) result.examples = schema.examples.map(serializeExample);
100
+ if (schema.examples.length > 0) result.examples = schema.examples.map((example) => serializeExample(example, meta));
88
101
  const flags = {};
89
102
  for (const [name, flagDef] of Object.entries(schema.flags)) flags[name] = serializeFlag(flagDef, opts);
90
103
  result.flags = flags;
91
104
  result.args = schema.args.map(serializeArgEntry);
92
- result.commands = schema.commands.filter((cmd) => opts.includeHidden || !cmd.hidden).map((cmd) => serializeCommand(cmd, opts));
105
+ result.commands = schema.commands.filter((cmd) => opts.includeHidden || !cmd.hidden).map((cmd) => serializeCommand(cmd, opts, meta));
93
106
  return result;
94
107
  }
95
108
  /**
@@ -203,11 +216,15 @@ function serializeChoice(choice) {
203
216
  /**
204
217
  * Serialize a {@link CommandExample} into a plain object.
205
218
  *
219
+ * Function-form commands are resolved against `meta` so the output is a plain
220
+ * serializable string rather than a dropped function.
221
+ *
206
222
  * @param example - The example to serialize.
223
+ * @param meta - Program name/version passed to function-form commands.
207
224
  * @returns JSON-serializable object with command and optional description.
208
225
  */
209
- function serializeExample(example) {
210
- const result = { command: example.command };
226
+ function serializeExample(example, meta) {
227
+ const result = { command: resolveExampleCommand(example.command, meta) };
211
228
  if (example.description !== void 0) result.description = example.description;
212
229
  return result;
213
230
  }
@@ -371,13 +371,33 @@ type ExecutionStep = {
371
371
  readonly kind: 'middleware';
372
372
  readonly handler: ErasedMiddlewareHandler;
373
373
  };
374
+ /**
375
+ * Program metadata passed to a function-form example, resolved at render time.
376
+ *
377
+ * `name` is the actually-invoked program name (`options.help.binName`, falling
378
+ * back to the command name) so examples stay truthful under symlinks,
379
+ * `inheritName`, and `npx x` vs a global install. `version` is the program
380
+ * version, or `undefined` when none is configured.
381
+ */
382
+ interface ExampleMeta {
383
+ readonly name: string;
384
+ readonly version: string | undefined;
385
+ }
386
+ /**
387
+ * An example command line: a literal string, or a function resolved at render
388
+ * time with the program {@link ExampleMeta} (so the program name need not be
389
+ * hardcoded).
390
+ */
391
+ type ExampleCommand = string | ((meta: ExampleMeta) => string);
374
392
  /** A single usage example shown in help text. */
375
393
  interface CommandExample {
376
394
  /** The command invocation (e.g. `'deploy production --force'`). */
377
- readonly command: string;
395
+ readonly command: ExampleCommand;
378
396
  /** Optional description of what this example does. */
379
397
  readonly description?: string;
380
398
  }
399
+ /** Resolve an {@link ExampleCommand} to its string form for the given meta. */
400
+ declare function resolveExampleCommand(command: ExampleCommand, meta: ExampleMeta): string;
381
401
  /**
382
402
  * Runtime descriptor produced by {@link CommandBuilder}.
383
403
  *
@@ -773,7 +793,13 @@ declare class CommandBuilder<F extends Record<string, FlagBuilder<FlagConfig>> =
773
793
  * Call multiple times to add several examples. Each example shows a
774
794
  * shell invocation, optionally with a description.
775
795
  *
776
- * @param cmd - The example command line (without the program name prefix).
796
+ * `cmd` may be a literal string or a function receiving the program
797
+ * {@link ExampleMeta} (`name`, `version`), resolved at render time. Use the
798
+ * function form to reference the invoked program name instead of hardcoding
799
+ * it, so examples stay truthful under symlinks, `inheritName`, and
800
+ * `npx x` vs a global install.
801
+ *
802
+ * @param cmd - The example command line, or a `(meta) => string` builder.
777
803
  * @param description - Optional one-line explanation of what the example does.
778
804
  *
779
805
  * @example
@@ -782,19 +808,19 @@ declare class CommandBuilder<F extends Record<string, FlagBuilder<FlagConfig>> =
782
808
  * .arg('target', arg.string())
783
809
  * .flag('force', flag.boolean().alias('f'))
784
810
  * .example('deploy production', 'Deploy to production')
785
- * .example('deploy staging -f', 'Force deploy to staging')
811
+ * .example((m) => `${m.name} deploy staging -f`, 'Force deploy to staging')
786
812
  * .action(({ args, flags }) => { ... });
787
813
  *
788
814
  * // $ mycli deploy --help
789
815
  * // ...
790
816
  * // Examples:
791
- * // deploy production Deploy to production
792
- * // deploy staging -f Force deploy to staging
817
+ * // deploy production Deploy to production
818
+ * // mycli deploy staging -f Force deploy to staging
793
819
  * ```
794
820
  *
795
821
  * @returns The builder (for chaining).
796
822
  */
797
- example(cmd: string, description?: string): CommandBuilder<F, A, C>;
823
+ example(cmd: ExampleCommand, description?: string): CommandBuilder<F, A, C>;
798
824
  /**
799
825
  * Register a named flag on this command.
800
826
  *
@@ -996,4 +1022,4 @@ declare function command(name: string): CommandBuilder;
996
1022
  */
997
1023
  declare function group(name: string): CommandBuilder;
998
1024
  //#endregion
999
- export { type ActionHandler, type ActionParams, type AnyCommandBuilder, type CommandArgEntry, CommandBuilder, type CommandConfig, type CommandExample, type CommandMeta, type CommandSchema, type DeriveHandler, type DeriveParams, type ErasedActionHandler, type ErasedCommand, type ErasedDeriveHandler, type ErasedInteractiveResolver, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type Out, type RunnableCommand, type WidenContext, type WidenDerivedContext, command, group };
1025
+ export { type ActionHandler, type ActionParams, type AnyCommandBuilder, type CommandArgEntry, CommandBuilder, type CommandConfig, type CommandExample, type CommandMeta, type CommandSchema, type DeriveHandler, type DeriveParams, type ErasedActionHandler, type ErasedCommand, type ErasedDeriveHandler, type ErasedInteractiveResolver, type ExampleCommand, type ExampleMeta, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type Out, type RunnableCommand, type WidenContext, type WidenDerivedContext, command, group, resolveExampleCommand };
@@ -1,6 +1,10 @@
1
1
  import { CLIError } from "../errors/index.mjs";
2
2
  import { getFlagNegatedName } from "./flag.mjs";
3
3
  //#region src/core/schema/command.ts
4
+ /** Resolve an {@link ExampleCommand} to its string form for the given meta. */
5
+ function resolveExampleCommand(command, meta) {
6
+ return typeof command === "function" ? command(meta) : command;
7
+ }
4
8
  /**
5
9
  * Validate a new arg entry against invariants before adding it to the command.
6
10
  *
@@ -430,7 +434,13 @@ var CommandBuilder = class CommandBuilder {
430
434
  * Call multiple times to add several examples. Each example shows a
431
435
  * shell invocation, optionally with a description.
432
436
  *
433
- * @param cmd - The example command line (without the program name prefix).
437
+ * `cmd` may be a literal string or a function receiving the program
438
+ * {@link ExampleMeta} (`name`, `version`), resolved at render time. Use the
439
+ * function form to reference the invoked program name instead of hardcoding
440
+ * it, so examples stay truthful under symlinks, `inheritName`, and
441
+ * `npx x` vs a global install.
442
+ *
443
+ * @param cmd - The example command line, or a `(meta) => string` builder.
434
444
  * @param description - Optional one-line explanation of what the example does.
435
445
  *
436
446
  * @example
@@ -439,14 +449,14 @@ var CommandBuilder = class CommandBuilder {
439
449
  * .arg('target', arg.string())
440
450
  * .flag('force', flag.boolean().alias('f'))
441
451
  * .example('deploy production', 'Deploy to production')
442
- * .example('deploy staging -f', 'Force deploy to staging')
452
+ * .example((m) => `${m.name} deploy staging -f`, 'Force deploy to staging')
443
453
  * .action(({ args, flags }) => { ... });
444
454
  *
445
455
  * // $ mycli deploy --help
446
456
  * // ...
447
457
  * // Examples:
448
- * // deploy production Deploy to production
449
- * // deploy staging -f Force deploy to staging
458
+ * // deploy production Deploy to production
459
+ * // mycli deploy staging -f Force deploy to staging
450
460
  * ```
451
461
  *
452
462
  * @returns The builder (for chaining).
@@ -723,4 +733,4 @@ function group(name) {
723
733
  return command(name);
724
734
  }
725
735
  //#endregion
726
- export { CommandBuilder, command, group };
736
+ export { CommandBuilder, command, group, resolveExampleCommand };
@@ -8,5 +8,5 @@ import { DateFlagOptions, UrlFlagOptions } from "./value-parsers.mjs";
8
8
  import { DuplicatePolicy, FLAG_KINDS, FLAG_PRESENCES, FlagAlias, FlagBuilder, FlagConfig, FlagFactory, FlagKind, FlagNegation, FlagParseFn, FlagPresence, FlagSchema, FlagSchemaOverrides, InferFlag, InferFlags, PathChecks, PathFlagOptions, ResolvedValue, WithPresence, createSchema, flag, getFlagNegatedName } from "./flag.mjs";
9
9
  import { ErasedMiddlewareHandler, Middleware, MiddlewareHandler, MiddlewareParams, middleware } from "./middleware.mjs";
10
10
  import { RunOptions, RunResult } from "./run.mjs";
11
- import { ActionHandler, ActionParams, AnyCommandBuilder, CommandArgEntry, CommandBuilder, CommandConfig, CommandExample, CommandMeta, CommandSchema, DeriveHandler, DeriveParams, ErasedCommand, ErasedDeriveHandler, ErasedInteractiveResolver, InteractiveParams, InteractiveResolver, InteractiveResult, Out, command, group } from "./command.mjs";
12
- export { ARG_KINDS, ARG_PRESENCES, type ActionHandler, type ActionParams, type ActivityEvent, type AnyCommandBuilder, ArgBuilder, type ArgConfig, type ArgFactory, type ArgKind, type ArgParseFn, type ArgPresence, type ArgSchema, type CommandArgEntry, CommandBuilder, type CommandConfig, type CommandExample, type CommandMeta, type CommandSchema, type ConfirmPromptConfig, type DateFlagOptions, type DeriveHandler, type DeriveParams, type DuplicatePolicy, type ErasedCommand, type ErasedDeriveHandler, type ErasedInteractiveResolver, type ErasedMiddlewareHandler, FLAG_KINDS, FLAG_PRESENCES, type Fallback, type FlagAlias, FlagBuilder, type FlagConfig, type FlagFactory, type FlagKind, type FlagNegation, type FlagParseFn, type FlagPresence, type FlagSchema, type FlagSchemaOverrides, type InferArg, type InferArgs, type InferFlag, type InferFlags, type InferStandardInput, type InferStandardOutput, type InputPromptConfig, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type Middleware, type MiddlewareHandler, type MiddlewareParams, type MultiselectPromptConfig, type NumberConstraintViolation, type NumberConstraints, type Out, PROMPT_KINDS, type PathChecks, type PathFlagOptions, type ProgressHandle, type ProgressOptions, type PromptConfig, type PromptConfigBase, type PromptKind, type PromptResult, type ResolvedArgValue, type ResolvedValue, type RunOptions, type RunResult, type SelectChoice, type SelectPromptConfig, type SpinnerHandle, type SpinnerOptions, type StandardSchemaV1, type StandardSchemaV1FailureResult, type StandardSchemaV1Issue, type StandardSchemaV1Options, type StandardSchemaV1PathSegment, type StandardSchemaV1Props, type StandardSchemaV1Result, type StandardSchemaV1SuccessResult, type StandardSchemaV1Types, type StringConstraintViolation, type StringConstraints, type TableColumn, type TableFormat, type TableOptions, type TableStream, type UrlFlagOptions, type WithArgPresence, type WithPresence, type WithVariadic, arg, command, createArgSchema, createSchema, describeNumberConstraintViolation, describeStringConstraintViolation, flag, getFlagNegatedName, group, middleware, validateNumberConstraints, validateStringConstraints };
11
+ import { ActionHandler, ActionParams, AnyCommandBuilder, CommandArgEntry, CommandBuilder, CommandConfig, CommandExample, CommandMeta, CommandSchema, DeriveHandler, DeriveParams, ErasedCommand, ErasedDeriveHandler, ErasedInteractiveResolver, ExampleCommand, ExampleMeta, InteractiveParams, InteractiveResolver, InteractiveResult, Out, command, group, resolveExampleCommand } from "./command.mjs";
12
+ export { ARG_KINDS, ARG_PRESENCES, type ActionHandler, type ActionParams, type ActivityEvent, type AnyCommandBuilder, ArgBuilder, type ArgConfig, type ArgFactory, type ArgKind, type ArgParseFn, type ArgPresence, type ArgSchema, type CommandArgEntry, CommandBuilder, type CommandConfig, type CommandExample, type CommandMeta, type CommandSchema, type ConfirmPromptConfig, type DateFlagOptions, type DeriveHandler, type DeriveParams, type DuplicatePolicy, type ErasedCommand, type ErasedDeriveHandler, type ErasedInteractiveResolver, type ErasedMiddlewareHandler, type ExampleCommand, type ExampleMeta, FLAG_KINDS, FLAG_PRESENCES, type Fallback, type FlagAlias, FlagBuilder, type FlagConfig, type FlagFactory, type FlagKind, type FlagNegation, type FlagParseFn, type FlagPresence, type FlagSchema, type FlagSchemaOverrides, type InferArg, type InferArgs, type InferFlag, type InferFlags, type InferStandardInput, type InferStandardOutput, type InputPromptConfig, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type Middleware, type MiddlewareHandler, type MiddlewareParams, type MultiselectPromptConfig, type NumberConstraintViolation, type NumberConstraints, type Out, PROMPT_KINDS, type PathChecks, type PathFlagOptions, type ProgressHandle, type ProgressOptions, type PromptConfig, type PromptConfigBase, type PromptKind, type PromptResult, type ResolvedArgValue, type ResolvedValue, type RunOptions, type RunResult, type SelectChoice, type SelectPromptConfig, type SpinnerHandle, type SpinnerOptions, type StandardSchemaV1, type StandardSchemaV1FailureResult, type StandardSchemaV1Issue, type StandardSchemaV1Options, type StandardSchemaV1PathSegment, type StandardSchemaV1Props, type StandardSchemaV1Result, type StandardSchemaV1SuccessResult, type StandardSchemaV1Types, type StringConstraintViolation, type StringConstraints, type TableColumn, type TableFormat, type TableOptions, type TableStream, type UrlFlagOptions, type WithArgPresence, type WithPresence, type WithVariadic, arg, command, createArgSchema, createSchema, describeNumberConstraintViolation, describeStringConstraintViolation, flag, getFlagNegatedName, group, middleware, resolveExampleCommand, validateNumberConstraints, validateStringConstraints };
package/dist/index.d.mts CHANGED
@@ -19,7 +19,7 @@ import { HelpTheme, HelpThemeFactory } from "./core/help/theme.mjs";
19
19
  import { osc8, visibleWidth } from "./core/help/ansi.mjs";
20
20
  import { HelpOptions, formatHelp } from "./core/help/index.mjs";
21
21
  import { RunResult } from "./core/schema/run.mjs";
22
- import { ActionHandler, ActionParams, AnyCommandBuilder, CommandArgEntry, CommandBuilder, CommandConfig, CommandExample, CommandMeta, CommandSchema, DeriveHandler, DeriveParams, InteractiveParams, InteractiveResolver, InteractiveResult, Out, command, group } from "./core/schema/command.mjs";
22
+ import { ActionHandler, ActionParams, AnyCommandBuilder, CommandArgEntry, CommandBuilder, CommandConfig, CommandExample, CommandMeta, CommandSchema, DeriveHandler, DeriveParams, ExampleCommand, ExampleMeta, InteractiveParams, InteractiveResolver, InteractiveResult, Out, command, group, resolveExampleCommand } from "./core/schema/command.mjs";
23
23
  import "./core/schema/index.mjs";
24
24
  import { ParseOptions, ParseResult, Token, parse, tokenize } from "./core/parse/index.mjs";
25
25
  import { ManifestDiscoveryOptions, PackageJsonAdapter, PackageJsonData, PackageRepository, PackageRepositoryUrlOptions, discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl } from "./core/config/package-json.mjs";
@@ -34,4 +34,4 @@ import { ConfigAdapter, ConfigDiscoveryOptions, ConfigDiscoveryResult, ConfigFou
34
34
  import { CLIBuilder, CLIOptions, CLIRunOptions, CLISchema, ConfigSettings, DefaultCommandOptions, InferNameOption, ManifestPresetSettings, ManifestSettings, PackageJsonSettings, ResolvedManifestSettings, cli, isMainModule } from "./core/cli/index.mjs";
35
35
  import { JsonSchemaOptions, definitionMetaSchema, generateCommandSchema, generateInputSchema, generateSchema } from "./core/json-schema/index.mjs";
36
36
  import { Colors } from "ansispeck";
37
- export { type ActionHandler, type ActionParams, type ActivityEvent, type AnyCommandBuilder, ArgBuilder, type ArgConfig, type ArgFactory, type ArgKind, type ArgParseFn, type ArgPresence, type ArgSchema, type BeforeParseParams, CLIBuilder, CLIError, type CLIErrorJSON, type CLIErrorOptions, type CLIOptions, type CLIPlugin, type CLIPluginHooks, type CLIRunOptions, type CLISchema, type Colors, type CommandArgEntry, CommandBuilder, type CommandConfig, type CommandExample, type CommandMeta, type CommandSchema, type CompletionOptions, type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type ConfigSettings, type ConfirmPromptConfig, type DateFlagOptions, type DefaultCommandOptions, type DeprecationWarning, type DeriveHandler, type DeriveParams, type DuplicatePolicy, type ErrorCode, type Fallback, FlagBuilder, type FlagConfig, type FlagFactory, type FlagKind, type FlagNegation, type FlagParseFn, type FlagPresence, type FlagSchema, type FormatLoader, type HelpLinks, type HelpOptions, type HelpTheme, type HelpThemeFactory, type InferArg, type InferArgs, type InferFlag, type InferFlags, type InferNameOption, type InferStandardInput, type InferStandardOutput, type InputPromptConfig, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type JsonSchemaOptions, type ManifestDiscoveryOptions, type ManifestPresetSettings, type ManifestSettings, type Middleware, type MiddlewareHandler, type MiddlewareParams, type MultiselectPromptConfig, type NumberConstraintViolation, type NumberConstraints, type Out, type OutputOptions, type PackageJsonAdapter, type PackageJsonData, type PackageJsonSettings, type PackageRepository, type PackageRepositoryUrlOptions, ParseError, type ParseErrorCode, type ParseErrorOptions, type ParseOptions, type ParseResult, type PathChecks, type PathFlagOptions, type PluginCommandContext, type ProgressHandle, type ProgressOptions, type PromptConfig, type PromptConfigBase, type PromptEngine, type PromptKind, type PromptResult, type ReadFn, type ResolveOptions, type ResolveResult, type ResolvedArgValue, type ResolvedCommandParams, type ResolvedManifestSettings, type ResolvedMultiselectPromptConfig, type ResolvedPromptConfig, type ResolvedSelectPromptConfig, type ResolvedValue, type RunResult, SHELLS, type SelectChoice, type SelectPromptConfig, type Shell, type SpinnerHandle, type SpinnerOptions, type StandardSchemaV1, type StandardSchemaV1FailureResult, type StandardSchemaV1Issue, type StandardSchemaV1Options, type StandardSchemaV1PathSegment, type StandardSchemaV1Props, type StandardSchemaV1Result, type StandardSchemaV1SuccessResult, type StandardSchemaV1Types, type StringConstraintViolation, type StringConstraints, type TableColumn, type TableFormat, type TableOptions, type TableStream, type Token, type UrlFlagOptions, ValidationError, type ValidationErrorCode, type ValidationErrorOptions, type Verbosity, type WithArgPresence, type WithPresence, type WithVariadic, type WriteFn, arg, buildConfigSearchPaths, cli, command, configFormat, createArgSchema, createOutput, createSchema, createTerminalPrompter, definitionMetaSchema, discoverConfig, discoverManifest, discoverPackageJson, flag, formatHelp, generateBashCompletion, generateCommandSchema, generateCompletion, generateFishCompletion, generateInputSchema, generatePowerShellCompletion, generateSchema, generateZshCompletion, getFlagNegatedName, group, inferCliName, isCLIError, isMainModule, isParseError, isValidationError, middleware, osc8, packageRepositoryUrl, parse, plugin, resolve, resolvePromptConfig, tokenize, visibleWidth };
37
+ export { type ActionHandler, type ActionParams, type ActivityEvent, type AnyCommandBuilder, ArgBuilder, type ArgConfig, type ArgFactory, type ArgKind, type ArgParseFn, type ArgPresence, type ArgSchema, type BeforeParseParams, CLIBuilder, CLIError, type CLIErrorJSON, type CLIErrorOptions, type CLIOptions, type CLIPlugin, type CLIPluginHooks, type CLIRunOptions, type CLISchema, type Colors, type CommandArgEntry, CommandBuilder, type CommandConfig, type CommandExample, type CommandMeta, type CommandSchema, type CompletionOptions, type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type ConfigSettings, type ConfirmPromptConfig, type DateFlagOptions, type DefaultCommandOptions, type DeprecationWarning, type DeriveHandler, type DeriveParams, type DuplicatePolicy, type ErrorCode, type ExampleCommand, type ExampleMeta, type Fallback, FlagBuilder, type FlagConfig, type FlagFactory, type FlagKind, type FlagNegation, type FlagParseFn, type FlagPresence, type FlagSchema, type FormatLoader, type HelpLinks, type HelpOptions, type HelpTheme, type HelpThemeFactory, type InferArg, type InferArgs, type InferFlag, type InferFlags, type InferNameOption, type InferStandardInput, type InferStandardOutput, type InputPromptConfig, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type JsonSchemaOptions, type ManifestDiscoveryOptions, type ManifestPresetSettings, type ManifestSettings, type Middleware, type MiddlewareHandler, type MiddlewareParams, type MultiselectPromptConfig, type NumberConstraintViolation, type NumberConstraints, type Out, type OutputOptions, type PackageJsonAdapter, type PackageJsonData, type PackageJsonSettings, type PackageRepository, type PackageRepositoryUrlOptions, ParseError, type ParseErrorCode, type ParseErrorOptions, type ParseOptions, type ParseResult, type PathChecks, type PathFlagOptions, type PluginCommandContext, type ProgressHandle, type ProgressOptions, type PromptConfig, type PromptConfigBase, type PromptEngine, type PromptKind, type PromptResult, type ReadFn, type ResolveOptions, type ResolveResult, type ResolvedArgValue, type ResolvedCommandParams, type ResolvedManifestSettings, type ResolvedMultiselectPromptConfig, type ResolvedPromptConfig, type ResolvedSelectPromptConfig, type ResolvedValue, type RunResult, SHELLS, type SelectChoice, type SelectPromptConfig, type Shell, type SpinnerHandle, type SpinnerOptions, type StandardSchemaV1, type StandardSchemaV1FailureResult, type StandardSchemaV1Issue, type StandardSchemaV1Options, type StandardSchemaV1PathSegment, type StandardSchemaV1Props, type StandardSchemaV1Result, type StandardSchemaV1SuccessResult, type StandardSchemaV1Types, type StringConstraintViolation, type StringConstraints, type TableColumn, type TableFormat, type TableOptions, type TableStream, type Token, type UrlFlagOptions, ValidationError, type ValidationErrorCode, type ValidationErrorOptions, type Verbosity, type WithArgPresence, type WithPresence, type WithVariadic, type WriteFn, arg, buildConfigSearchPaths, cli, command, configFormat, createArgSchema, createOutput, createSchema, createTerminalPrompter, definitionMetaSchema, discoverConfig, discoverManifest, discoverPackageJson, flag, formatHelp, generateBashCompletion, generateCommandSchema, generateCompletion, generateFishCompletion, generateInputSchema, generatePowerShellCompletion, generateSchema, generateZshCompletion, getFlagNegatedName, group, inferCliName, isCLIError, isMainModule, isParseError, isValidationError, middleware, osc8, packageRepositoryUrl, parse, plugin, resolve, resolveExampleCommand, resolvePromptConfig, tokenize, visibleWidth };
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { CLIError, ParseError, ValidationError, isCLIError, isParseError, isValidationError } from "./core/errors/index.mjs";
2
2
  import { FlagBuilder, createSchema, flag, getFlagNegatedName } from "./core/schema/flag.mjs";
3
3
  import { ArgBuilder, arg, createArgSchema } from "./core/schema/arg.mjs";
4
- import { CommandBuilder, command, group } from "./core/schema/command.mjs";
4
+ import { CommandBuilder, command, group, resolveExampleCommand } from "./core/schema/command.mjs";
5
5
  import { middleware } from "./core/schema/middleware.mjs";
6
6
  import { parse, tokenize } from "./core/parse/index.mjs";
7
7
  import { generateBashCompletion } from "./core/completion/shells/bash.mjs";
@@ -19,4 +19,4 @@ import { discoverManifest, discoverPackageJson, inferCliName, packageRepositoryU
19
19
  import { plugin } from "./core/cli/plugin.mjs";
20
20
  import { buildConfigSearchPaths, configFormat, discoverConfig } from "./core/config/index.mjs";
21
21
  import { CLIBuilder, cli, isMainModule } from "./core/cli/index.mjs";
22
- export { ArgBuilder, CLIBuilder, CLIError, CommandBuilder, FlagBuilder, ParseError, SHELLS, ValidationError, arg, buildConfigSearchPaths, cli, command, configFormat, createArgSchema, createOutput, createSchema, createTerminalPrompter, definitionMetaSchema, discoverConfig, discoverManifest, discoverPackageJson, flag, formatHelp, generateBashCompletion, generateCommandSchema, generateCompletion, generateFishCompletion, generateInputSchema, generatePowerShellCompletion, generateSchema, generateZshCompletion, getFlagNegatedName, group, inferCliName, isCLIError, isMainModule, isParseError, isValidationError, middleware, osc8, packageRepositoryUrl, parse, plugin, resolve, resolvePromptConfig, tokenize, visibleWidth };
22
+ export { ArgBuilder, CLIBuilder, CLIError, CommandBuilder, FlagBuilder, ParseError, SHELLS, ValidationError, arg, buildConfigSearchPaths, cli, command, configFormat, createArgSchema, createOutput, createSchema, createTerminalPrompter, definitionMetaSchema, discoverConfig, discoverManifest, discoverPackageJson, flag, formatHelp, generateBashCompletion, generateCommandSchema, generateCompletion, generateFishCompletion, generateInputSchema, generatePowerShellCompletion, generateSchema, generateZshCompletion, getFlagNegatedName, group, inferCliName, isCLIError, isMainModule, isParseError, isValidationError, middleware, osc8, packageRepositoryUrl, parse, plugin, resolve, resolveExampleCommand, resolvePromptConfig, tokenize, visibleWidth };
package/dist/version.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  //#region src/version.ts
2
2
  /** Package version (e.g. `"0.9.1"`). `"dev"` when running unbundled. */
3
- const DREAMCLI_VERSION = "3.0.0-rc.13";
3
+ const DREAMCLI_VERSION = "3.0.0-rc.15";
4
4
  /** Git short SHA (e.g. `"f9b5f1a"`). `"dev"` when running unbundled. */
5
- const DREAMCLI_REVISION = "a6777ca";
5
+ const DREAMCLI_REVISION = "403c982";
6
6
  //#endregion
7
7
  export { DREAMCLI_REVISION, DREAMCLI_VERSION };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kjanat/dreamcli",
3
- "version": "3.0.0-rc.13",
3
+ "version": "3.0.0-rc.15",
4
4
  "description": "Schema-first, fully typed TypeScript CLI framework",
5
5
  "keywords": [
6
6
  "dreamcli",