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

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 +217 -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,4 +1,226 @@
1
- import{resolveRootSurface as e}from"./root-surface.mjs";import{osc8 as t,padEnd as n,wrapText as r}from"../help/ansi.mjs";import{formatFlagEntriesBlock as i,formatHelpSections as a}from"../help/index.mjs";import{command as o}from"../schema/command.mjs";function s(t,n){let r=n?.width??80,i=n?.binName??t.name,o=n?.hyperlinks===!0,s=n?.inlineDefault??!0,l=n?.showDefaultInCommands??!1,m=e(t),h=m.visibleDefaultCommand,g=!m.hasVisibleSubcommands&&t.completionsFlag===void 0,_=s||g?h:void 0,v=c(t,_),y=v!==void 0,b=[u(t,o)];t.description!==void 0&&b.push(t.description);let x=m.hasVisibleSubcommands?h===void 0?`<command>`:`[command]`:``,S=x.length>0?`Usage: ${i} ${x} [options]`:`Usage: ${i} [options]`,C=[];y&&v!==void 0&&(C=[...a(v,{...n,binName:i,isDefaultHelp:!0})]);let w=C.shift();y&&w!==void 0&&_!==void 0?b.push(m.hasVisibleSubcommands?p(S,w):w):b.push(S);let T=l&&h!==void 0?[...m.visibleSubcommands,h]:m.visibleSubcommands;T.length>0&&b.push(d(T,l?h?.name:void 0,r)),y&&v!==void 0&&(v.description!==void 0&&v.description===t.description&&C[0]===v.description&&C.shift(),b.push(...C));let E=f(t,r);if(E.length>0&&b.push(E),n?.footer??m.hasVisibleSubcommands){let e=m.hasVisibleSubcommands?h===void 0?` <command>`:` [command]`:``;b.push(`Run '${i}${e} --help' for more information.`)}return`${b.join(`
2
-
3
- `)}\n`}function c(e,t){if(e.completionsFlag===void 0)return t;let n=t??o(e.name).schema;return{...n,flags:{completions:l(e.completionsFlag.shells),...n.flags}}}function l(e){return{kind:`enum`,presence:`optional`,defaultValue:void 0,aliases:[],envVar:void 0,configPath:void 0,description:`Print a shell completion script and exit`,enumValues:e,elementSchema:void 0,numberConstraints:void 0,prompt:void 0,parseFn:void 0,deprecated:void 0,propagate:!1}}function u(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 d(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(`
4
- `)}function f(e,t){let n=[{left:`-h, --help`,description:`Show this help message and exit`}];return e.version!==void 0&&n.push({left:`-V, --version`,description:`Print the version number and exit`}),n.push({left:`--json`,description:`Emit machine-readable JSON output`}),e.configSettings!==void 0&&n.push({left:`--config <path>`,description:`Load configuration from the given file`}),i(`Global options:`,n,t)}function p(e,t){let n=t.startsWith(`Usage: `)?t.slice(7):t;return`${e}\n${` `.repeat(7)}${n}`}export{s as formatRootHelp};
1
+ import { command } from "../schema/command.mjs";
2
+ import { resolveRootSurface } from "./root-surface.mjs";
3
+ import { osc8, padEnd, wrapText } from "../help/ansi.mjs";
4
+ import { resolveHelpTheme } from "../help/theme.mjs";
5
+ import { formatFlagEntriesBlock, formatHelpSections } from "../help/index.mjs";
6
+ //#region src/core/cli/root-help.ts
7
+ /**
8
+ * Root-level help formatter for the CLI program.
9
+ *
10
+ * Separate from `help/formatHelp()` which renders per-command help —
11
+ * different concerns, different format.
12
+ *
13
+ * @module dreamcli/core/cli/root-help
14
+ * @internal
15
+ */
16
+ /**
17
+ * Generate root-level help text for the CLI program.
18
+ *
19
+ * Shows program name, version, description, usage line, and available
20
+ * subcommands. The default command is the CLI's root *surface*: its arguments
21
+ * and flags are rendered inline (unless `inlineDefault` is `false`) and it is
22
+ * omitted from the `Commands:` list unless `showDefaultInCommands` is set. When
23
+ * `.completions({ as: 'flag' })` is active, the eager `--completions <shell>`
24
+ * flag is advertised in the `Flags:` section.
25
+ *
26
+ * @internal
27
+ */
28
+ function formatRootHelp(schema, options) {
29
+ const width = options?.width ?? 80;
30
+ const binName = options?.binName ?? schema.name;
31
+ const hyperlinks = options?.hyperlinks === true;
32
+ const inlineDefault = options?.inlineDefault ?? true;
33
+ const showDefaultInCommands = options?.showDefaultInCommands ?? false;
34
+ const theme = resolveHelpTheme(options?.colors, options?.theme);
35
+ const surface = resolveRootSurface(schema);
36
+ const defaultCommand = surface.visibleDefaultCommand;
37
+ const defaultIsSoleSurface = !surface.hasVisibleSubcommands && schema.completionsFlag === void 0;
38
+ const inlineDefaultCommand = inlineDefault || defaultIsSoleSurface ? defaultCommand : void 0;
39
+ const surfaceCommand = resolveSurfaceCommand(schema, inlineDefaultCommand);
40
+ const inline = surfaceCommand !== void 0;
41
+ const sections = [formatHeader(schema, hyperlinks, theme)];
42
+ if (schema.description !== void 0) sections.push(schema.description);
43
+ const placeholder = surface.hasVisibleSubcommands ? defaultCommand !== void 0 ? "[command]" : "<command>" : "";
44
+ const usageTitle = theme.sectionTitle("Usage:");
45
+ const rootUsage = placeholder.length > 0 ? `${usageTitle} ${theme.usageBin(binName)} ${theme.placeholder(placeholder)} ${theme.placeholder("[options]")}` : `${usageTitle} ${theme.usageBin(binName)} ${theme.placeholder("[options]")}`;
46
+ let surfaceSections = [];
47
+ if (inline && surfaceCommand !== void 0) surfaceSections = [...formatHelpSections(surfaceCommand, {
48
+ ...options,
49
+ binName,
50
+ isDefaultHelp: true
51
+ })];
52
+ const surfaceUsage = surfaceSections.shift();
53
+ if (inline && surfaceUsage !== void 0 && inlineDefaultCommand !== void 0) sections.push(surface.hasVisibleSubcommands ? mergeUsageSections(rootUsage, surfaceUsage, usageTitle) : surfaceUsage);
54
+ else sections.push(rootUsage);
55
+ const listDefaultInCommands = defaultCommand !== void 0 && (surface.defaultRouted || showDefaultInCommands);
56
+ const listedCommands = listDefaultInCommands ? [...surface.visibleSubcommands, defaultCommand] : surface.visibleSubcommands;
57
+ if (listedCommands.length > 0) sections.push(formatRootCommandsSection(listedCommands, listDefaultInCommands ? defaultCommand?.name : void 0, width, theme));
58
+ if (inline && surfaceCommand !== void 0) {
59
+ if (surfaceCommand.description !== void 0 && surfaceCommand.description === schema.description && surfaceSections[0] === surfaceCommand.description) surfaceSections.shift();
60
+ sections.push(...surfaceSections);
61
+ }
62
+ const globalOptions = formatGlobalOptionsSection(schema, width, theme);
63
+ if (globalOptions.length > 0) sections.push(globalOptions);
64
+ if (options?.footer ?? surface.hasVisibleSubcommands) {
65
+ const footerPlaceholder = surface.hasVisibleSubcommands ? defaultCommand !== void 0 ? " [command]" : " <command>" : "";
66
+ sections.push(`Run '${binName}${footerPlaceholder} --help' for more information.`);
67
+ }
68
+ return `${sections.join("\n\n")}\n`;
69
+ }
70
+ /**
71
+ * Resolve the command rendered inline as the CLI's root surface.
72
+ *
73
+ * Returns the default command, augmented with the eager `--completions <shell>`
74
+ * flag when `.completions({ as: 'flag' })` is active. When there is no default
75
+ * command but the completions flag is configured, a synthetic surface carrying
76
+ * just that flag is returned so the flag is still advertised. Returns
77
+ * `undefined` when there is nothing to render inline.
78
+ *
79
+ * @internal
80
+ */
81
+ function resolveSurfaceCommand(schema, defaultCommand) {
82
+ if (schema.completionsFlag === void 0) return defaultCommand;
83
+ const base = defaultCommand ?? command(schema.name).schema;
84
+ return {
85
+ ...base,
86
+ flags: {
87
+ completions: completionsFlagSchema(schema.completionsFlag.shells),
88
+ ...base.flags
89
+ }
90
+ };
91
+ }
92
+ /**
93
+ * Build the synthetic, render-only flag schema for the eager `--completions`
94
+ * flag. It never participates in parsing (the planner intercepts the flag
95
+ * directly); it exists purely so root help can list
96
+ * `--completions <bash|zsh|…>` in its `Flags:` section.
97
+ *
98
+ * @internal
99
+ */
100
+ function completionsFlagSchema(shells) {
101
+ return {
102
+ kind: "enum",
103
+ presence: "optional",
104
+ defaultValue: void 0,
105
+ aliases: [],
106
+ envVar: void 0,
107
+ configPath: void 0,
108
+ description: "Print a shell completion script and exit",
109
+ enumValues: shells,
110
+ elementSchema: void 0,
111
+ separator: void 0,
112
+ unique: false,
113
+ numberConstraints: void 0,
114
+ stringConstraints: void 0,
115
+ pathChecks: void 0,
116
+ valueHint: void 0,
117
+ prompt: void 0,
118
+ parseFn: void 0,
119
+ deprecated: void 0,
120
+ propagate: false,
121
+ negation: void 0,
122
+ duplicates: "last"
123
+ };
124
+ }
125
+ /**
126
+ * Render the header line (`name vX.Y.Z`).
127
+ *
128
+ * When `hyperlinks` is enabled and the schema carries link URLs (via
129
+ * `CLIBuilder.links()`, possibly derived from package.json metadata), the
130
+ * name and version are wrapped in OSC 8 hyperlinks. The header is the only
131
+ * place links are emitted — usage lines, hints, and the commands table stay
132
+ * plain.
133
+ *
134
+ * @param schema - The CLI schema.
135
+ * @param hyperlinks - Whether OSC 8 hyperlinks may be emitted.
136
+ * @param theme - Theme applied to the name and version (inside any hyperlink).
137
+ * @returns The header line.
138
+ * @internal
139
+ */
140
+ function formatHeader(schema, hyperlinks, theme) {
141
+ const links = hyperlinks ? schema.helpLinks : void 0;
142
+ const styledName = theme.headerName(schema.name);
143
+ const name = links?.name !== void 0 ? osc8(links.name, styledName) : styledName;
144
+ if (schema.version === void 0) return name;
145
+ const version = theme.headerVersion(`v${schema.version}`);
146
+ return `${name} ${links?.version !== void 0 ? osc8(links.version, version) : version}`;
147
+ }
148
+ /**
149
+ * Format the "Commands:" section with aligned names and descriptions.
150
+ *
151
+ * @param visibleCommands - Non-hidden top-level commands.
152
+ * @param defaultName - Name of the default command (appends " (default)" tag).
153
+ * @param width - Terminal width for description wrapping.
154
+ * @param theme - Theme applied to the title, command names, and default tag.
155
+ * @returns Formatted commands block.
156
+ * @internal
157
+ */
158
+ function formatRootCommandsSection(visibleCommands, defaultName, width, theme) {
159
+ const lines = [theme.sectionTitle("Commands:")];
160
+ const GAP = 2;
161
+ const DEFAULT_TAG = " (default)";
162
+ let maxNameLen = 0;
163
+ for (const cmd of visibleCommands) {
164
+ const tagLen = cmd.name === defaultName ? 10 : 0;
165
+ const nameLen = cmd.name.length + tagLen;
166
+ if (nameLen > maxNameLen) maxNameLen = nameLen;
167
+ }
168
+ const descCol = 2 + maxNameLen + GAP;
169
+ for (const cmd of visibleCommands) {
170
+ const padded = padEnd(` ${cmd.name === defaultName ? `${theme.command(cmd.name)}${theme.annotation(DEFAULT_TAG)}` : theme.command(cmd.name)}`, descCol);
171
+ const desc = cmd.description ?? "";
172
+ if (desc.length === 0) lines.push(padded.trimEnd());
173
+ else lines.push(`${padded}${wrapText(desc, width, descCol)}`);
174
+ }
175
+ return lines.join("\n");
176
+ }
177
+ /**
178
+ * Build the `Global options:` section advertising the active built-in flags.
179
+ *
180
+ * `--help, -h` and `--json` are always available; `--version, -V` is shown only
181
+ * when the program declares a version; `--config <path>` only when `.config()`
182
+ * enabled config discovery. The eager `--completions` flag is intentionally
183
+ * omitted — it is advertised via the inline surface when active.
184
+ *
185
+ * @param schema - The CLI schema (read for `version` and `configSettings`).
186
+ * @param width - Terminal width for description wrapping.
187
+ * @param theme - Theme applied to the title and flag forms.
188
+ * @returns Formatted `Global options:` block (always non-empty).
189
+ * @internal
190
+ */
191
+ function formatGlobalOptionsSection(schema, width, theme) {
192
+ const entries = [{
193
+ left: theme.flag("-h, --help"),
194
+ description: "Show this help message and exit"
195
+ }];
196
+ if (schema.version !== void 0) entries.push({
197
+ left: theme.flag("-V, --version"),
198
+ description: "Print the version number and exit"
199
+ });
200
+ entries.push({
201
+ left: theme.flag("--json"),
202
+ description: "Emit machine-readable JSON output"
203
+ });
204
+ if (schema.configSettings !== void 0) entries.push({
205
+ left: `${theme.flag("--config")} ${theme.placeholder("<path>")}`,
206
+ description: "Load configuration from the given file"
207
+ });
208
+ return formatFlagEntriesBlock(theme.sectionTitle("Global options:"), entries, width);
209
+ }
210
+ /**
211
+ * Merge root and default-command usage lines into a single block.
212
+ *
213
+ * @param rootUsage - The root usage line (e.g. `Usage: mycli [command] [options]`).
214
+ * @param commandUsage - The default command's usage line.
215
+ * @param usageTitle - The themed `Usage:` title — byte-identical in both lines
216
+ * within one render, so the styled prefix strips cleanly.
217
+ * @returns Combined usage block with aligned continuation.
218
+ * @internal
219
+ */
220
+ function mergeUsageSections(rootUsage, commandUsage, usageTitle) {
221
+ const usagePrefix = `${usageTitle} `;
222
+ const commandSuffix = commandUsage.startsWith(usagePrefix) ? commandUsage.slice(usagePrefix.length) : commandUsage;
223
+ return `${rootUsage}\n${" ".repeat(7)}${commandSuffix}`;
224
+ }
225
+ //#endregion
226
+ export { formatRootHelp };
@@ -1,5 +1,4 @@
1
1
  import { CommandSchema } from "../schema/command.mjs";
2
-
3
2
  //#region src/core/cli/root-surface.d.ts
4
3
  /**
5
4
  * Structural CLI shape needed for root-surface analysis.
@@ -16,6 +15,12 @@ interface RootSurfaceSchemaLike {
16
15
  readonly defaultCommand: {
17
16
  readonly schema: CommandSchema;
18
17
  } | undefined;
18
+ /**
19
+ * Whether the default command is also exposed as a named route
20
+ * (`.default(cmd, { route: true })`). Optional so hand-built schema-like
21
+ * objects default to the surface-only behavior.
22
+ */
23
+ readonly defaultCommandRouted?: boolean | undefined;
19
24
  }
20
25
  /**
21
26
  * Normalized root shape shared by help and completion logic.
@@ -40,6 +45,12 @@ interface RootSurface {
40
45
  readonly hasVisibleDefault: boolean;
41
46
  /** Whether any visible real subcommands exist (the default does not count). */
42
47
  readonly hasVisibleSubcommands: boolean;
48
+ /**
49
+ * Whether the visible default is also a named route (`.default(cmd, { route:
50
+ * true })`), meaning it should be listed in `Commands:` beside its siblings
51
+ * in addition to being rendered as the root surface.
52
+ */
53
+ readonly defaultRouted: boolean;
43
54
  }
44
55
  /**
45
56
  * Resolve the visible shape of the CLI root.
@@ -1 +1,28 @@
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,i=r===void 0?t:t.filter(e=>e.name!==r.name);return{visibleCommands:t,visibleSubcommands:i,visibleDefaultCommand:r,hasVisibleDefault:r!==void 0,hasVisibleSubcommands:i.length>0}}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
+ defaultRouted: visibleDefaultCommand !== void 0 && schema.defaultCommandRouted === true
25
+ };
26
+ }
27
+ //#endregion
28
+ export { resolveRootSurface };
@@ -1,15 +1,18 @@
1
1
  import { Verbosity } from "../output/contracts.mjs";
2
+ import "../output/index.mjs";
2
3
  import { PromptEngine } from "../prompt/index.mjs";
3
4
  import { CLIPlugin } from "./plugin.mjs";
4
5
  import { CLIError } from "../errors/index.mjs";
6
+ import { HelpThemeFactory } from "../help/theme.mjs";
7
+ import "../help/index.mjs";
5
8
  import { CommandSchema, ErasedCommand } from "../schema/command.mjs";
9
+ import { ParseOptions } from "../parse/index.mjs";
6
10
  import { RuntimeAdapter } from "../../runtime/adapter.mjs";
7
11
  import { PackageJsonData } from "../config/package-json.mjs";
8
12
  import { HelpLinks } from "./help-links.mjs";
9
13
  import { CompletionOptions } from "../completion/shells/shared.mjs";
10
14
  import { Shell } from "../completion/index.mjs";
11
15
  import { FormatLoader } from "../config/index.mjs";
12
-
13
16
  //#region src/core/cli/runtime-preflight.d.ts
14
17
  /** Config discovery settings extracted from CLISchema for preflight use. @internal */
15
18
  interface RuntimeConfigSettings {
@@ -58,6 +61,8 @@ interface RuntimePreflightSchemaLike {
58
61
  readonly commands: readonly ErasedCommand[];
59
62
  /** Fallback command when no subcommand token matches. */
60
63
  readonly defaultCommand: ErasedCommand | undefined;
64
+ /** Whether the default command is also exposed as a named top-level route. */
65
+ readonly defaultCommandRouted: boolean;
61
66
  /** Config file discovery settings; `undefined` disables config loading. */
62
67
  readonly configSettings: RuntimeConfigSettings | undefined;
63
68
  /** Package.json discovery settings; `undefined` disables package.json inference. */
@@ -78,7 +83,10 @@ interface RuntimePreflightSchemaLike {
78
83
  readonly footer?: boolean;
79
84
  readonly width?: number;
80
85
  readonly hyperlinks?: boolean;
86
+ readonly theme?: HelpThemeFactory;
81
87
  } | undefined;
88
+ /** Flag-parsing behavior settings (e.g. case parity). */
89
+ readonly flagSettings: ParseOptions | undefined;
82
90
  /** Plugins forwarded into the execution pipeline. */
83
91
  readonly plugins: readonly CLIPlugin[];
84
92
  }
@@ -104,6 +112,8 @@ interface RuntimePreflightOptions {
104
112
  readonly jsonMode?: boolean;
105
113
  /** TTY detection override; bypasses adapter TTY check. */
106
114
  readonly isTTY?: boolean;
115
+ /** Filesystem probe override for `flag.path()` checks; bypasses the adapter probe. */
116
+ readonly stat?: (path: string) => Promise<'file' | 'directory' | null>;
107
117
  }
108
118
  /**
109
119
  * Fully resolved runtime inputs ready for the execution pipeline.
@@ -127,6 +137,8 @@ interface RuntimeExecutionInputs {
127
137
  readonly prompter?: PromptEngine;
128
138
  /** Loaded config data for the config resolution step. */
129
139
  readonly config?: Readonly<Record<string, unknown>>;
140
+ /** Filesystem probe (from the adapter) for `flag.path()` checks. */
141
+ readonly stat?: (path: string) => Promise<'file' | 'directory' | null>;
130
142
  }
131
143
  /** Preflight succeeded — all runtime inputs are resolved and ready for execution. @internal */
132
144
  interface ReadyRuntimePreflight {
@@ -167,7 +179,7 @@ declare function extractConfigFlag(argv: readonly string[]): {
167
179
  readonly filteredArgv: readonly string[];
168
180
  };
169
181
  /** Check whether a single command's args declare stdin-mode and argv leaves them unresolved. @internal */
170
- declare function commandInvocationNeedsStdin(schema: CommandSchema, argv: readonly string[]): boolean;
182
+ declare function commandInvocationNeedsStdin(schema: CommandSchema, argv: readonly string[], flagSettings?: ParseOptions): boolean;
171
183
  /** Plan the invocation and check whether the matched command needs stdin data. @internal */
172
184
  declare function invocationNeedsStdin(schema: RuntimePreflightSchemaLike, argv: readonly string[]): boolean;
173
185
  /**
@@ -1 +1,169 @@
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`:case`root-completions`: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, flagSettings) {
53
+ if (argv.includes("--help") || argv.includes("-h")) return false;
54
+ try {
55
+ const parsed = parse(schema, argv, flagSettings);
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, schema.flagSettings);
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
+ stat: options.options?.stat ?? options.adapter.stat,
162
+ ...stdinData !== void 0 ? { stdinData } : {},
163
+ ...options.options?.prompter !== void 0 ? { prompter: options.options.prompter } : autoPrompter !== void 0 ? { prompter: autoPrompter } : {},
164
+ ...loadedConfig !== void 0 ? { config: loadedConfig } : {}
165
+ }
166
+ };
167
+ }
168
+ //#endregion
169
+ export { commandInvocationNeedsStdin, extractConfigFlag, invocationNeedsStdin, prepareRuntimePreflight };
@@ -4,7 +4,6 @@ import { generateFishCompletion } from "./shells/fish.mjs";
4
4
  import { generatePowerShellCompletion } from "./shells/powershell.mjs";
5
5
  import { generateZshCompletion } from "./shells/zsh.mjs";
6
6
  import { CLISchema } from "../cli/index.mjs";
7
-
8
7
  //#region src/core/completion/index.d.ts
9
8
  /**
10
9
  * Supported shell targets for completion script generation.
@@ -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(e){let t=e.split(/[\\/]/),n=(t[t.length-1]??e).replace(/\.(?:exe|cmd|bat)$/i,``);return n===`pwsh`?`powershell`:i.includes(n)?n:void 0}function o(e){let t=e.SHELL,n=t!==void 0&&t!==``?a(t):void 0;if(n!==void 0)return n;if(e.PSModulePath!==void 0)return`powershell`}function s(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,o as detectShell,s as generateCompletion,a as normalizeShell};
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, generateBashCompletion, generateCompletion, generateFishCompletion, generatePowerShellCompletion, generateZshCompletion, normalizeShell };
@@ -1,6 +1,5 @@
1
1
  import { CompletionOptions } from "./shared.mjs";
2
2
  import { CLISchema } from "../../cli/index.mjs";
3
-
4
3
  //#region src/core/completion/shells/bash.d.ts
5
4
  /**
6
5
  * Generate a bash completion script for the CLI.