@kjanat/dreamcli 2.5.0 → 3.0.0-rc.2

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 (160) hide show
  1. package/CHANGELOG.md +153 -1
  2. package/README.md +9 -2
  3. package/dist/core/cli/dispatch.mjs +214 -1
  4. package/dist/core/cli/help-links.mjs +41 -1
  5. package/dist/core/cli/index.d.mts +109 -16
  6. package/dist/core/cli/index.mjs +901 -1
  7. package/dist/core/cli/planner.d.mts +27 -5
  8. package/dist/core/cli/planner.mjs +300 -1
  9. package/dist/core/cli/plugin.mjs +41 -1
  10. package/dist/core/cli/propagate.mjs +57 -1
  11. package/dist/core/cli/root-help.d.mts +16 -2
  12. package/dist/core/cli/root-help.mjs +208 -6
  13. package/dist/core/cli/root-surface.d.mts +18 -3
  14. package/dist/core/cli/root-surface.mjs +27 -1
  15. package/dist/core/cli/runtime-preflight.d.mts +16 -1
  16. package/dist/core/cli/runtime-preflight.mjs +168 -1
  17. package/dist/core/completion/index.d.mts +32 -1
  18. package/dist/core/completion/index.mjs +90 -1
  19. package/dist/core/completion/shells/bash.mjs +304 -3
  20. package/dist/core/completion/shells/fish.mjs +159 -2
  21. package/dist/core/completion/shells/powershell.mjs +353 -2
  22. package/dist/core/completion/shells/shared.d.mts +10 -0
  23. package/dist/core/completion/shells/shared.mjs +154 -1
  24. package/dist/core/completion/shells/zsh.mjs +244 -2
  25. package/dist/core/config/index.mjs +246 -1
  26. package/dist/core/config/package-json.mjs +385 -3
  27. package/dist/core/errors/index.mjs +87 -1
  28. package/dist/core/execution/index.mjs +189 -1
  29. package/dist/core/help/ansi.mjs +122 -2
  30. package/dist/core/help/index.d.mts +45 -1
  31. package/dist/core/help/index.mjs +329 -7
  32. package/dist/core/json-schema/index.mjs +487 -9
  33. package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
  34. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  35. package/dist/core/output/activity.mjs +452 -1
  36. package/dist/core/output/bind.mjs +56 -1
  37. package/dist/core/output/contracts.mjs +57 -1
  38. package/dist/core/output/display-value.mjs +32 -1
  39. package/dist/core/output/index.d.mts +21 -0
  40. package/dist/core/output/index.mjs +442 -2
  41. package/dist/core/output/renderers.mjs +46 -1
  42. package/dist/core/output/writer.mjs +12 -1
  43. package/dist/core/parse/index.d.mts +15 -1
  44. package/dist/core/parse/index.mjs +555 -1
  45. package/dist/core/prompt/index.d.mts +11 -4
  46. package/dist/core/prompt/index.mjs +348 -6
  47. package/dist/core/resolve/args.mjs +105 -1
  48. package/dist/core/resolve/coerce.mjs +279 -1
  49. package/dist/core/resolve/config.mjs +19 -1
  50. package/dist/core/resolve/errors.mjs +140 -2
  51. package/dist/core/resolve/flags.mjs +196 -1
  52. package/dist/core/resolve/index.mjs +85 -1
  53. package/dist/core/resolve/property.d.mts +2 -1
  54. package/dist/core/resolve/property.mjs +45 -1
  55. package/dist/core/schema/arg.d.mts +90 -10
  56. package/dist/core/schema/arg.mjs +463 -1
  57. package/dist/core/schema/command.d.mts +21 -1
  58. package/dist/core/schema/command.mjs +712 -1
  59. package/dist/core/schema/flag.d.mts +92 -2
  60. package/dist/core/schema/flag.mjs +453 -1
  61. package/dist/core/schema/index.d.mts +2 -1
  62. package/dist/core/schema/middleware.mjs +41 -1
  63. package/dist/core/schema/number-constraints.d.mts +96 -0
  64. package/dist/core/schema/number-constraints.mjs +60 -0
  65. package/dist/core/schema/prompt.d.mts +15 -0
  66. package/dist/core/schema/run.d.mts +4 -4
  67. package/dist/core/schema-dsl/runtime.mjs +271 -2
  68. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  69. package/dist/core/testkit/index.d.mts +9 -5
  70. package/dist/core/testkit/index.mjs +83 -1
  71. package/dist/index.d.mts +3 -1
  72. package/dist/index.mjs +22 -1
  73. package/dist/runtime/adapter.mjs +82 -1
  74. package/dist/runtime/auto.mjs +46 -1
  75. package/dist/runtime/bun.mjs +28 -1
  76. package/dist/runtime/deno.mjs +217 -2
  77. package/dist/runtime/detect.mjs +45 -1
  78. package/dist/runtime/node.mjs +169 -2
  79. package/dist/runtime/paths.mjs +48 -1
  80. package/dist/runtime.mjs +7 -1
  81. package/dist/strings.mjs +22 -1
  82. package/dist/testkit.mjs +5 -1
  83. package/dist/version.mjs +7 -1
  84. package/examples/basic.ts +5 -1
  85. package/examples/gh/package.json +2 -7
  86. package/examples/pwsh-demo/package.json +1 -7
  87. package/examples/pwsh-demo/src/main.test.ts +1 -4
  88. package/examples/pwsh-demo/src/main.ts +14 -4
  89. package/examples/transport-launcher.ts +85 -0
  90. package/package.json +23 -41
  91. package/dist/runtime/support.d.mts +0 -42
  92. package/dist/runtime/support.mjs +0 -1
  93. package/src/core/cli/dispatch.ts +0 -349
  94. package/src/core/cli/help-links.ts +0 -82
  95. package/src/core/cli/index.ts +0 -1413
  96. package/src/core/cli/planner.ts +0 -487
  97. package/src/core/cli/plugin.ts +0 -117
  98. package/src/core/cli/propagate.ts +0 -97
  99. package/src/core/cli/root-help.ts +0 -252
  100. package/src/core/cli/root-surface.ts +0 -74
  101. package/src/core/cli/runtime-preflight.ts +0 -438
  102. package/src/core/completion/index.ts +0 -88
  103. package/src/core/completion/shells/bash.ts +0 -459
  104. package/src/core/completion/shells/fish.ts +0 -259
  105. package/src/core/completion/shells/powershell.ts +0 -439
  106. package/src/core/completion/shells/shared.ts +0 -283
  107. package/src/core/completion/shells/zsh.ts +0 -381
  108. package/src/core/config/index.ts +0 -417
  109. package/src/core/config/package-json.ts +0 -560
  110. package/src/core/errors/index.ts +0 -193
  111. package/src/core/execution/index.ts +0 -268
  112. package/src/core/help/ansi.ts +0 -144
  113. package/src/core/help/index.ts +0 -516
  114. package/src/core/json-schema/index.ts +0 -891
  115. package/src/core/json-schema/meta-descriptions.generated.ts +0 -185
  116. package/src/core/output/activity.ts +0 -575
  117. package/src/core/output/bind.ts +0 -59
  118. package/src/core/output/contracts.ts +0 -194
  119. package/src/core/output/display-value.ts +0 -48
  120. package/src/core/output/index.ts +0 -704
  121. package/src/core/output/renderers.ts +0 -125
  122. package/src/core/output/writer.ts +0 -46
  123. package/src/core/parse/index.ts +0 -681
  124. package/src/core/prompt/index.ts +0 -583
  125. package/src/core/resolve/args.ts +0 -144
  126. package/src/core/resolve/coerce.ts +0 -432
  127. package/src/core/resolve/config.ts +0 -26
  128. package/src/core/resolve/contracts.ts +0 -135
  129. package/src/core/resolve/errors.ts +0 -227
  130. package/src/core/resolve/flags.ts +0 -255
  131. package/src/core/resolve/index.ts +0 -108
  132. package/src/core/resolve/property.ts +0 -99
  133. package/src/core/schema/activity.ts +0 -240
  134. package/src/core/schema/arg.ts +0 -719
  135. package/src/core/schema/command.ts +0 -1498
  136. package/src/core/schema/flag.ts +0 -801
  137. package/src/core/schema/index.ts +0 -91
  138. package/src/core/schema/middleware.ts +0 -171
  139. package/src/core/schema/prompt.ts +0 -156
  140. package/src/core/schema/run.ts +0 -198
  141. package/src/core/schema-dsl/index.ts +0 -109
  142. package/src/core/schema-dsl/parse.ts +0 -262
  143. package/src/core/schema-dsl/runtime.ts +0 -609
  144. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  145. package/src/core/testkit/index.ts +0 -123
  146. package/src/index.ts +0 -179
  147. package/src/runtime/adapter.ts +0 -303
  148. package/src/runtime/auto.ts +0 -110
  149. package/src/runtime/bun.ts +0 -55
  150. package/src/runtime/deno.ts +0 -369
  151. package/src/runtime/detect.ts +0 -105
  152. package/src/runtime/index.ts +0 -21
  153. package/src/runtime/node-builtins.d.ts +0 -27
  154. package/src/runtime/node.ts +0 -300
  155. package/src/runtime/paths.ts +0 -64
  156. package/src/runtime/support.ts +0 -135
  157. package/src/runtime.ts +0 -31
  158. package/src/strings.ts +0 -34
  159. package/src/testkit.ts +0 -25
  160. package/src/version.ts +0 -20
@@ -1,6 +1,208 @@
1
- import{resolveRootSurface as e}from"./root-surface.mjs";import{osc8 as t,padEnd as n,wrapText as r}from"../help/ansi.mjs";import{formatHelpSections as i}from"../help/index.mjs";function a(t,n){let r=n?.width??80,a=n?.hyperlinks===!0,s=e(t);if(s.hasSingleVisibleDefault){let e=s.visibleDefaultCommand;if(e!==void 0){let c=o(t,s.visibleCommands,s.visibleDefaultCommand,r,a),l=c.findIndex(e=>e.startsWith(`Usage: `)),d=[...i(e,{...n,binName:t.name,isDefaultHelp:!0})],f=d.shift();return l!==-1&&f!==void 0&&(c[l]=u(c[l]??``,f)),e.description!==void 0&&t.description!==void 0&&e.description===t.description&&d.shift(),c.push(...d),`${c.join(`
2
-
3
- `)}\n`}}let l=o(t,s.visibleCommands,s.visibleDefaultCommand,r,a),d=c(s.visibleCommands,s.visibleDefaultCommand);return l.push(d.length>0?`Run '${t.name} ${d} --help' for more information.`:`Run '${t.name} --help' for more information.`),`${l.join(`
4
-
5
- `)}\n`}function o(e,t,n,r,i){let a=[];a.push(s(e,i)),e.description!==void 0&&a.push(e.description);let o=c(t,n);return a.push(o.length>0?`Usage: ${e.name} ${o} [options]`:`Usage: ${e.name} [options]`),t.length>0&&a.push(l(t,n?.name,r)),a}function s(e,n){let r=n?e.helpLinks:void 0,i=r?.name===void 0?e.name:t(r.name,e.name);if(e.version===void 0)return i;let a=`v${e.version}`;return`${i} ${r?.version===void 0?a:t(r.version,a)}`}function c(e,t){return e.length===0&&t===void 0?``:t===void 0?`<command>`:`[command]`}function l(e,t,i){let a=[`Commands:`],o=0;for(let n of e){let e=n.name===t?10:0,r=n.name.length+e;r>o&&(o=r)}let s=2+o+2;for(let o of e){let e=n(` ${o.name===t?`${o.name} (default)`:o.name}`,s),c=o.description??``;c.length===0?a.push(e.trimEnd()):a.push(`${e}${r(c,i,s)}`)}return a.join(`
6
- `)}function u(e,t){let n=t.startsWith(`Usage: `)?t.slice(7):t;return`${e}\n${` `.repeat(7)}${n}`}export{a as formatRootHelp};
1
+ import { resolveRootSurface } from "./root-surface.mjs";
2
+ import { osc8, padEnd, wrapText } from "../help/ansi.mjs";
3
+ import { formatFlagEntriesBlock, formatHelpSections } from "../help/index.mjs";
4
+ import { command } from "../schema/command.mjs";
5
+ //#region src/core/cli/root-help.ts
6
+ /**
7
+ * Root-level help formatter for the CLI program.
8
+ *
9
+ * Separate from `help/formatHelp()` which renders per-command help —
10
+ * different concerns, different format.
11
+ *
12
+ * @module dreamcli/core/cli/root-help
13
+ * @internal
14
+ */
15
+ /**
16
+ * Generate root-level help text for the CLI program.
17
+ *
18
+ * Shows program name, version, description, usage line, and available
19
+ * subcommands. The default command is the CLI's root *surface*: its arguments
20
+ * and flags are rendered inline (unless `inlineDefault` is `false`) and it is
21
+ * omitted from the `Commands:` list unless `showDefaultInCommands` is set. When
22
+ * `.completions({ as: 'flag' })` is active, the eager `--completions <shell>`
23
+ * flag is advertised in the `Flags:` section.
24
+ *
25
+ * @internal
26
+ */
27
+ function formatRootHelp(schema, options) {
28
+ const width = options?.width ?? 80;
29
+ const binName = options?.binName ?? schema.name;
30
+ const hyperlinks = options?.hyperlinks === true;
31
+ const inlineDefault = options?.inlineDefault ?? true;
32
+ const showDefaultInCommands = options?.showDefaultInCommands ?? false;
33
+ const surface = resolveRootSurface(schema);
34
+ const defaultCommand = surface.visibleDefaultCommand;
35
+ const defaultIsSoleSurface = !surface.hasVisibleSubcommands && schema.completionsFlag === void 0;
36
+ const inlineDefaultCommand = inlineDefault || defaultIsSoleSurface ? defaultCommand : void 0;
37
+ const surfaceCommand = resolveSurfaceCommand(schema, inlineDefaultCommand);
38
+ const inline = surfaceCommand !== void 0;
39
+ const sections = [formatHeader(schema, hyperlinks)];
40
+ if (schema.description !== void 0) sections.push(schema.description);
41
+ const placeholder = surface.hasVisibleSubcommands ? defaultCommand !== void 0 ? "[command]" : "<command>" : "";
42
+ const rootUsage = placeholder.length > 0 ? `Usage: ${binName} ${placeholder} [options]` : `Usage: ${binName} [options]`;
43
+ let surfaceSections = [];
44
+ if (inline && surfaceCommand !== void 0) surfaceSections = [...formatHelpSections(surfaceCommand, {
45
+ ...options,
46
+ binName,
47
+ isDefaultHelp: true
48
+ })];
49
+ const surfaceUsage = surfaceSections.shift();
50
+ if (inline && surfaceUsage !== void 0 && inlineDefaultCommand !== void 0) sections.push(surface.hasVisibleSubcommands ? mergeUsageSections(rootUsage, surfaceUsage) : surfaceUsage);
51
+ else sections.push(rootUsage);
52
+ const listedCommands = showDefaultInCommands && defaultCommand !== void 0 ? [...surface.visibleSubcommands, defaultCommand] : surface.visibleSubcommands;
53
+ if (listedCommands.length > 0) sections.push(formatRootCommandsSection(listedCommands, showDefaultInCommands ? defaultCommand?.name : void 0, width));
54
+ if (inline && surfaceCommand !== void 0) {
55
+ if (surfaceCommand.description !== void 0 && surfaceCommand.description === schema.description && surfaceSections[0] === surfaceCommand.description) surfaceSections.shift();
56
+ sections.push(...surfaceSections);
57
+ }
58
+ const globalOptions = formatGlobalOptionsSection(schema, width);
59
+ if (globalOptions.length > 0) sections.push(globalOptions);
60
+ if (options?.footer ?? surface.hasVisibleSubcommands) {
61
+ const footerPlaceholder = surface.hasVisibleSubcommands ? defaultCommand !== void 0 ? " [command]" : " <command>" : "";
62
+ sections.push(`Run '${binName}${footerPlaceholder} --help' for more information.`);
63
+ }
64
+ return `${sections.join("\n\n")}\n`;
65
+ }
66
+ /**
67
+ * Resolve the command rendered inline as the CLI's root surface.
68
+ *
69
+ * Returns the default command, augmented with the eager `--completions <shell>`
70
+ * flag when `.completions({ as: 'flag' })` is active. When there is no default
71
+ * command but the completions flag is configured, a synthetic surface carrying
72
+ * just that flag is returned so the flag is still advertised. Returns
73
+ * `undefined` when there is nothing to render inline.
74
+ *
75
+ * @internal
76
+ */
77
+ function resolveSurfaceCommand(schema, defaultCommand) {
78
+ if (schema.completionsFlag === void 0) return defaultCommand;
79
+ const base = defaultCommand ?? command(schema.name).schema;
80
+ return {
81
+ ...base,
82
+ flags: {
83
+ completions: completionsFlagSchema(schema.completionsFlag.shells),
84
+ ...base.flags
85
+ }
86
+ };
87
+ }
88
+ /**
89
+ * Build the synthetic, render-only flag schema for the eager `--completions`
90
+ * flag. It never participates in parsing (the planner intercepts the flag
91
+ * directly); it exists purely so root help can list
92
+ * `--completions <bash|zsh|…>` in its `Flags:` section.
93
+ *
94
+ * @internal
95
+ */
96
+ function completionsFlagSchema(shells) {
97
+ return {
98
+ kind: "enum",
99
+ presence: "optional",
100
+ defaultValue: void 0,
101
+ aliases: [],
102
+ envVar: void 0,
103
+ configPath: void 0,
104
+ description: "Print a shell completion script and exit",
105
+ enumValues: shells,
106
+ elementSchema: void 0,
107
+ numberConstraints: void 0,
108
+ prompt: void 0,
109
+ parseFn: void 0,
110
+ deprecated: void 0,
111
+ propagate: false
112
+ };
113
+ }
114
+ /**
115
+ * Render the header line (`name vX.Y.Z`).
116
+ *
117
+ * When `hyperlinks` is enabled and the schema carries link URLs (via
118
+ * `CLIBuilder.links()`, possibly derived from package.json metadata), the
119
+ * name and version are wrapped in OSC 8 hyperlinks. The header is the only
120
+ * place links are emitted — usage lines, hints, and the commands table stay
121
+ * plain.
122
+ *
123
+ * @param schema - The CLI schema.
124
+ * @param hyperlinks - Whether OSC 8 hyperlinks may be emitted.
125
+ * @returns The header line.
126
+ * @internal
127
+ */
128
+ function formatHeader(schema, hyperlinks) {
129
+ const links = hyperlinks ? schema.helpLinks : void 0;
130
+ const name = links?.name !== void 0 ? osc8(links.name, schema.name) : schema.name;
131
+ if (schema.version === void 0) return name;
132
+ const version = `v${schema.version}`;
133
+ return `${name} ${links?.version !== void 0 ? osc8(links.version, version) : version}`;
134
+ }
135
+ /**
136
+ * Format the "Commands:" section with aligned names and descriptions.
137
+ *
138
+ * @param visibleCommands - Non-hidden top-level commands.
139
+ * @param defaultName - Name of the default command (appends " (default)" tag).
140
+ * @param width - Terminal width for description wrapping.
141
+ * @returns Formatted commands block.
142
+ * @internal
143
+ */
144
+ function formatRootCommandsSection(visibleCommands, defaultName, width) {
145
+ const lines = ["Commands:"];
146
+ const GAP = 2;
147
+ const DEFAULT_TAG = " (default)";
148
+ let maxNameLen = 0;
149
+ for (const cmd of visibleCommands) {
150
+ const tagLen = cmd.name === defaultName ? 10 : 0;
151
+ const nameLen = cmd.name.length + tagLen;
152
+ if (nameLen > maxNameLen) maxNameLen = nameLen;
153
+ }
154
+ const descCol = 2 + maxNameLen + GAP;
155
+ for (const cmd of visibleCommands) {
156
+ const padded = padEnd(` ${cmd.name === defaultName ? `${cmd.name}${DEFAULT_TAG}` : cmd.name}`, descCol);
157
+ const desc = cmd.description ?? "";
158
+ if (desc.length === 0) lines.push(padded.trimEnd());
159
+ else lines.push(`${padded}${wrapText(desc, width, descCol)}`);
160
+ }
161
+ return lines.join("\n");
162
+ }
163
+ /**
164
+ * Build the `Global options:` section advertising the active built-in flags.
165
+ *
166
+ * `--help, -h` and `--json` are always available; `--version, -V` is shown only
167
+ * when the program declares a version; `--config <path>` only when `.config()`
168
+ * enabled config discovery. The eager `--completions` flag is intentionally
169
+ * omitted — it is advertised via the inline surface when active.
170
+ *
171
+ * @param schema - The CLI schema (read for `version` and `configSettings`).
172
+ * @param width - Terminal width for description wrapping.
173
+ * @returns Formatted `Global options:` block (always non-empty).
174
+ * @internal
175
+ */
176
+ function formatGlobalOptionsSection(schema, width) {
177
+ const entries = [{
178
+ left: "-h, --help",
179
+ description: "Show this help message and exit"
180
+ }];
181
+ if (schema.version !== void 0) entries.push({
182
+ left: "-V, --version",
183
+ description: "Print the version number and exit"
184
+ });
185
+ entries.push({
186
+ left: "--json",
187
+ description: "Emit machine-readable JSON output"
188
+ });
189
+ if (schema.configSettings !== void 0) entries.push({
190
+ left: "--config <path>",
191
+ description: "Load configuration from the given file"
192
+ });
193
+ return formatFlagEntriesBlock("Global options:", entries, width);
194
+ }
195
+ /**
196
+ * Merge root and default-command usage lines into a single block.
197
+ *
198
+ * @param rootUsage - The root usage line (e.g. `Usage: mycli [command] [options]`).
199
+ * @param commandUsage - The default command's usage line.
200
+ * @returns Combined usage block with aligned continuation.
201
+ * @internal
202
+ */
203
+ function mergeUsageSections(rootUsage, commandUsage) {
204
+ const commandSuffix = commandUsage.startsWith("Usage: ") ? commandUsage.slice(7) : commandUsage;
205
+ return `${rootUsage}\n${" ".repeat(7)}${commandSuffix}`;
206
+ }
207
+ //#endregion
208
+ export { formatRootHelp };
@@ -20,20 +20,35 @@ interface RootSurfaceSchemaLike {
20
20
  /**
21
21
  * Normalized root shape shared by help and completion logic.
22
22
  *
23
+ * Since v0.3 the default command is a distinct root *surface* rather than a
24
+ * named subcommand: `.default()` no longer registers it under
25
+ * {@link RootSurfaceSchemaLike.commands}. To stay robust against callers that
26
+ * still place the default in the command list (e.g. hand-built test schemas),
27
+ * {@link resolveRootSurface} always derives {@link RootSurface.visibleSubcommands}
28
+ * by excluding the default command from the visible command list.
29
+ *
23
30
  * @internal
24
31
  */
25
32
  interface RootSurface {
33
+ /** All visible top-level commands as declared in `schema.commands`. */
26
34
  readonly visibleCommands: readonly CommandSchema[];
35
+ /** Visible real subcommands — `visibleCommands` minus the default command. */
36
+ readonly visibleSubcommands: readonly CommandSchema[];
37
+ /** The visible default command, or `undefined` when none exists or it is hidden. */
27
38
  readonly visibleDefaultCommand: CommandSchema | undefined;
28
- readonly hasSingleVisibleDefault: boolean;
29
- readonly hasVisibleSiblingCommands: boolean;
39
+ /** Whether a visible default command exists. */
40
+ readonly hasVisibleDefault: boolean;
41
+ /** Whether any visible real subcommands exist (the default does not count). */
42
+ readonly hasVisibleSubcommands: boolean;
30
43
  }
31
44
  /**
32
45
  * Resolve the visible shape of the CLI root.
33
46
  *
34
47
  * Hidden commands are excluded from the visible command list. Hidden
35
48
  * default commands remain executable, but are not surfaced through
36
- * help or completions.
49
+ * help or completions. The default command is reported separately from the
50
+ * real subcommands so help and completion can render it as the root surface
51
+ * instead of echoing it as a pseudo-subcommand.
37
52
  *
38
53
  * @internal
39
54
  */
@@ -1 +1,27 @@
1
- function e(e){let t=e.commands.map(e=>e.schema).filter(e=>!e.hidden),n=e.defaultCommand?.schema,r=n!==void 0&&!n.hidden?n:void 0;return{visibleCommands:t,visibleDefaultCommand:r,hasSingleVisibleDefault:r!==void 0&&t.length===1&&t[0]?.name===r.name,hasVisibleSiblingCommands:r!==void 0&&t.some(e=>e.name!==r.name)}}export{e as resolveRootSurface};
1
+ //#region src/core/cli/root-surface.ts
2
+ /**
3
+ * Resolve the visible shape of the CLI root.
4
+ *
5
+ * Hidden commands are excluded from the visible command list. Hidden
6
+ * default commands remain executable, but are not surfaced through
7
+ * help or completions. The default command is reported separately from the
8
+ * real subcommands so help and completion can render it as the root surface
9
+ * instead of echoing it as a pseudo-subcommand.
10
+ *
11
+ * @internal
12
+ */
13
+ function resolveRootSurface(schema) {
14
+ const visibleCommands = schema.commands.map((command) => command.schema).filter((command) => !command.hidden);
15
+ const rawDefaultCommand = schema.defaultCommand?.schema;
16
+ const visibleDefaultCommand = rawDefaultCommand !== void 0 && !rawDefaultCommand.hidden ? rawDefaultCommand : void 0;
17
+ const visibleSubcommands = visibleDefaultCommand !== void 0 ? visibleCommands.filter((command) => command.name !== visibleDefaultCommand.name) : visibleCommands;
18
+ return {
19
+ visibleCommands,
20
+ visibleSubcommands,
21
+ visibleDefaultCommand,
22
+ hasVisibleDefault: visibleDefaultCommand !== void 0,
23
+ hasVisibleSubcommands: visibleSubcommands.length > 0
24
+ };
25
+ }
26
+ //#endregion
27
+ export { resolveRootSurface };
@@ -6,6 +6,8 @@ import { CommandSchema, ErasedCommand } from "../schema/command.mjs";
6
6
  import { RuntimeAdapter } from "../../runtime/adapter.mjs";
7
7
  import { PackageJsonData } from "../config/package-json.mjs";
8
8
  import { HelpLinks } from "./help-links.mjs";
9
+ import { CompletionOptions } from "../completion/shells/shared.mjs";
10
+ import { Shell } from "../completion/index.mjs";
9
11
  import { FormatLoader } from "../config/index.mjs";
10
12
 
11
13
  //#region src/core/cli/runtime-preflight.d.ts
@@ -62,8 +64,21 @@ interface RuntimePreflightSchemaLike {
62
64
  readonly packageJsonSettings: RuntimeManifestSettings | undefined;
63
65
  /** Root-help header link targets; `undefined` fields may be derived from package.json. */
64
66
  readonly helpLinks: HelpLinks | undefined;
65
- /** Whether `.completions()` registered the built-in completions command. */
67
+ /** Whether `.completions()` registered the built-in completions command/flag. */
66
68
  readonly hasBuiltInCompletions: boolean;
69
+ /** Eager `--completions <shell>` flag config; `undefined` disables interception. */
70
+ readonly completionsFlag: {
71
+ readonly shells: readonly Shell[];
72
+ readonly options: CompletionOptions | undefined;
73
+ } | undefined;
74
+ /** Consumer-configured root-help defaults. */
75
+ readonly helpConfig: {
76
+ readonly inlineDefault?: boolean;
77
+ readonly showDefaultInCommands?: boolean;
78
+ readonly footer?: boolean;
79
+ readonly width?: number;
80
+ readonly hyperlinks?: boolean;
81
+ } | undefined;
67
82
  /** Plugins forwarded into the execution pipeline. */
68
83
  readonly plugins: readonly CLIPlugin[];
69
84
  }
@@ -1 +1,168 @@
1
- import{CLIError as e,ParseError as t}from"../errors/index.mjs";import{parse as n}from"../parse/index.mjs";import{createTerminalPrompter as r}from"../prompt/index.mjs";import{discoverManifest as i,inferCliName as a}from"../config/package-json.mjs";import{deriveHelpLinks as o}from"./help-links.mjs";import{planInvocation as s}from"./planner.mjs";import{discoverConfig as c}from"../config/index.mjs";const l={jsonMode:!1,isTTY:!1,verbosity:`normal`};function u(e){let t=[],n;for(let r=0;r<e.length;r+=1){let i=e[r];if(i!==void 0){if(i===`--`){t.push(...e.slice(r));break}if(n===void 0&&i.startsWith(`--config=`)){let e=i.slice(9);if(e.length>0){n=e;continue}t.push(i);continue}if(n===void 0&&i===`--config`){let a=e[r+1];if(a!==void 0&&!a.startsWith(`-`)&&a!==`--`){n=a,r+=1;continue}t.push(i);continue}t.push(i)}}return{configPath:n,filteredArgv:t}}function d(e,r){if(r.includes(`--help`)||r.includes(`-h`))return!1;try{let t=n(e,r);return e.args.some(({name:e,schema:n})=>{let r=t.args[e];return n.stdinMode&&(r===void 0||r===`-`)})}catch(e){if(e instanceof t)return!1;throw e}}function f(e,t){let n=s({schema:e,argv:t,help:{binName:e.name},output:l});switch(n.kind){case`match`:return d(n.plan.mergedSchema,n.plan.argv);case`dispatch-error`:case`needs-subcommand`:case`root-help`:case`root-version`:return!1}}function p(e,t){if(!e.hasBuiltInCompletions)return!1;let n=s({schema:e,argv:t,help:{binName:e.name},output:l});return n.kind===`match`&&n.plan.command.schema.name===`completions`}async function m(e,t,n,r){let s=e.packageJsonSettings,c=s!==void 0&&!r?await(async()=>{let n=s.data??await i(t,{...s.from===void 0?{}:{startDir:s.from},files:s.files});if(n===null)return e;let r=s.inferName?a(n,{stripScope:s.stripScope}):void 0;return{...e,...e.version===void 0&&n.version!==void 0?{version:n.version}:{},...e.description===void 0&&n.description!==void 0?{description:n.description}:{},...r===void 0?{}:{name:r},helpLinks:o(e.helpLinks,n,e.version??n.version)}})():e;return n===void 0?c:{...c,name:n}}async function h(t,n,r,i,a){if(t.configSettings===void 0||i||a!==void 0)return a;try{let e=await c(t.configSettings.appName,n,{...r===void 0?{}:{configPath:r},...t.configSettings.loaders===void 0?{}:{loaders:t.configSettings.loaders}});return e.found?e.data:void 0}catch(t){if(t instanceof e)return t;throw t}}async function g(t){let n=t.adapter.argv.slice(2),{configPath:i,filteredArgv:a}=t.schema.configSettings===void 0?{configPath:void 0,filteredArgv:n}:u(n),o=a.includes(`--json`)||t.options?.jsonMode===!0,s=p(t.schema,a),c=await m(t.schema,t.adapter,t.inheritedName,s),l=await h(c,t.adapter,i,s,t.options?.config);if(l instanceof e)return{kind:`config-error`,error:l,jsonMode:o};let d=t.options?.prompter===void 0&&t.adapter.stdinIsTTY?r(t.adapter.stdin,t.adapter.stderr):void 0,g=t.options?.stdinData===void 0&&f(c,a)?await t.adapter.readStdin():t.options?.stdinData;return{kind:`ready`,schema:c,filteredArgv:a,inputs:{env:t.options?.env??t.adapter.env,isTTY:t.options?.isTTY??t.adapter.isTTY,jsonMode:o,verbosity:t.options?.verbosity??`normal`,...g===void 0?{}:{stdinData:g},...t.options?.prompter===void 0?d===void 0?{}:{prompter:d}:{prompter:t.options.prompter},...l===void 0?{}:{config:l}}}}export{g as prepareRuntimePreflight};
1
+ import { CLIError, ParseError } from "../errors/index.mjs";
2
+ import { parse } from "../parse/index.mjs";
3
+ import { createTerminalPrompter } from "../prompt/index.mjs";
4
+ import { discoverManifest, inferCliName } from "../config/package-json.mjs";
5
+ import { deriveHelpLinks } from "./help-links.mjs";
6
+ import { planInvocation } from "./planner.mjs";
7
+ import { discoverConfig } from "../config/index.mjs";
8
+ //#region src/core/cli/runtime-preflight.ts
9
+ const PRECHECK_OUTPUT = {
10
+ jsonMode: false,
11
+ isTTY: false,
12
+ verbosity: "normal"
13
+ };
14
+ /** Extract and strip valid runtime `--config` forms from argv, returning path + filtered tokens. @internal */
15
+ function extractConfigFlag(argv) {
16
+ const filteredArgv = [];
17
+ let configPath;
18
+ for (let i = 0; i < argv.length; i += 1) {
19
+ const arg = argv[i];
20
+ if (arg === void 0) continue;
21
+ if (arg === "--") {
22
+ filteredArgv.push(...argv.slice(i));
23
+ break;
24
+ }
25
+ if (configPath === void 0 && arg.startsWith("--config=")) {
26
+ const value = arg.slice(9);
27
+ if (value.length > 0) {
28
+ configPath = value;
29
+ continue;
30
+ }
31
+ filteredArgv.push(arg);
32
+ continue;
33
+ }
34
+ if (configPath === void 0 && arg === "--config") {
35
+ const nextArg = argv[i + 1];
36
+ if (nextArg !== void 0 && !nextArg.startsWith("-") && nextArg !== "--") {
37
+ configPath = nextArg;
38
+ i += 1;
39
+ continue;
40
+ }
41
+ filteredArgv.push(arg);
42
+ continue;
43
+ }
44
+ filteredArgv.push(arg);
45
+ }
46
+ return {
47
+ configPath,
48
+ filteredArgv
49
+ };
50
+ }
51
+ /** Check whether a single command's args declare stdin-mode and argv leaves them unresolved. @internal */
52
+ function commandInvocationNeedsStdin(schema, argv) {
53
+ if (argv.includes("--help") || argv.includes("-h")) return false;
54
+ try {
55
+ const parsed = parse(schema, argv);
56
+ return schema.args.some(({ name, schema: argSchema }) => {
57
+ const parsedValue = parsed.args[name];
58
+ return argSchema.stdinMode && (parsedValue === void 0 || parsedValue === "-");
59
+ });
60
+ } catch (error) {
61
+ if (error instanceof ParseError) return false;
62
+ throw error;
63
+ }
64
+ }
65
+ /** Plan the invocation and check whether the matched command needs stdin data. @internal */
66
+ function invocationNeedsStdin(schema, argv) {
67
+ const plan = planInvocation({
68
+ schema,
69
+ argv,
70
+ help: { binName: schema.name },
71
+ output: PRECHECK_OUTPUT
72
+ });
73
+ switch (plan.kind) {
74
+ case "match": return commandInvocationNeedsStdin(plan.plan.mergedSchema, plan.plan.argv);
75
+ case "dispatch-error":
76
+ case "needs-subcommand":
77
+ case "root-help":
78
+ case "root-version":
79
+ case "root-completions": return false;
80
+ }
81
+ }
82
+ function isCompletionsInvocation(schema, argv) {
83
+ if (!schema.hasBuiltInCompletions) return false;
84
+ const plan = planInvocation({
85
+ schema,
86
+ argv,
87
+ help: { binName: schema.name },
88
+ output: PRECHECK_OUTPUT
89
+ });
90
+ return plan.kind === "match" && plan.plan.command.schema.name === "completions";
91
+ }
92
+ async function applyPackageJsonDiscovery(schema, adapter, inheritedName, isCompletions) {
93
+ const packageJsonSettings = schema.packageJsonSettings;
94
+ const packageSchema = packageJsonSettings !== void 0 && !isCompletions ? await (async () => {
95
+ const pkg = packageJsonSettings.data ?? await discoverManifest(adapter, {
96
+ ...packageJsonSettings.from !== void 0 ? { startDir: packageJsonSettings.from } : {},
97
+ files: packageJsonSettings.files
98
+ });
99
+ if (pkg === null) return schema;
100
+ const inferredName = packageJsonSettings.inferName ? inferCliName(pkg, { stripScope: packageJsonSettings.stripScope }) : void 0;
101
+ return {
102
+ ...schema,
103
+ ...schema.version === void 0 && pkg.version !== void 0 ? { version: pkg.version } : {},
104
+ ...schema.description === void 0 && pkg.description !== void 0 ? { description: pkg.description } : {},
105
+ ...inferredName !== void 0 ? { name: inferredName } : {},
106
+ helpLinks: deriveHelpLinks(schema.helpLinks, pkg, schema.version ?? pkg.version)
107
+ };
108
+ })() : schema;
109
+ return inheritedName !== void 0 ? {
110
+ ...packageSchema,
111
+ name: inheritedName
112
+ } : packageSchema;
113
+ }
114
+ async function loadRuntimeConfig(schema, adapter, configPath, isCompletions, existingConfig) {
115
+ if (schema.configSettings === void 0 || isCompletions || existingConfig !== void 0) return existingConfig;
116
+ try {
117
+ const result = await discoverConfig(schema.configSettings.appName, adapter, {
118
+ ...configPath !== void 0 ? { configPath } : {},
119
+ ...schema.configSettings.loaders !== void 0 ? { loaders: schema.configSettings.loaders } : {}
120
+ });
121
+ return result.found ? result.data : void 0;
122
+ } catch (error) {
123
+ if (error instanceof CLIError) return error;
124
+ throw error;
125
+ }
126
+ }
127
+ /**
128
+ * Run all adapter-driven sourcing work before command execution.
129
+ *
130
+ * Discovers config files, reads package.json metadata, detects stdin needs,
131
+ * wires up the prompt engine, and resolves output policy overrides into a
132
+ * single {@linkcode RuntimePreflightResult}.
133
+ * @internal
134
+ */
135
+ async function prepareRuntimePreflight(options) {
136
+ const rawArgv = options.adapter.argv.slice(2);
137
+ const { configPath, filteredArgv } = options.schema.configSettings !== void 0 ? extractConfigFlag(rawArgv) : {
138
+ configPath: void 0,
139
+ filteredArgv: rawArgv
140
+ };
141
+ const jsonMode = filteredArgv.includes("--json") || options.options?.jsonMode === true;
142
+ const isCompletions = isCompletionsInvocation(options.schema, filteredArgv);
143
+ const schema = await applyPackageJsonDiscovery(options.schema, options.adapter, options.inheritedName, isCompletions);
144
+ const loadedConfig = await loadRuntimeConfig(schema, options.adapter, configPath, isCompletions, options.options?.config);
145
+ if (loadedConfig instanceof CLIError) return {
146
+ kind: "config-error",
147
+ error: loadedConfig,
148
+ jsonMode
149
+ };
150
+ const autoPrompter = options.options?.prompter === void 0 && options.adapter.stdinIsTTY ? createTerminalPrompter(options.adapter.stdin, options.adapter.stderr) : void 0;
151
+ const stdinData = options.options?.stdinData === void 0 && invocationNeedsStdin(schema, filteredArgv) ? await options.adapter.readStdin() : options.options?.stdinData;
152
+ return {
153
+ kind: "ready",
154
+ schema,
155
+ filteredArgv,
156
+ inputs: {
157
+ env: options.options?.env ?? options.adapter.env,
158
+ isTTY: options.options?.isTTY ?? options.adapter.isTTY,
159
+ jsonMode,
160
+ verbosity: options.options?.verbosity ?? "normal",
161
+ ...stdinData !== void 0 ? { stdinData } : {},
162
+ ...options.options?.prompter !== void 0 ? { prompter: options.options.prompter } : autoPrompter !== void 0 ? { prompter: autoPrompter } : {},
163
+ ...loadedConfig !== void 0 ? { config: loadedConfig } : {}
164
+ }
165
+ };
166
+ }
167
+ //#endregion
168
+ export { prepareRuntimePreflight };
@@ -22,6 +22,37 @@ type Shell = 'bash' | 'zsh' | 'fish' | 'powershell';
22
22
  * @see {@link Shell} for the union type matching these entries.
23
23
  */
24
24
  declare const SHELLS: Readonly<readonly ['bash', 'zsh', 'fish', 'powershell']>;
25
+ /**
26
+ * Normalize a raw shell token — a bare name (`zsh`), a `$SHELL` path
27
+ * (`/bin/zsh`), or a Windows executable (`…\pwsh.exe`) — to a supported
28
+ * {@link Shell}, or `undefined` when it does not map to one.
29
+ *
30
+ * Mirrors the matching used by the `completions` subcommand so the subcommand
31
+ * and the eager `--completions <shell>` flag accept exactly the same inputs.
32
+ *
33
+ * @param raw - User-supplied shell token or interpreter path.
34
+ * @returns The resolved {@link Shell}, or `undefined` if unrecognized.
35
+ */
36
+ declare function normalizeShell(raw: string): Shell | undefined;
37
+ /**
38
+ * Auto-detect the current shell from environment variables.
39
+ *
40
+ * Resolution order:
41
+ * 1. `$SHELL` parsed as an interpreter path (`/bin/zsh` → `zsh`). It wins when
42
+ * it names a shell we support — a pwsh session launched from bash inherits
43
+ * `SHELL=/bin/bash`, and the login shell the user opted into should be
44
+ * honored over the fallback.
45
+ * 2. Otherwise, the presence of `$PSModulePath` signals PowerShell. PowerShell
46
+ * never sets `$SHELL` on any platform but always exports `PSModulePath` for
47
+ * module discovery, so it is the reliable pwsh signal.
48
+ *
49
+ * Returns `undefined` when no signal resolves, leaving the caller to ask the
50
+ * user for an explicit shell.
51
+ *
52
+ * @param env - Environment record (e.g. `process.env` or an adapter's env).
53
+ * @returns The detected {@link Shell}, or `undefined`.
54
+ */
55
+ declare function detectShell(env: Readonly<Record<string, string | undefined>>): Shell | undefined;
25
56
  /**
26
57
  * Generate a completion script for the given shell.
27
58
  *
@@ -43,4 +74,4 @@ declare const SHELLS: Readonly<readonly ['bash', 'zsh', 'fish', 'powershell']>;
43
74
  */
44
75
  declare function generateCompletion(schema: CLISchema, shell: Shell, options?: CompletionOptions): string;
45
76
  //#endregion
46
- export { type CompletionOptions, SHELLS, type Shell, generateBashCompletion, generateCompletion, generateFishCompletion, generatePowerShellCompletion, generateZshCompletion };
77
+ export { type CompletionOptions, SHELLS, type Shell, detectShell, generateBashCompletion, generateCompletion, generateFishCompletion, generatePowerShellCompletion, generateZshCompletion, normalizeShell };
@@ -1 +1,90 @@
1
- import{generateBashCompletion as e}from"./shells/bash.mjs";import{generateFishCompletion as t}from"./shells/fish.mjs";import{generatePowerShellCompletion as n}from"./shells/powershell.mjs";import{generateZshCompletion as r}from"./shells/zsh.mjs";const i=Object.freeze([`bash`,`zsh`,`fish`,`powershell`]);function a(i,a,o){switch(a){case`bash`:return e(i,o);case`zsh`:return r(i,o);case`fish`:return t(i,o);case`powershell`:return n(i,o)}}export{i as SHELLS,a as generateCompletion};
1
+ import { generateBashCompletion } from "./shells/bash.mjs";
2
+ import { generateFishCompletion } from "./shells/fish.mjs";
3
+ import { generatePowerShellCompletion } from "./shells/powershell.mjs";
4
+ import { generateZshCompletion } from "./shells/zsh.mjs";
5
+ //#region src/core/completion/index.ts
6
+ /**
7
+ * Implemented shell values as a frozen readonly non-empty tuple.
8
+ *
9
+ * Use this tuple for user-facing validation and shell selection UIs.
10
+ * It intentionally matches the shipped {@link Shell} union exactly so docs,
11
+ * help output, and completion generation advertise the same support surface.
12
+ *
13
+ * @see {@link Shell} for the union type matching these entries.
14
+ */
15
+ const SHELLS = Object.freeze([
16
+ "bash",
17
+ "zsh",
18
+ "fish",
19
+ "powershell"
20
+ ]);
21
+ /**
22
+ * Normalize a raw shell token — a bare name (`zsh`), a `$SHELL` path
23
+ * (`/bin/zsh`), or a Windows executable (`…\pwsh.exe`) — to a supported
24
+ * {@link Shell}, or `undefined` when it does not map to one.
25
+ *
26
+ * Mirrors the matching used by the `completions` subcommand so the subcommand
27
+ * and the eager `--completions <shell>` flag accept exactly the same inputs.
28
+ *
29
+ * @param raw - User-supplied shell token or interpreter path.
30
+ * @returns The resolved {@link Shell}, or `undefined` if unrecognized.
31
+ */
32
+ function normalizeShell(raw) {
33
+ const segments = raw.split(/[\\/]/);
34
+ const name = (segments[segments.length - 1] ?? raw).replace(/\.(?:exe|cmd|bat)$/i, "");
35
+ if (name === "pwsh") return "powershell";
36
+ return SHELLS.includes(name) ? name : void 0;
37
+ }
38
+ /**
39
+ * Auto-detect the current shell from environment variables.
40
+ *
41
+ * Resolution order:
42
+ * 1. `$SHELL` parsed as an interpreter path (`/bin/zsh` → `zsh`). It wins when
43
+ * it names a shell we support — a pwsh session launched from bash inherits
44
+ * `SHELL=/bin/bash`, and the login shell the user opted into should be
45
+ * honored over the fallback.
46
+ * 2. Otherwise, the presence of `$PSModulePath` signals PowerShell. PowerShell
47
+ * never sets `$SHELL` on any platform but always exports `PSModulePath` for
48
+ * module discovery, so it is the reliable pwsh signal.
49
+ *
50
+ * Returns `undefined` when no signal resolves, leaving the caller to ask the
51
+ * user for an explicit shell.
52
+ *
53
+ * @param env - Environment record (e.g. `process.env` or an adapter's env).
54
+ * @returns The detected {@link Shell}, or `undefined`.
55
+ */
56
+ function detectShell(env) {
57
+ const shellVar = env.SHELL;
58
+ const fromShell = shellVar !== void 0 && shellVar !== "" ? normalizeShell(shellVar) : void 0;
59
+ if (fromShell !== void 0) return fromShell;
60
+ if (env.PSModulePath !== void 0) return "powershell";
61
+ }
62
+ /**
63
+ * Generate a completion script for the given shell.
64
+ *
65
+ * This is the primary completion entrypoint for most consumers. Pass a CLI
66
+ * schema and target shell, then write the returned script to a file or source
67
+ * it directly from the command line.
68
+ *
69
+ * @param schema - The CLI schema describing commands, flags, and args.
70
+ * @param shell - Target shell.
71
+ * @param options - Optional generator configuration such as function naming
72
+ * and root default-command completion behavior.
73
+ * @returns A complete shell completion script as a string.
74
+ *
75
+ * @example
76
+ * ```ts
77
+ * const script = generateCompletion(app.schema, 'bash');
78
+ * // e.g. source <(mycli completions bash)
79
+ * ```
80
+ */
81
+ function generateCompletion(schema, shell, options) {
82
+ switch (shell) {
83
+ case "bash": return generateBashCompletion(schema, options);
84
+ case "zsh": return generateZshCompletion(schema, options);
85
+ case "fish": return generateFishCompletion(schema, options);
86
+ case "powershell": return generatePowerShellCompletion(schema, options);
87
+ }
88
+ }
89
+ //#endregion
90
+ export { SHELLS, detectShell, generateCompletion, normalizeShell };