@kjanat/dreamcli 2.4.1 → 3.0.0-rc.1

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 (94) hide show
  1. package/CHANGELOG.md +169 -1
  2. package/README.md +14 -7
  3. package/dist/core/cli/index.d.mts +283 -81
  4. package/dist/core/cli/index.mjs +1 -1
  5. package/dist/core/cli/planner.d.mts +27 -5
  6. package/dist/core/cli/planner.mjs +1 -1
  7. package/dist/core/cli/root-help.d.mts +16 -2
  8. package/dist/core/cli/root-help.mjs +3 -5
  9. package/dist/core/cli/root-surface.d.mts +18 -3
  10. package/dist/core/cli/root-surface.mjs +1 -1
  11. package/dist/core/cli/runtime-preflight.d.mts +31 -5
  12. package/dist/core/cli/runtime-preflight.mjs +1 -1
  13. package/dist/core/completion/index.d.mts +32 -1
  14. package/dist/core/completion/index.mjs +1 -1
  15. package/dist/core/completion/shells/shared.d.mts +10 -0
  16. package/dist/core/completion/shells/shared.mjs +1 -1
  17. package/dist/core/config/index.d.mts +2 -2
  18. package/dist/core/config/package-json.d.mts +93 -20
  19. package/dist/core/config/package-json.mjs +3 -1
  20. package/dist/core/help/index.d.mts +45 -1
  21. package/dist/core/help/index.mjs +6 -6
  22. package/dist/core/json-schema/index.mjs +1 -1
  23. package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
  24. package/dist/core/parse/index.d.mts +15 -1
  25. package/dist/core/parse/index.mjs +1 -1
  26. package/dist/core/prompt/index.d.mts +11 -3
  27. package/dist/core/prompt/index.mjs +3 -3
  28. package/dist/core/resolve/coerce.mjs +1 -1
  29. package/dist/core/resolve/flags.mjs +1 -1
  30. package/dist/core/resolve/property.d.mts +2 -0
  31. package/dist/core/resolve/property.mjs +1 -1
  32. package/dist/core/schema/arg.d.mts +90 -10
  33. package/dist/core/schema/arg.mjs +1 -1
  34. package/dist/core/schema/command.d.mts +3 -1
  35. package/dist/core/schema/flag.d.mts +92 -2
  36. package/dist/core/schema/flag.mjs +1 -1
  37. package/dist/core/schema/index.d.mts +2 -1
  38. package/dist/core/schema/number-constraints.d.mts +96 -0
  39. package/dist/core/schema/number-constraints.mjs +1 -0
  40. package/dist/core/schema/prompt.d.mts +15 -0
  41. package/dist/core/schema/run.d.mts +4 -4
  42. package/dist/core/testkit/index.d.mts +9 -5
  43. package/dist/core/testkit/index.mjs +1 -1
  44. package/dist/index.d.mts +4 -3
  45. package/dist/index.mjs +1 -1
  46. package/dist/runtime/auto.mjs +1 -1
  47. package/dist/runtime/bun.mjs +1 -1
  48. package/dist/runtime/deno.mjs +2 -2
  49. package/dist/runtime/node.mjs +2 -2
  50. package/dist/version.mjs +1 -1
  51. package/examples/basic.ts +5 -1
  52. package/examples/gh/package.json +2 -7
  53. package/examples/pwsh-demo/package.json +1 -7
  54. package/examples/pwsh-demo/src/main.test.ts +1 -4
  55. package/examples/pwsh-demo/src/main.ts +14 -4
  56. package/examples/transport-launcher.ts +85 -0
  57. package/package.json +15 -24
  58. package/src/core/cli/dispatch.ts +7 -1
  59. package/src/core/cli/index.ts +521 -122
  60. package/src/core/cli/planner.ts +192 -23
  61. package/src/core/cli/root-help.ts +195 -105
  62. package/src/core/cli/root-surface.ts +25 -12
  63. package/src/core/cli/runtime-preflight.ts +43 -8
  64. package/src/core/completion/index.ts +50 -0
  65. package/src/core/completion/shells/powershell.ts +2 -2
  66. package/src/core/completion/shells/shared.ts +30 -3
  67. package/src/core/config/index.ts +12 -2
  68. package/src/core/config/package-json.ts +250 -41
  69. package/src/core/execution/index.ts +1 -4
  70. package/src/core/help/index.ts +57 -10
  71. package/src/core/json-schema/index.ts +23 -4
  72. package/src/core/json-schema/meta-descriptions.generated.ts +115 -98
  73. package/src/core/parse/index.ts +62 -1
  74. package/src/core/prompt/index.ts +54 -14
  75. package/src/core/resolve/coerce.ts +73 -5
  76. package/src/core/resolve/flags.ts +14 -0
  77. package/src/core/resolve/property.ts +4 -4
  78. package/src/core/schema/arg.ts +125 -3
  79. package/src/core/schema/command.ts +3 -1
  80. package/src/core/schema/flag.ts +120 -4
  81. package/src/core/schema/index.ts +5 -0
  82. package/src/core/schema/number-constraints.ts +153 -0
  83. package/src/core/schema/prompt.ts +15 -0
  84. package/src/core/schema/run.ts +4 -4
  85. package/src/core/testkit/index.ts +32 -8
  86. package/src/index.ts +8 -0
  87. package/src/runtime/auto.ts +0 -24
  88. package/src/runtime/bun.ts +0 -7
  89. package/src/runtime/deno.ts +0 -2
  90. package/src/runtime/node.ts +0 -11
  91. package/src/runtime/support.ts +1 -59
  92. package/src/schema.ts +16 -0
  93. package/dist/runtime/support.d.mts +0 -42
  94. package/dist/runtime/support.mjs +0 -1
@@ -101,28 +101,147 @@ function joinPath(base: string, segment: string): string {
101
101
  return base.endsWith(sep) ? `${base}${segment}` : `${base}${sep}${segment}`;
102
102
  }
103
103
 
104
+ // --- discoverManifest
105
+
106
+ /** Default manifest filenames probed when none are supplied. @internal */
107
+ const DEFAULT_MANIFEST_FILES: readonly string[] = ['package.json'];
108
+
109
+ /** Options for {@link discoverManifest}. */
110
+ interface ManifestDiscoveryOptions {
111
+ /**
112
+ * Explicit directory or file path to walk up from. Defaults to
113
+ * `adapter.cwd` when omitted. Pass an absolute path inside your own package
114
+ * (e.g. `fileURLToPath(import.meta.url)`) for installable CLIs whose version
115
+ * should reflect the CLI's own package, not the consumer's working directory.
116
+ *
117
+ * This low-level helper takes a resolved path **string** only. The builder
118
+ * sugar `CLIBuilder.manifest({ from })` exposes the same anchor under the name
119
+ * `from` and additionally accepts a `file:` URL string or `URL` instance,
120
+ * normalizing it to a path first.
121
+ */
122
+ readonly startDir?: string;
123
+ /**
124
+ * Candidate manifest filenames, in per-directory priority order
125
+ * (e.g. `['deno.json', 'jsr.json']`). At each directory the first existing
126
+ * file that carries CLI metadata wins, so the nearest manifest directory
127
+ * always takes precedence over file order. A file that parses but holds no
128
+ * recognised metadata (e.g. a config-only `deno.json` with just
129
+ * `tasks`/`imports`) is skipped, so a sibling `jsr.json` — or a manifest
130
+ * higher up — can still be found. Defaults to `['package.json']`.
131
+ *
132
+ * An empty list is a deliberate no-op: with no candidates to probe, the
133
+ * walk-up reads nothing and resolves to `null` (consistent with the
134
+ * "returns `null` when no manifest is found" contract).
135
+ */
136
+ readonly files?: readonly string[];
137
+ }
138
+
139
+ /**
140
+ * Whether parsed manifest data carries any CLI-relevant metadata.
141
+ *
142
+ * {@link parsePackageJson} returns an empty object for a config-only manifest
143
+ * (e.g. a `deno.json` holding only `tasks` / `imports` / `compilerOptions`).
144
+ * Treating that empty result as a discovery hit would shadow a sibling
145
+ * `jsr.json` and halt the walk-up, silently dropping real metadata. Discovery
146
+ * therefore only accepts a manifest that actually carries at least one
147
+ * recognised field.
148
+ *
149
+ * @internal
150
+ */
151
+ function manifestHasMetadata(data: PackageJsonData): boolean {
152
+ return (
153
+ data.name !== undefined ||
154
+ data.version !== undefined ||
155
+ data.description !== undefined ||
156
+ data.bin !== undefined ||
157
+ data.homepage !== undefined ||
158
+ data.repository !== undefined
159
+ );
160
+ }
161
+
162
+ /**
163
+ * Discover the nearest manifest (`package.json`, `deno.json`, `jsr.json`, …)
164
+ * by walking up from `startDir` (or `adapter.cwd` when omitted).
165
+ *
166
+ * Convenience helper behind `CLIBuilder.manifest()`. Most apps should let the
167
+ * CLI runtime discover metadata automatically; call this directly when testing
168
+ * metadata inference or embedding the behavior in custom tooling.
169
+ *
170
+ * Candidate files are parsed as JSON with a JSONC fallback — `package.json`,
171
+ * `deno.json`, `jsr.json`, and `deno.jsonc` all qualify, including files that
172
+ * carry `//` / block comments or trailing commas (common in `deno.json`). A
173
+ * file that fails both parses is skipped, so discovery keeps probing.
174
+ *
175
+ * Returns the parsed metadata on success, `null` when no manifest is found
176
+ * (not an error). Malformed JSON, non-object roots, and config-only manifests
177
+ * that carry no recognised metadata (e.g. a `deno.json` with only `tasks` /
178
+ * `imports`) are all skipped, so discovery keeps probing the remaining
179
+ * candidate files and parent directories — the feature is a convenience, not a
180
+ * hard requirement.
181
+ *
182
+ * @param adapter - Adapter providing `readFile` + `cwd`.
183
+ * @param options - Optional anchor (`startDir`) and candidate filenames (`files`).
184
+ *
185
+ * @example
186
+ * ```ts
187
+ * import { discoverManifest } from '@kjanat/dreamcli';
188
+ *
189
+ * const meta = await discoverManifest(adapter, { files: ['deno.json', 'jsr.json'] });
190
+ * if (meta !== null) {
191
+ * console.log(meta.version); // '1.2.3'
192
+ * }
193
+ * ```
194
+ */
195
+ async function discoverManifest(
196
+ adapter: PackageJsonAdapter,
197
+ options: ManifestDiscoveryOptions = {},
198
+ ): Promise<PackageJsonData | null> {
199
+ const files = options.files ?? DEFAULT_MANIFEST_FILES;
200
+ let dir: string | undefined = options.startDir ?? adapter.cwd;
201
+
202
+ while (dir !== undefined) {
203
+ for (const file of files) {
204
+ let content: string | null = null;
205
+ try {
206
+ content = await adapter.readFile(joinPath(dir, file));
207
+ } catch {
208
+ // Adapter may throw on permission errors, is-directory, or other
209
+ // syscall failures — skip this file and keep probing.
210
+ }
211
+ if (content !== null) {
212
+ const parsed = parsePackageJson(content);
213
+ if (parsed !== null && manifestHasMetadata(parsed)) {
214
+ return parsed;
215
+ }
216
+ }
217
+ }
218
+ dir = parentDir(dir);
219
+ }
220
+
221
+ return null;
222
+ }
223
+
104
224
  // --- discoverPackageJson
105
225
 
106
226
  /**
107
227
  * Discover the nearest `package.json` by walking up from `startDir` (or
108
228
  * `adapter.cwd` when omitted).
109
229
  *
110
- * Convenience helper behind `CLIBuilder.packageJson()`. Most apps should let
111
- * the CLI runtime discover package metadata automatically; call this directly
112
- * when testing metadata inference or embedding the behavior in custom tooling.
230
+ * @deprecated Use {@link discoverManifest} with `{ files: ['package.json'] }`
231
+ * (the default), which also supports `deno.json` / `jsr.json`.
113
232
  *
114
- * Returns the parsed metadata on success, `null` when no `package.json`
115
- * is found (not an error). Malformed JSON and non-object roots also
116
- * return `null` — the feature is a convenience, not a hard requirement.
233
+ * Behavior note (changed by the manifest generalization): a parseable but
234
+ * metadata-less `package.json` — `{}`, or one carrying only non-metadata fields
235
+ * such as `dependencies` / `scripts` / `type` — is no longer treated as a
236
+ * discovery hit. Previously such a file halted the walk-up and resolved to `{}`;
237
+ * now it is skipped and the walk-up CONTINUES to parent directories. In a
238
+ * monorepo this means a metadata-less leaf `package.json` no longer shadows an
239
+ * ancestor manifest, so an ancestor's `version` can surface where the old
240
+ * behavior returned `{}`. Pass pre-loaded `data` (or use {@link discoverManifest}
241
+ * with an explicit `startDir`) when you need to pin discovery to one directory.
117
242
  *
118
243
  * @param adapter - Adapter providing `readFile` + `cwd`.
119
244
  * @param startDir - Optional explicit directory or file path to walk up from.
120
- * Pass an absolute path inside your own package (e.g.
121
- * `fileURLToPath(import.meta.url)`) when authoring an installable CLI whose
122
- * version should reflect the CLI's own package, not the consumer's working
123
- * directory. Defaults to `adapter.cwd` when `undefined`. A file path is
124
- * probed as a directory first (yielding nothing) before the walk-up reaches
125
- * its real parent directory, so passing `import.meta.url` resolves correctly.
126
245
  *
127
246
  * @example
128
247
  * ```ts
@@ -138,40 +257,117 @@ async function discoverPackageJson(
138
257
  adapter: PackageJsonAdapter,
139
258
  startDir?: string,
140
259
  ): Promise<PackageJsonData | null> {
141
- let dir: string | undefined = startDir ?? adapter.cwd;
260
+ return discoverManifest(adapter, startDir !== undefined ? { startDir } : {});
261
+ }
142
262
 
143
- while (dir !== undefined) {
144
- let content: string | null = null;
145
- try {
146
- content = await adapter.readFile(joinPath(dir, 'package.json'));
147
- } catch {
148
- // Adapter may throw on permission errors, is-directory, or other
149
- // syscall failures — skip this directory and keep walking up.
263
+ // --- stripJsonc
264
+
265
+ /** Whitespace characters JSON treats as insignificant. @internal */
266
+ function isJsonWhitespace(ch: string): boolean {
267
+ return ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r';
268
+ }
269
+
270
+ /**
271
+ * Strip JSONC extensions (line/block comments and trailing commas) so the result
272
+ * is plain JSON. String-aware: comment markers and commas inside string literals
273
+ * are preserved verbatim, so a `"https://…"` URL or a `"/* …"` value survives
274
+ * untouched. Runtime-agnostic — no dependencies, plain string scanning.
275
+ *
276
+ * Only invoked as a fallback when strict `JSON.parse` fails, so valid JSON never
277
+ * passes through here.
278
+ *
279
+ * @internal
280
+ */
281
+ function stripJsonc(input: string): string {
282
+ // Pass 1 — drop comments outside of strings.
283
+ let decommented = '';
284
+ let inString = false;
285
+ let escaped = false;
286
+ for (let i = 0; i < input.length; i += 1) {
287
+ const ch = input[i] ?? '';
288
+ if (inString) {
289
+ decommented += ch;
290
+ if (escaped) escaped = false;
291
+ else if (ch === '\\') escaped = true;
292
+ else if (ch === '"') inString = false;
293
+ continue;
150
294
  }
151
- if (content !== null) {
152
- const parsed = parsePackageJson(content);
153
- if (parsed !== null) {
154
- return parsed;
155
- }
295
+ if (ch === '"') {
296
+ inString = true;
297
+ decommented += ch;
298
+ continue;
156
299
  }
157
- dir = parentDir(dir);
300
+ if (ch === '/' && input[i + 1] === '/') {
301
+ i += 2;
302
+ while (i < input.length && input[i] !== '\n') i += 1;
303
+ i -= 1; // let the loop's increment land on (and re-emit) the newline
304
+ continue;
305
+ }
306
+ if (ch === '/' && input[i + 1] === '*') {
307
+ i += 2;
308
+ while (i < input.length && !(input[i] === '*' && input[i + 1] === '/')) i += 1;
309
+ i += 1; // skip the '*'; the loop increment skips the closing '/'
310
+ continue;
311
+ }
312
+ decommented += ch;
158
313
  }
159
314
 
160
- return null;
315
+ // Pass 2 — drop commas immediately before a closing `}` or `]`.
316
+ let result = '';
317
+ inString = false;
318
+ escaped = false;
319
+ for (let i = 0; i < decommented.length; i += 1) {
320
+ const ch = decommented[i] ?? '';
321
+ if (inString) {
322
+ result += ch;
323
+ if (escaped) escaped = false;
324
+ else if (ch === '\\') escaped = true;
325
+ else if (ch === '"') inString = false;
326
+ continue;
327
+ }
328
+ if (ch === '"') {
329
+ inString = true;
330
+ result += ch;
331
+ continue;
332
+ }
333
+ if (ch === ',') {
334
+ let j = i + 1;
335
+ while (j < decommented.length && isJsonWhitespace(decommented[j] ?? '')) j += 1;
336
+ const next = decommented[j];
337
+ if (next === '}' || next === ']') {
338
+ continue; // trailing comma — omit it
339
+ }
340
+ }
341
+ result += ch;
342
+ }
343
+ return result;
161
344
  }
162
345
 
163
346
  // --- parsePackageJson
164
347
 
165
348
  /**
166
- * Parse a package.json content string into {@link PackageJsonData}.
349
+ * Parse a manifest content string into {@link PackageJsonData}.
167
350
  *
168
- * Returns `null` for malformed JSON or non-object roots.
351
+ * Strict JSON is parsed directly; on failure, a JSONC fallback strips comments
352
+ * and trailing commas (common in `deno.json`) and retries. Returns `null` for
353
+ * content that is neither valid JSON nor JSONC, or whose root is not an object.
169
354
  *
170
355
  * @internal
171
356
  */
172
357
  function parsePackageJson(content: string): PackageJsonData | null {
358
+ let parsed: unknown;
359
+ try {
360
+ parsed = JSON.parse(content);
361
+ } catch {
362
+ // Tolerate JSONC: deno.json is parsed as JSONC by Deno and real files
363
+ // routinely carry comments / trailing commas. Retry after stripping them.
364
+ try {
365
+ parsed = JSON.parse(stripJsonc(content));
366
+ } catch {
367
+ return null;
368
+ }
369
+ }
173
370
  try {
174
- const parsed: unknown = JSON.parse(content);
175
371
  if (!isPlainObject(parsed)) {
176
372
  return null;
177
373
  }
@@ -314,31 +510,44 @@ function packageRepositoryUrl(pkg: PackageJsonData): string | undefined {
314
510
  // --- inferCliName
315
511
 
316
512
  /**
317
- * Infer the CLI binary name from package.json data.
513
+ * Infer the CLI binary name from manifest data.
318
514
  *
319
515
  * Resolution order:
320
516
  * 1. First key of `bin` object (e.g. `{"mycli": "./dist/cli.js"}` → `"mycli"`)
321
- * 2. Package `name` with scope stripped (e.g. `"@scope/mycli"` → `"mycli"`)
517
+ * 2. Package `name`, scope stripped by default (e.g. `"@scope/mycli"` → `"mycli"`);
518
+ * pass `{ stripScope: false }` to keep the full scoped name
322
519
  * 3. `undefined` if neither exists
323
520
  *
521
+ * Note: `bin` keys are never scoped, so `stripScope` only affects the `name`
522
+ * fallback (relevant for `deno.json` / `jsr.json`, which have no `bin` field).
523
+ *
524
+ * @param pkg - Parsed manifest metadata.
525
+ * @param options - `stripScope` (default `true`): strip a leading `@scope/`
526
+ * from the `name` fallback.
527
+ *
324
528
  * @example
325
529
  * ```ts
326
530
  * import { inferCliName } from '@kjanat/dreamcli';
327
531
  *
328
- * inferCliName({ bin: { mycli: './dist/cli.js' } }); // 'mycli'
329
- * inferCliName({ name: '@scope/mycli' }); // 'mycli'
330
- * inferCliName({ name: 'mycli' }); // 'mycli'
331
- * inferCliName({}); // undefined
532
+ * inferCliName({ bin: { mycli: './dist/cli.js' } }); // 'mycli'
533
+ * inferCliName({ name: '@scope/mycli' }); // 'mycli'
534
+ * inferCliName({ name: '@scope/mycli' }, { stripScope: false }); // '@scope/mycli'
535
+ * inferCliName({ name: 'mycli' }); // 'mycli'
536
+ * inferCliName({}); // undefined
332
537
  * ```
333
538
  */
334
- function inferCliName(pkg: PackageJsonData): string | undefined {
335
- // Prefer bin key name
539
+ function inferCliName(
540
+ pkg: PackageJsonData,
541
+ options: { readonly stripScope?: boolean } = {},
542
+ ): string | undefined {
543
+ // Prefer bin key name (never scoped).
336
544
  if (typeof pkg.bin === 'object') {
337
545
  const keys = Object.keys(pkg.bin);
338
546
  if (keys.length > 0 && keys[0] !== undefined) return keys[0];
339
547
  }
340
- // Fall back to package name, stripped of scope
548
+ // Fall back to package name, optionally stripped of scope.
341
549
  if (pkg.name !== undefined) {
550
+ if (options.stripScope === false) return pkg.name;
342
551
  const slashIdx = pkg.name.indexOf('/');
343
552
  return slashIdx >= 0 ? pkg.name.slice(slashIdx + 1) : pkg.name;
344
553
  }
@@ -347,5 +556,5 @@ function inferCliName(pkg: PackageJsonData): string | undefined {
347
556
 
348
557
  // --- Exports
349
558
 
350
- export type { PackageJsonAdapter, PackageJsonData, PackageRepository };
351
- export { discoverPackageJson, inferCliName, packageRepositoryUrl };
559
+ export type { ManifestDiscoveryOptions, PackageJsonAdapter, PackageJsonData, PackageRepository };
560
+ export { discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl };
@@ -16,10 +16,7 @@ import type {
16
16
  import { CLIError } from '#internals/core/errors/index.ts';
17
17
  import { formatHelp } from '#internals/core/help/index.ts';
18
18
  import type { CapturedOutput } from '#internals/core/output/index.ts';
19
- import {
20
- clearRequestedExitCode,
21
- getRequestedExitCode,
22
- } from '#internals/core/output/index.ts';
19
+ import { clearRequestedExitCode, getRequestedExitCode } from '#internals/core/output/index.ts';
23
20
  import { includesBeforeSeparator, parse } from '#internals/core/parse/index.ts';
24
21
  import { createTestPrompter } from '#internals/core/prompt/index.ts';
25
22
  import type { DeprecationWarning, ResolveOptions } from '#internals/core/resolve/index.ts';
@@ -34,6 +34,31 @@ interface HelpOptions {
34
34
  * automatically when stdout is a TTY.
35
35
  */
36
36
  readonly hyperlinks?: boolean;
37
+ /**
38
+ * Render the default command's arguments and flags inline in root help.
39
+ *
40
+ * Only affects root-level help. When `false`, root help lists commands and
41
+ * defers default-command details to `<bin> --help`-style hints.
42
+ *
43
+ * @defaultValue `true`
44
+ */
45
+ readonly inlineDefault?: boolean;
46
+ /**
47
+ * List the default command in the root `Commands:` table.
48
+ *
49
+ * By default the default command is treated as the root surface and omitted
50
+ * from the command list (its args/flags render inline instead).
51
+ *
52
+ * @defaultValue `false`
53
+ */
54
+ readonly showDefaultInCommands?: boolean;
55
+ /**
56
+ * Show the `Run '<bin> <command> --help' for more information.` footer.
57
+ *
58
+ * Defaults to showing the hint only when visible subcommands exist; set
59
+ * explicitly to force it on or off.
60
+ */
61
+ readonly footer?: boolean;
37
62
  /** @internal Whether this usage line is being rendered as merged root/default help. */
38
63
  readonly isDefaultHelp?: boolean;
39
64
  }
@@ -82,7 +107,7 @@ function formatHelpDefaultValue(value: unknown): string {
82
107
 
83
108
  // --- Flag formatting
84
109
 
85
- /** Formatted flag entry for the flags table. */
110
+ /** Formatted flag entry for the flags table. @internal */
86
111
  interface FlagEntry {
87
112
  readonly left: string;
88
113
  readonly description: string;
@@ -349,11 +374,15 @@ function formatHelp(schema: CommandSchema, options?: HelpOptions): string {
349
374
  */
350
375
  function formatUsageLine(schema: CommandSchema, opts: ResolvedHelpOptions): string {
351
376
  const parts: string[] = ['Usage:'];
377
+ // For the default command rendered as the root surface (`isDefaultHelp`), the
378
+ // command name is NOT a route — `.default()` does not register a named command,
379
+ // so `mycli <name>` would be consumed as the default's first positional, not a
380
+ // dispatch. Render usage with only the bin name to avoid teaching a fake form.
352
381
  const cmdName =
353
382
  opts.binName === undefined
354
383
  ? schema.name
355
- : opts.isDefaultHelp && opts.binName === schema.name
356
- ? schema.name
384
+ : opts.isDefaultHelp
385
+ ? opts.binName
357
386
  : `${opts.binName} ${schema.name}`;
358
387
  parts.push(cmdName);
359
388
 
@@ -422,13 +451,31 @@ function formatFlagsSection(
422
451
  flags: Readonly<Record<string, FlagSchema>>,
423
452
  opts: ResolvedHelpOptions,
424
453
  ): string {
425
- const lines: string[] = ['Flags:'];
426
- const GAP = 2;
454
+ return formatFlagEntriesBlock('Flags:', buildFlagEntries(flags), opts.width);
455
+ }
427
456
 
428
- const entries = buildFlagEntries(flags);
457
+ /**
458
+ * Render a titled two-column flag block from pre-built {@link FlagEntry} rows.
459
+ *
460
+ * Shared by the per-command `Flags:` section and the root-help `Global options:`
461
+ * block (built-in flags), so column alignment and description wrapping stay
462
+ * identical across both. Returns `''` when there are no entries.
463
+ *
464
+ * @param title - Section heading (e.g. `'Flags:'`, `'Global options:'`).
465
+ * @param entries - Formatted left/description rows.
466
+ * @param width - Terminal width for description wrapping.
467
+ * @returns Multi-line block string, or `''` when `entries` is empty.
468
+ * @internal
469
+ */
470
+ function formatFlagEntriesBlock(
471
+ title: string,
472
+ entries: readonly FlagEntry[],
473
+ width: number,
474
+ ): string {
429
475
  if (entries.length === 0) return '';
476
+ const lines: string[] = [title];
477
+ const GAP = 2;
430
478
 
431
- // Compute max left width
432
479
  let maxLeft = 0;
433
480
  for (const entry of entries) {
434
481
  const indented = ` ${entry.left}`;
@@ -442,7 +489,7 @@ function formatFlagsSection(
442
489
  lines.push(left);
443
490
  } else {
444
491
  const padded = padEnd(left, descCol);
445
- const wrapped = wrapText(entry.description, opts.width, descCol);
492
+ const wrapped = wrapText(entry.description, width, descCol);
446
493
  lines.push(`${padded}${wrapped}`);
447
494
  }
448
495
  }
@@ -512,5 +559,5 @@ function formatExamplesSection(examples: readonly CommandExample[]): string {
512
559
  // --- Exports
513
560
 
514
561
  export { osc8, visibleWidth } from './ansi.ts';
515
- export type { HelpOptions };
516
- export { formatHelp, formatHelpSections };
562
+ export type { FlagEntry, HelpOptions };
563
+ export { formatFlagEntriesBlock, formatHelp, formatHelpSections };
@@ -579,9 +579,17 @@ function flagToJsonSchemaType(schema: FlagSchema): Record<string, unknown> {
579
579
  case 'string':
580
580
  result.type = 'string';
581
581
  break;
582
- case 'number':
583
- result.type = 'number';
582
+ case 'number': {
583
+ const constraints = schema.numberConstraints;
584
+ result.type = constraints?.int === true ? 'integer' : 'number';
585
+ if (constraints?.min !== undefined) {
586
+ result.minimum = constraints.min;
587
+ }
588
+ if (constraints?.max !== undefined) {
589
+ result.maximum = constraints.max;
590
+ }
584
591
  break;
592
+ }
585
593
  case 'boolean':
586
594
  result.type = 'boolean';
587
595
  break;
@@ -641,8 +649,19 @@ function argKindToType(schema: ArgSchema): Record<string, unknown> {
641
649
  switch (schema.kind) {
642
650
  case 'string':
643
651
  return { type: 'string' };
644
- case 'number':
645
- return { type: 'number' };
652
+ case 'number': {
653
+ const constraints = schema.numberConstraints;
654
+ const result: Record<string, unknown> = {
655
+ type: constraints?.int === true ? 'integer' : 'number',
656
+ };
657
+ if (constraints?.min !== undefined) {
658
+ result.minimum = constraints.min;
659
+ }
660
+ if (constraints?.max !== undefined) {
661
+ result.maximum = constraints.max;
662
+ }
663
+ return result;
664
+ }
646
665
  case 'enum': {
647
666
  const result: Record<string, unknown> = { type: 'string' };
648
667
  if (schema.enumValues !== undefined) {