@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.11

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 (194) hide show
  1. package/CHANGELOG.md +227 -1
  2. package/dist/core/cli/dispatch.d.mts +6 -5
  3. package/dist/core/cli/dispatch.mjs +205 -1
  4. package/dist/core/cli/help-links.d.mts +0 -1
  5. package/dist/core/cli/help-links.mjs +41 -1
  6. package/dist/core/cli/index.d.mts +81 -8
  7. package/dist/core/cli/index.mjs +945 -1
  8. package/dist/core/cli/planner.d.mts +5 -1
  9. package/dist/core/cli/planner.mjs +300 -1
  10. package/dist/core/cli/plugin.d.mts +1 -1
  11. package/dist/core/cli/plugin.mjs +41 -1
  12. package/dist/core/cli/propagate.d.mts +1 -1
  13. package/dist/core/cli/propagate.mjs +57 -1
  14. package/dist/core/cli/root-help.d.mts +2 -1
  15. package/dist/core/cli/root-help.mjs +226 -4
  16. package/dist/core/cli/root-surface.d.mts +12 -1
  17. package/dist/core/cli/root-surface.mjs +28 -1
  18. package/dist/core/cli/runtime-preflight.d.mts +14 -2
  19. package/dist/core/cli/runtime-preflight.mjs +169 -1
  20. package/dist/core/completion/index.d.mts +0 -1
  21. package/dist/core/completion/index.mjs +90 -1
  22. package/dist/core/completion/shells/bash.d.mts +0 -1
  23. package/dist/core/completion/shells/bash.mjs +308 -3
  24. package/dist/core/completion/shells/fish.d.mts +0 -1
  25. package/dist/core/completion/shells/fish.mjs +162 -2
  26. package/dist/core/completion/shells/powershell.d.mts +0 -1
  27. package/dist/core/completion/shells/powershell.mjs +358 -2
  28. package/dist/core/completion/shells/shared.d.mts +13 -2
  29. package/dist/core/completion/shells/shared.mjs +176 -1
  30. package/dist/core/completion/shells/zsh.d.mts +0 -1
  31. package/dist/core/completion/shells/zsh.mjs +251 -2
  32. package/dist/core/config/index.d.mts +2 -3
  33. package/dist/core/config/index.mjs +246 -1
  34. package/dist/core/config/package-json.d.mts +27 -4
  35. package/dist/core/config/package-json.mjs +386 -3
  36. package/dist/core/errors/index.d.mts +3 -3
  37. package/dist/core/errors/index.mjs +87 -1
  38. package/dist/core/execution/index.d.mts +0 -1
  39. package/dist/core/execution/index.mjs +201 -1
  40. package/dist/core/help/ansi.d.mts +11 -5
  41. package/dist/core/help/ansi.mjs +121 -2
  42. package/dist/core/help/index.d.mts +22 -3
  43. package/dist/core/help/index.mjs +341 -7
  44. package/dist/core/help/theme.d.mts +68 -0
  45. package/dist/core/help/theme.mjs +46 -0
  46. package/dist/core/json-schema/index.d.mts +15 -2
  47. package/dist/core/json-schema/index.mjs +536 -12
  48. package/dist/core/json-schema/meta-descriptions.generated.d.mts +55 -38
  49. package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
  50. package/dist/core/output/activity.d.mts +0 -1
  51. package/dist/core/output/activity.mjs +452 -1
  52. package/dist/core/output/bind.mjs +56 -1
  53. package/dist/core/output/contracts.d.mts +4 -5
  54. package/dist/core/output/contracts.mjs +57 -1
  55. package/dist/core/output/display-value.mjs +32 -1
  56. package/dist/core/output/index.d.mts +21 -1
  57. package/dist/core/output/index.mjs +442 -2
  58. package/dist/core/output/renderers.d.mts +0 -1
  59. package/dist/core/output/renderers.mjs +46 -1
  60. package/dist/core/output/writer.mjs +12 -1
  61. package/dist/core/parse/index.d.mts +40 -7
  62. package/dist/core/parse/index.mjs +727 -1
  63. package/dist/core/prompt/index.d.mts +1 -1
  64. package/dist/core/prompt/index.mjs +348 -6
  65. package/dist/core/resolve/args.d.mts +1 -1
  66. package/dist/core/resolve/args.mjs +105 -1
  67. package/dist/core/resolve/coerce.d.mts +1 -1
  68. package/dist/core/resolve/coerce.mjs +336 -1
  69. package/dist/core/resolve/config.mjs +19 -1
  70. package/dist/core/resolve/contracts.d.mts +9 -4
  71. package/dist/core/resolve/errors.d.mts +0 -1
  72. package/dist/core/resolve/errors.mjs +140 -2
  73. package/dist/core/resolve/flags.d.mts +7 -2
  74. package/dist/core/resolve/flags.mjs +251 -1
  75. package/dist/core/resolve/index.d.mts +2 -2
  76. package/dist/core/resolve/index.mjs +85 -1
  77. package/dist/core/resolve/property.d.mts +4 -2
  78. package/dist/core/resolve/property.mjs +53 -1
  79. package/dist/core/schema/activity.d.mts +31 -11
  80. package/dist/core/schema/arg.d.mts +3 -4
  81. package/dist/core/schema/arg.mjs +463 -1
  82. package/dist/core/schema/command.d.mts +26 -6
  83. package/dist/core/schema/command.mjs +726 -1
  84. package/dist/core/schema/flag.d.mts +485 -19
  85. package/dist/core/schema/flag.mjs +705 -1
  86. package/dist/core/schema/index.d.mts +4 -2
  87. package/dist/core/schema/middleware.d.mts +4 -3
  88. package/dist/core/schema/middleware.mjs +41 -1
  89. package/dist/core/schema/number-constraints.mjs +60 -1
  90. package/dist/core/schema/prompt.d.mts +6 -3
  91. package/dist/core/schema/run.d.mts +20 -1
  92. package/dist/core/schema/string-constraints.d.mts +97 -0
  93. package/dist/core/schema/string-constraints.mjs +69 -0
  94. package/dist/core/schema/value-parsers.d.mts +78 -0
  95. package/dist/core/schema/value-parsers.mjs +142 -0
  96. package/dist/core/schema-dsl/runtime.mjs +271 -2
  97. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  98. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  99. package/dist/core/testkit/index.d.mts +0 -31
  100. package/dist/core/testkit/index.mjs +83 -1
  101. package/dist/index.d.mts +11 -6
  102. package/dist/index.mjs +22 -1
  103. package/dist/runtime/adapter.d.mts +38 -2
  104. package/dist/runtime/adapter.mjs +87 -1
  105. package/dist/runtime/auto.d.mts +2 -3
  106. package/dist/runtime/auto.mjs +45 -1
  107. package/dist/runtime/deno.d.mts +24 -5
  108. package/dist/runtime/deno.mjs +262 -2
  109. package/dist/runtime/detect.mjs +45 -1
  110. package/dist/runtime/index.d.mts +3 -4
  111. package/dist/runtime/node.d.mts +8 -2
  112. package/dist/runtime/node.mjs +220 -2
  113. package/dist/runtime/paths.mjs +48 -1
  114. package/dist/runtime.d.mts +4 -4
  115. package/dist/runtime.mjs +6 -1
  116. package/dist/strings.mjs +22 -1
  117. package/dist/testkit.d.mts +1 -0
  118. package/dist/testkit.mjs +5 -1
  119. package/dist/version.d.mts +7 -3
  120. package/dist/version.mjs +7 -1
  121. package/dreamcli.schema.json +36 -7
  122. package/package.json +45 -42
  123. package/dist/runtime/bun.d.mts +0 -28
  124. package/dist/runtime/bun.mjs +0 -1
  125. package/src/core/cli/dispatch.ts +0 -355
  126. package/src/core/cli/help-links.ts +0 -82
  127. package/src/core/cli/index.ts +0 -1614
  128. package/src/core/cli/planner.ts +0 -656
  129. package/src/core/cli/plugin.ts +0 -117
  130. package/src/core/cli/propagate.ts +0 -97
  131. package/src/core/cli/root-help.ts +0 -342
  132. package/src/core/cli/root-surface.ts +0 -87
  133. package/src/core/cli/runtime-preflight.ts +0 -456
  134. package/src/core/completion/index.ts +0 -138
  135. package/src/core/completion/shells/bash.ts +0 -459
  136. package/src/core/completion/shells/fish.ts +0 -259
  137. package/src/core/completion/shells/powershell.ts +0 -439
  138. package/src/core/completion/shells/shared.ts +0 -310
  139. package/src/core/completion/shells/zsh.ts +0 -381
  140. package/src/core/config/index.ts +0 -417
  141. package/src/core/config/package-json.ts +0 -560
  142. package/src/core/errors/index.ts +0 -193
  143. package/src/core/execution/index.ts +0 -265
  144. package/src/core/help/ansi.ts +0 -144
  145. package/src/core/help/index.ts +0 -563
  146. package/src/core/json-schema/index.ts +0 -910
  147. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  148. package/src/core/output/activity.ts +0 -575
  149. package/src/core/output/bind.ts +0 -59
  150. package/src/core/output/contracts.ts +0 -194
  151. package/src/core/output/display-value.ts +0 -48
  152. package/src/core/output/index.ts +0 -704
  153. package/src/core/output/renderers.ts +0 -125
  154. package/src/core/output/writer.ts +0 -46
  155. package/src/core/parse/index.ts +0 -742
  156. package/src/core/prompt/index.ts +0 -623
  157. package/src/core/resolve/args.ts +0 -144
  158. package/src/core/resolve/coerce.ts +0 -500
  159. package/src/core/resolve/config.ts +0 -26
  160. package/src/core/resolve/contracts.ts +0 -135
  161. package/src/core/resolve/errors.ts +0 -227
  162. package/src/core/resolve/flags.ts +0 -269
  163. package/src/core/resolve/index.ts +0 -108
  164. package/src/core/resolve/property.ts +0 -99
  165. package/src/core/schema/activity.ts +0 -240
  166. package/src/core/schema/arg.ts +0 -841
  167. package/src/core/schema/command.ts +0 -1500
  168. package/src/core/schema/flag.ts +0 -917
  169. package/src/core/schema/index.ts +0 -96
  170. package/src/core/schema/middleware.ts +0 -171
  171. package/src/core/schema/number-constraints.ts +0 -153
  172. package/src/core/schema/prompt.ts +0 -171
  173. package/src/core/schema/run.ts +0 -198
  174. package/src/core/schema-dsl/index.ts +0 -109
  175. package/src/core/schema-dsl/parse.ts +0 -262
  176. package/src/core/schema-dsl/runtime.ts +0 -609
  177. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  178. package/src/core/testkit/index.ts +0 -147
  179. package/src/index.ts +0 -181
  180. package/src/runtime/adapter.ts +0 -303
  181. package/src/runtime/auto.ts +0 -86
  182. package/src/runtime/bun.ts +0 -48
  183. package/src/runtime/deno.ts +0 -367
  184. package/src/runtime/detect.ts +0 -105
  185. package/src/runtime/index.ts +0 -21
  186. package/src/runtime/node-builtins.d.ts +0 -27
  187. package/src/runtime/node.ts +0 -289
  188. package/src/runtime/paths.ts +0 -64
  189. package/src/runtime/support.ts +0 -77
  190. package/src/runtime.ts +0 -31
  191. package/src/schema.ts +0 -16
  192. package/src/strings.ts +0 -34
  193. package/src/testkit.ts +0 -25
  194. package/src/version.ts +0 -20
@@ -1,117 +0,0 @@
1
- /**
2
- * CLI plugin lifecycle hooks.
3
- *
4
- * Plugins attach to `CLIBuilder` and observe command execution at stable
5
- * points: before parse, after resolve, before action, and after action.
6
- *
7
- * @module dreamcli/core/cli/plugin
8
- */
9
-
10
- import type { DeprecationWarning } from '#internals/core/resolve/index.ts';
11
- import type { CommandMeta, CommandSchema, Out } from '#internals/core/schema/command.ts';
12
-
13
- /** Shared hook payload for a concrete command execution. */
14
- interface PluginCommandContext {
15
- /** Runtime command schema being executed. */
16
- readonly command: CommandSchema;
17
- /** CLI metadata for this execution. */
18
- readonly meta: CommandMeta;
19
- /** Output channel for this execution. */
20
- readonly out: Out;
21
- }
22
-
23
- /** Payload for `beforeParse`. */
24
- interface BeforeParseParams extends PluginCommandContext {
25
- /** Raw argv that will be parsed for the leaf command. */
26
- readonly argv: readonly string[];
27
- }
28
-
29
- /** Payload for hooks that observe resolved inputs. */
30
- interface ResolvedCommandParams extends PluginCommandContext {
31
- /** Fully resolved flag values. */
32
- readonly flags: Readonly<Record<string, unknown>>;
33
- /** Fully resolved argument values. */
34
- readonly args: Readonly<Record<string, unknown>>;
35
- /** Structured deprecation warnings collected during resolution. */
36
- readonly deprecations: readonly DeprecationWarning[];
37
- }
38
-
39
- /**
40
- * Individual lifecycle hooks that a plugin may implement.
41
- *
42
- * Hook order for a successful command run is:
43
- * `beforeParse` → `afterResolve` → `beforeAction` → middleware/action → `afterAction`.
44
- *
45
- * Hooks are awaited serially and run in plugin registration order at each
46
- * stage. Throwing from any hook aborts the command just like throwing from
47
- * middleware or the action handler. `afterAction` runs only after the
48
- * middleware chain and action complete successfully.
49
- */
50
- interface CLIPluginHooks {
51
- /** Called immediately before leaf-command argv is parsed. */
52
- readonly beforeParse?: (params: BeforeParseParams) => void | Promise<void>;
53
- /** Called after parse + resolve, before middleware or action execution. */
54
- readonly afterResolve?: (params: ResolvedCommandParams) => void | Promise<void>;
55
- /** Called immediately before the middleware chain and action handler run. */
56
- readonly beforeAction?: (params: ResolvedCommandParams) => void | Promise<void>;
57
- /** Called after the middleware chain and action handler complete successfully. */
58
- readonly afterAction?: (params: ResolvedCommandParams) => void | Promise<void>;
59
- }
60
-
61
- /**
62
- * Immutable plugin definition registered via `CLIBuilder.plugin()`.
63
- *
64
- * Use {@link plugin} to construct values of this shape instead of manually
65
- * assembling the object.
66
- */
67
- interface CLIPlugin {
68
- /** Optional label for diagnostics and debugging. */
69
- readonly name: string | undefined;
70
- /** Lifecycle hooks implemented by the plugin. */
71
- readonly hooks: CLIPluginHooks;
72
- }
73
-
74
- /**
75
- * Create a CLI plugin from lifecycle hooks.
76
- *
77
- * @param hooks - Lifecycle hooks to register.
78
- * @param name - Optional plugin name for diagnostics.
79
- *
80
- * @example
81
- * ```ts
82
- * import { cli, command, plugin } from '@kjanat/dreamcli';
83
- *
84
- * const deploy = command('deploy').action(({ out }) => {
85
- * out.log('deploying');
86
- * });
87
- *
88
- * const trace = plugin(
89
- * {
90
- * beforeParse: ({ argv, out }) => {
91
- * out.info(`argv: ${argv.join(' ')}`);
92
- * },
93
- * afterResolve: ({ flags, args }) => {
94
- * console.log({ flags, args });
95
- * },
96
- * },
97
- * 'trace',
98
- * );
99
- *
100
- * cli('mycli').plugin(trace).command(deploy).run();
101
- * ```
102
- *
103
- * @returns A frozen {@link CLIPlugin} definition.
104
- */
105
- function plugin(hooks: CLIPluginHooks, name?: string): CLIPlugin {
106
- const frozenHooks = Object.freeze({ ...hooks });
107
- return Object.freeze({ hooks: frozenHooks, name });
108
- }
109
-
110
- export type {
111
- BeforeParseParams,
112
- CLIPlugin,
113
- CLIPluginHooks,
114
- PluginCommandContext,
115
- ResolvedCommandParams,
116
- };
117
- export { plugin };
@@ -1,97 +0,0 @@
1
- /**
2
- * Propagated flag collection for nested command dispatch.
3
- *
4
- * Walks a command path (root ancestor to target) and collects flags marked
5
- * `propagate: true`. Child commands that define a flag with the same name
6
- * as a propagated ancestor flag "shadow" the ancestor's flag — the child's
7
- * definition wins.
8
- *
9
- * @module dreamcli/core/cli/propagate
10
- */
11
-
12
- import type { CommandSchema, FlagSchema } from '#internals/core/schema/index.ts';
13
-
14
- // --- Propagated flag collection
15
-
16
- /**
17
- * Collect propagated flags from a command path.
18
- *
19
- * The command path is an ordered array of {@linkcode CommandSchema} from the root
20
- * ancestor to the target command that will actually execute. Each ancestor's
21
- * flags marked `propagate: true` are accumulated. If a descendant (including
22
- * the target) defines a flag with the same name — regardless of whether the
23
- * descendant's flag has `propagate: true` — it shadows the ancestor's flag.
24
- *
25
- * The target command's own flags are **not** included in the result. This
26
- * function returns only the *inherited* propagated flags that should be merged
27
- * into the target command's flag set before resolution.
28
- *
29
- * @param commandPath - Ordered schemas from root ancestor to target (inclusive).
30
- * Must contain at least one element (the target itself). When the path has
31
- * only one element, no ancestors exist and the result is empty.
32
- *
33
- * @returns A record of propagated flag schemas keyed by flag name. Empty when
34
- * the path has no ancestors or no ancestor flags have `propagate: true`.
35
- *
36
- * @example
37
- * ```ts
38
- * // Given: root (--verbose [propagate]) → db → migrate
39
- * // Where migrate does NOT define --verbose
40
- * const inherited = collectPropagatedFlags([rootSchema, dbSchema, migrateSchema]);
41
- * // inherited = { verbose: <FlagSchema from root> }
42
- *
43
- * // If db also defines --verbose (shadowing root):
44
- * const inherited2 = collectPropagatedFlags([rootSchema, dbSchemaWithVerbose, migrateSchema]);
45
- * // inherited2 = { verbose: <FlagSchema from db> }
46
- * ```
47
- */
48
- function collectPropagatedFlags(
49
- commandPath: readonly CommandSchema[],
50
- ): Readonly<Record<string, FlagSchema>> {
51
- if (commandPath.length <= 1) return {};
52
-
53
- // Ancestors = all elements except the last (target).
54
- // Walk root → ... → parent, accumulating propagated flags.
55
- // Later ancestors shadow earlier ones (natural overwrite order).
56
- const accumulated: Record<string, FlagSchema> = {};
57
-
58
- for (let i = 0; i < commandPath.length - 1; i++) {
59
- const ancestor = commandPath[i];
60
- if (ancestor === undefined) continue;
61
-
62
- for (const [name, flagSchema] of Object.entries(ancestor.flags)) {
63
- if (flagSchema.propagate) {
64
- // Check if any descendant (between this ancestor and the target)
65
- // defines a flag with the same name — if so, skip the ancestor's
66
- // flag entirely. This ensures a child that redefines a flag
67
- // (even without propagate) masks the ancestor's propagated flag.
68
- let shadowedByDescendant = false;
69
- for (let j = i + 1; j < commandPath.length - 1; j++) {
70
- const descendant = commandPath[j];
71
- if (descendant !== undefined && name in descendant.flags) {
72
- shadowedByDescendant = true;
73
- break;
74
- }
75
- }
76
- if (!shadowedByDescendant) {
77
- accumulated[name] = flagSchema;
78
- }
79
- }
80
- }
81
- }
82
-
83
- // Remove any flag names that the target command defines directly.
84
- // A target's own flag — propagated or not — shadows inherited flags.
85
- const target = commandPath[commandPath.length - 1];
86
- if (target !== undefined) {
87
- for (const name of Object.keys(target.flags)) {
88
- delete accumulated[name];
89
- }
90
- }
91
-
92
- return accumulated;
93
- }
94
-
95
- // --- Exports
96
-
97
- export { collectPropagatedFlags };
@@ -1,342 +0,0 @@
1
- /**
2
- * Root-level help formatter for the CLI program.
3
- *
4
- * Separate from `help/formatHelp()` which renders per-command help —
5
- * different concerns, different format.
6
- *
7
- * @module dreamcli/core/cli/root-help
8
- * @internal
9
- */
10
-
11
- import { osc8, padEnd, wrapText } from '#internals/core/help/ansi.ts';
12
- import type { FlagEntry, HelpOptions } from '#internals/core/help/index.ts';
13
- import { formatFlagEntriesBlock, formatHelpSections } from '#internals/core/help/index.ts';
14
- import type { CommandSchema } from '#internals/core/schema/command.ts';
15
- import { command } from '#internals/core/schema/command.ts';
16
- import type { FlagSchema } from '#internals/core/schema/flag.ts';
17
- import { resolveRootSurface } from './root-surface.ts';
18
-
19
- // Re-use CLISchema inline to avoid circular import through the barrel.
20
- // Only the shape matters — we read `.name`, `.version`, `.description`, `.commands`,
21
- // `.defaultCommand`, `.helpLinks`.
22
- /** Structural subset of `CLISchema` — avoids circular imports through the barrel. */
23
- interface CLISchemaLike {
24
- readonly name: string;
25
- readonly version: string | undefined;
26
- readonly description: string | undefined;
27
- readonly commands: ReadonlyArray<{
28
- readonly schema: CommandSchema;
29
- }>;
30
- readonly defaultCommand: { readonly schema: CommandSchema } | undefined;
31
- readonly helpLinks?:
32
- | {
33
- readonly name: string | undefined;
34
- readonly version: string | undefined;
35
- }
36
- | undefined;
37
- readonly completionsFlag?: { readonly shells: readonly string[] } | undefined;
38
- /**
39
- * Config discovery settings. Only its presence is read — defined means
40
- * `.config()` enabled the built-in `--config <path>` flag, so root help
41
- * advertises it in `Global options:`.
42
- */
43
- readonly configSettings?: { readonly appName: string } | undefined;
44
- }
45
-
46
- // --- Root help formatter
47
-
48
- /**
49
- * Generate root-level help text for the CLI program.
50
- *
51
- * Shows program name, version, description, usage line, and available
52
- * subcommands. The default command is the CLI's root *surface*: its arguments
53
- * and flags are rendered inline (unless `inlineDefault` is `false`) and it is
54
- * omitted from the `Commands:` list unless `showDefaultInCommands` is set. When
55
- * `.completions({ as: 'flag' })` is active, the eager `--completions <shell>`
56
- * flag is advertised in the `Flags:` section.
57
- *
58
- * @internal
59
- */
60
- function formatRootHelp(schema: CLISchemaLike, options?: HelpOptions): string {
61
- const width = options?.width ?? 80;
62
- const binName = options?.binName ?? schema.name;
63
- const hyperlinks = options?.hyperlinks === true;
64
- const inlineDefault = options?.inlineDefault ?? true;
65
- const showDefaultInCommands = options?.showDefaultInCommands ?? false;
66
-
67
- const surface = resolveRootSurface(schema);
68
- const defaultCommand = surface.visibleDefaultCommand;
69
- // `inlineDefault: false` hides the default command's args/flags, but the eager
70
- // `--completions` flag is a root-level option that must still be advertised, so
71
- // a synthetic completions-only surface is rendered even then.
72
- //
73
- // Exception: when the default command is the *only* surface — no visible
74
- // subcommands AND no eager `--completions` flag to advertise — suppressing it
75
- // would collapse root help to a bare `Usage: <bin> [options]` with no
76
- // discoverable interface at all. In that case the default is always rendered
77
- // inline regardless of `inlineDefault`. (With a completions flag the synthetic
78
- // surface still gives a discoverable path, so `inlineDefault: false` is honored.)
79
- const defaultIsSoleSurface =
80
- !surface.hasVisibleSubcommands && schema.completionsFlag === undefined;
81
- const renderDefaultInline = inlineDefault || defaultIsSoleSurface;
82
- const inlineDefaultCommand = renderDefaultInline ? defaultCommand : undefined;
83
- const surfaceCommand = resolveSurfaceCommand(schema, inlineDefaultCommand);
84
- const inline = surfaceCommand !== undefined;
85
-
86
- const sections: string[] = [formatHeader(schema, hyperlinks)];
87
- if (schema.description !== undefined) {
88
- sections.push(schema.description);
89
- }
90
-
91
- // ---- Usage --------------------------------------------------------------
92
- // A real default makes the command optional (`[command]`); without one a
93
- // command must be chosen (`<command>`). With no subcommands at all, the
94
- // default command's own usage stands alone.
95
- const placeholder = surface.hasVisibleSubcommands
96
- ? defaultCommand !== undefined
97
- ? '[command]'
98
- : '<command>'
99
- : '';
100
- const rootUsage =
101
- placeholder.length > 0
102
- ? `Usage: ${binName} ${placeholder} [options]`
103
- : `Usage: ${binName} [options]`;
104
-
105
- let surfaceSections: string[] = [];
106
- if (inline && surfaceCommand !== undefined) {
107
- surfaceSections = [
108
- ...formatHelpSections(surfaceCommand, {
109
- ...options,
110
- binName,
111
- isDefaultHelp: true,
112
- }),
113
- ];
114
- }
115
- const surfaceUsage = surfaceSections.shift();
116
- // Merge the surface usage into the root usage only when the default command is
117
- // actually inlined; a completions-only synthetic surface keeps the root usage.
118
- if (inline && surfaceUsage !== undefined && inlineDefaultCommand !== undefined) {
119
- sections.push(
120
- surface.hasVisibleSubcommands ? mergeUsageSections(rootUsage, surfaceUsage) : surfaceUsage,
121
- );
122
- } else {
123
- sections.push(rootUsage);
124
- }
125
-
126
- // ---- Commands -----------------------------------------------------------
127
- const listedCommands =
128
- showDefaultInCommands && defaultCommand !== undefined
129
- ? [...surface.visibleSubcommands, defaultCommand]
130
- : surface.visibleSubcommands;
131
- if (listedCommands.length > 0) {
132
- sections.push(
133
- formatRootCommandsSection(
134
- listedCommands,
135
- showDefaultInCommands ? defaultCommand?.name : undefined,
136
- width,
137
- ),
138
- );
139
- }
140
-
141
- // ---- Inline default surface (args/flags) --------------------------------
142
- if (inline && surfaceCommand !== undefined) {
143
- // Drop the surface command's description when it duplicates the program
144
- // description already printed at the top.
145
- if (
146
- surfaceCommand.description !== undefined &&
147
- surfaceCommand.description === schema.description &&
148
- surfaceSections[0] === surfaceCommand.description
149
- ) {
150
- surfaceSections.shift();
151
- }
152
- sections.push(...surfaceSections);
153
- }
154
-
155
- // ---- Global options (active built-in flags) -----------------------------
156
- // Built-ins are framework-provided and never appear in any command schema, so
157
- // they are advertised here for discoverability (#32). `--completions` is not
158
- // listed: when active it is already injected into the inline surface's flags.
159
- const globalOptions = formatGlobalOptionsSection(schema, width);
160
- if (globalOptions.length > 0) {
161
- sections.push(globalOptions);
162
- }
163
-
164
- // ---- Footer -------------------------------------------------------------
165
- const footerVisible = options?.footer ?? surface.hasVisibleSubcommands;
166
- if (footerVisible) {
167
- const footerPlaceholder = surface.hasVisibleSubcommands
168
- ? defaultCommand !== undefined
169
- ? ' [command]'
170
- : ' <command>'
171
- : '';
172
- sections.push(`Run '${binName}${footerPlaceholder} --help' for more information.`);
173
- }
174
-
175
- return `${sections.join('\n\n')}\n`;
176
- }
177
-
178
- /**
179
- * Resolve the command rendered inline as the CLI's root surface.
180
- *
181
- * Returns the default command, augmented with the eager `--completions <shell>`
182
- * flag when `.completions({ as: 'flag' })` is active. When there is no default
183
- * command but the completions flag is configured, a synthetic surface carrying
184
- * just that flag is returned so the flag is still advertised. Returns
185
- * `undefined` when there is nothing to render inline.
186
- *
187
- * @internal
188
- */
189
- function resolveSurfaceCommand(
190
- schema: CLISchemaLike,
191
- defaultCommand: CommandSchema | undefined,
192
- ): CommandSchema | undefined {
193
- if (schema.completionsFlag === undefined) return defaultCommand;
194
- const base = defaultCommand ?? command(schema.name).schema;
195
- return {
196
- ...base,
197
- flags: { completions: completionsFlagSchema(schema.completionsFlag.shells), ...base.flags },
198
- };
199
- }
200
-
201
- /**
202
- * Build the synthetic, render-only flag schema for the eager `--completions`
203
- * flag. It never participates in parsing (the planner intercepts the flag
204
- * directly); it exists purely so root help can list
205
- * `--completions <bash|zsh|…>` in its `Flags:` section.
206
- *
207
- * @internal
208
- */
209
- function completionsFlagSchema(shells: readonly string[]): FlagSchema {
210
- return {
211
- kind: 'enum',
212
- presence: 'optional',
213
- defaultValue: undefined,
214
- aliases: [],
215
- envVar: undefined,
216
- configPath: undefined,
217
- description: 'Print a shell completion script and exit',
218
- enumValues: shells,
219
- elementSchema: undefined,
220
- numberConstraints: undefined,
221
- prompt: undefined,
222
- parseFn: undefined,
223
- deprecated: undefined,
224
- propagate: false,
225
- };
226
- }
227
-
228
- /**
229
- * Render the header line (`name vX.Y.Z`).
230
- *
231
- * When `hyperlinks` is enabled and the schema carries link URLs (via
232
- * `CLIBuilder.links()`, possibly derived from package.json metadata), the
233
- * name and version are wrapped in OSC 8 hyperlinks. The header is the only
234
- * place links are emitted — usage lines, hints, and the commands table stay
235
- * plain.
236
- *
237
- * @param schema - The CLI schema.
238
- * @param hyperlinks - Whether OSC 8 hyperlinks may be emitted.
239
- * @returns The header line.
240
- * @internal
241
- */
242
- function formatHeader(schema: CLISchemaLike, hyperlinks: boolean): string {
243
- const links = hyperlinks ? schema.helpLinks : undefined;
244
- const name = links?.name !== undefined ? osc8(links.name, schema.name) : schema.name;
245
- if (schema.version === undefined) return name;
246
- const version = `v${schema.version}`;
247
- return `${name} ${links?.version !== undefined ? osc8(links.version, version) : version}`;
248
- }
249
-
250
- /**
251
- * Format the "Commands:" section with aligned names and descriptions.
252
- *
253
- * @param visibleCommands - Non-hidden top-level commands.
254
- * @param defaultName - Name of the default command (appends " (default)" tag).
255
- * @param width - Terminal width for description wrapping.
256
- * @returns Formatted commands block.
257
- * @internal
258
- */
259
- function formatRootCommandsSection(
260
- visibleCommands: readonly CommandSchema[],
261
- defaultName: string | undefined,
262
- width: number,
263
- ): string {
264
- const lines: string[] = ['Commands:'];
265
- const GAP = 2;
266
- const DEFAULT_TAG = ' (default)';
267
-
268
- // Compute max command name length for alignment (account for default tag)
269
- let maxNameLen = 0;
270
- for (const cmd of visibleCommands) {
271
- const tagLen = cmd.name === defaultName ? DEFAULT_TAG.length : 0;
272
- const nameLen = cmd.name.length + tagLen;
273
- if (nameLen > maxNameLen) {
274
- maxNameLen = nameLen;
275
- }
276
- }
277
-
278
- const descCol = 2 + maxNameLen + GAP; // 2 for indent
279
- for (const cmd of visibleCommands) {
280
- const isDefault = cmd.name === defaultName;
281
- const label = isDefault ? `${cmd.name}${DEFAULT_TAG}` : cmd.name;
282
- const padded = padEnd(` ${label}`, descCol);
283
- const desc = cmd.description ?? '';
284
- if (desc.length === 0) {
285
- lines.push(padded.trimEnd());
286
- } else {
287
- lines.push(`${padded}${wrapText(desc, width, descCol)}`);
288
- }
289
- }
290
-
291
- return lines.join('\n');
292
- }
293
-
294
- /**
295
- * Build the `Global options:` section advertising the active built-in flags.
296
- *
297
- * `--help, -h` and `--json` are always available; `--version, -V` is shown only
298
- * when the program declares a version; `--config <path>` only when `.config()`
299
- * enabled config discovery. The eager `--completions` flag is intentionally
300
- * omitted — it is advertised via the inline surface when active.
301
- *
302
- * @param schema - The CLI schema (read for `version` and `configSettings`).
303
- * @param width - Terminal width for description wrapping.
304
- * @returns Formatted `Global options:` block (always non-empty).
305
- * @internal
306
- */
307
- function formatGlobalOptionsSection(schema: CLISchemaLike, width: number): string {
308
- const entries: FlagEntry[] = [
309
- { left: '-h, --help', description: 'Show this help message and exit' },
310
- ];
311
- if (schema.version !== undefined) {
312
- entries.push({ left: '-V, --version', description: 'Print the version number and exit' });
313
- }
314
- entries.push({ left: '--json', description: 'Emit machine-readable JSON output' });
315
- if (schema.configSettings !== undefined) {
316
- entries.push({
317
- left: '--config <path>',
318
- description: 'Load configuration from the given file',
319
- });
320
- }
321
- return formatFlagEntriesBlock('Global options:', entries, width);
322
- }
323
-
324
- /**
325
- * Merge root and default-command usage lines into a single block.
326
- *
327
- * @param rootUsage - The root usage line (e.g. `Usage: mycli [command] [options]`).
328
- * @param commandUsage - The default command's usage line.
329
- * @returns Combined usage block with aligned continuation.
330
- * @internal
331
- */
332
- function mergeUsageSections(rootUsage: string, commandUsage: string): string {
333
- const usagePrefix = 'Usage: ';
334
- const commandSuffix = commandUsage.startsWith(usagePrefix)
335
- ? commandUsage.slice(usagePrefix.length)
336
- : commandUsage;
337
- return `${rootUsage}\n${' '.repeat(usagePrefix.length)}${commandSuffix}`;
338
- }
339
-
340
- // --- Exports
341
-
342
- export { formatRootHelp };
@@ -1,87 +0,0 @@
1
- /**
2
- * Shared root-surface analysis for help and completion rendering.
3
- *
4
- * Answers structural questions about what the CLI root looks like:
5
- * which top-level commands are visible, whether the default command is
6
- * visible, and whether the root is effectively a single visible default.
7
- *
8
- * @module dreamcli/core/cli/root-surface
9
- * @internal
10
- */
11
-
12
- import type { CommandSchema } from '#internals/core/schema/command.ts';
13
-
14
- /**
15
- * Structural CLI shape needed for root-surface analysis.
16
- *
17
- * Uses structural typing to avoid importing the full `CLISchema` and
18
- * creating unnecessary cross-module coupling.
19
- *
20
- * @internal
21
- */
22
- interface RootSurfaceSchemaLike {
23
- readonly commands: ReadonlyArray<{
24
- readonly schema: CommandSchema;
25
- }>;
26
- readonly defaultCommand: { readonly schema: CommandSchema } | undefined;
27
- }
28
-
29
- /**
30
- * Normalized root shape shared by help and completion logic.
31
- *
32
- * Since v0.3 the default command is a distinct root *surface* rather than a
33
- * named subcommand: `.default()` no longer registers it under
34
- * {@link RootSurfaceSchemaLike.commands}. To stay robust against callers that
35
- * still place the default in the command list (e.g. hand-built test schemas),
36
- * {@link resolveRootSurface} always derives {@link RootSurface.visibleSubcommands}
37
- * by excluding the default command from the visible command list.
38
- *
39
- * @internal
40
- */
41
- interface RootSurface {
42
- /** All visible top-level commands as declared in `schema.commands`. */
43
- readonly visibleCommands: readonly CommandSchema[];
44
- /** Visible real subcommands — `visibleCommands` minus the default command. */
45
- readonly visibleSubcommands: readonly CommandSchema[];
46
- /** The visible default command, or `undefined` when none exists or it is hidden. */
47
- readonly visibleDefaultCommand: CommandSchema | undefined;
48
- /** Whether a visible default command exists. */
49
- readonly hasVisibleDefault: boolean;
50
- /** Whether any visible real subcommands exist (the default does not count). */
51
- readonly hasVisibleSubcommands: boolean;
52
- }
53
-
54
- /**
55
- * Resolve the visible shape of the CLI root.
56
- *
57
- * Hidden commands are excluded from the visible command list. Hidden
58
- * default commands remain executable, but are not surfaced through
59
- * help or completions. The default command is reported separately from the
60
- * real subcommands so help and completion can render it as the root surface
61
- * instead of echoing it as a pseudo-subcommand.
62
- *
63
- * @internal
64
- */
65
- function resolveRootSurface(schema: RootSurfaceSchemaLike): RootSurface {
66
- const visibleCommands = schema.commands
67
- .map((command) => command.schema)
68
- .filter((command) => !command.hidden);
69
- const rawDefaultCommand = schema.defaultCommand?.schema;
70
- const visibleDefaultCommand =
71
- rawDefaultCommand !== undefined && !rawDefaultCommand.hidden ? rawDefaultCommand : undefined;
72
- const visibleSubcommands =
73
- visibleDefaultCommand !== undefined
74
- ? visibleCommands.filter((command) => command.name !== visibleDefaultCommand.name)
75
- : visibleCommands;
76
-
77
- return {
78
- visibleCommands,
79
- visibleSubcommands,
80
- visibleDefaultCommand,
81
- hasVisibleDefault: visibleDefaultCommand !== undefined,
82
- hasVisibleSubcommands: visibleSubcommands.length > 0,
83
- };
84
- }
85
-
86
- export type { RootSurface, RootSurfaceSchemaLike };
87
- export { resolveRootSurface };