@kjanat/dreamcli 2.0.0 → 2.1.0

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.
@@ -44,7 +44,7 @@ function generatePowerShellCompletion(schema: CLISchema, options?: CompletionOpt
44
44
  lines.push(`# Generated by ${versionTag()}`);
45
45
  lines.push('#');
46
46
  lines.push('# Install for the current session:');
47
- lines.push(`# ${schema.name} completions powershell | Invoke-Expression`);
47
+ lines.push(`# ${schema.name} completions powershell | Out-String | Invoke-Expression`);
48
48
  lines.push('#');
49
49
  lines.push('# Install permanently:');
50
50
  lines.push(`# ${schema.name} completions powershell > $PROFILE.CurrentUserCurrentHost`);
@@ -69,6 +69,10 @@ function generatePowerShellCompletion(schema: CLISchema, options?: CompletionOpt
69
69
  lines.push('\t}');
70
70
  lines.push('');
71
71
  lines.push('\t$results = [System.Collections.Generic.List[CompletionResult]]::new()');
72
+ lines.push('\tif ($state.AfterSeparator) {');
73
+ lines.push('\t\treturn $results');
74
+ lines.push('\t}');
75
+ lines.push('');
72
76
  lines.push(
73
77
  `\t$wordPrefix = if ([string]::IsNullOrEmpty($wordToComplete)) { '' } else { $wordToComplete }`,
74
78
  );
@@ -236,12 +240,13 @@ function emitPowerShellHelpers(lines: string[], helperPrefix: string, dataVarNam
236
240
  lines.push('\tparam([CommandAst]$CommandAst, [int]$CursorPosition)');
237
241
  lines.push(`\t$pathData = $script:${dataVarName}[${quotePowerShellString('')}]`);
238
242
  lines.push('\t$path = ""');
243
+ lines.push('\t$afterSeparator = $false');
239
244
  lines.push('\t$expectingValue = $false');
240
245
  lines.push('\t$valueFlag = $null');
241
246
  lines.push('\t$tokens = [System.Collections.Generic.List[string]]::new()');
242
247
  lines.push('');
243
248
  lines.push('\tforeach ($element in $CommandAst.CommandElements | Select-Object -Skip 1) {');
244
- lines.push('\t\tif ($element.Extent.EndOffset -gt $CursorPosition) {');
249
+ lines.push('\t\tif ($element.Extent.EndOffset -ge $CursorPosition) {');
245
250
  lines.push('\t\t\tbreak');
246
251
  lines.push('\t\t}');
247
252
  lines.push(`\t\t$tokenText = ${helperPrefix}_UnquoteToken $element.Extent.Text`);
@@ -256,6 +261,7 @@ function emitPowerShellHelpers(lines: string[], helperPrefix: string, dataVarNam
256
261
  lines.push('\t\t}');
257
262
  lines.push('');
258
263
  lines.push("\t\tif ($token -eq '--') {");
264
+ lines.push('\t\t\t$afterSeparator = $true');
259
265
  lines.push('\t\t\tbreak');
260
266
  lines.push('\t\t}');
261
267
  lines.push('');
@@ -292,6 +298,7 @@ function emitPowerShellHelpers(lines: string[], helperPrefix: string, dataVarNam
292
298
  lines.push('\treturn @{');
293
299
  lines.push('\t\tPath = $path');
294
300
  lines.push('\t\tPathData = $pathData');
301
+ lines.push('\t\tAfterSeparator = $afterSeparator');
295
302
  lines.push('\t\tExpectingValue = $expectingValue');
296
303
  lines.push('\t\tValueFlag = $valueFlag');
297
304
  lines.push('\t}');
@@ -308,6 +315,30 @@ function emitPowerShellHelpers(lines: string[], helperPrefix: string, dataVarNam
308
315
  lines.push('\treturn $flagMatch');
309
316
  lines.push('}');
310
317
  lines.push('');
318
+ lines.push(`function ${helperPrefix}_FormatCompletionValue {`);
319
+ lines.push('\tparam([string]$Value)');
320
+ lines.push('\tif ($Value.Length -eq 0) {');
321
+ lines.push("\t\treturn \"''\"");
322
+ lines.push('\t}');
323
+ lines.push('');
324
+ lines.push("\tif ($Value -match '^[a-zA-Z0-9_./:\\\\-]+$') {");
325
+ lines.push('\t\treturn $Value');
326
+ lines.push('\t}');
327
+ lines.push('');
328
+ lines.push("\treturn \"'$([CodeGeneration]::EscapeSingleQuotedStringContent($Value))'\"");
329
+ lines.push('}');
330
+ lines.push('');
331
+ lines.push(`function ${helperPrefix}_MatchesCompletionPrefix {`);
332
+ lines.push('\tparam([string]$WordToComplete, [string]$RawText, [string]$CompletionText)');
333
+ lines.push('\tif ([string]::IsNullOrEmpty($WordToComplete)) {');
334
+ lines.push('\t\treturn $true');
335
+ lines.push('\t}');
336
+ lines.push('');
337
+ lines.push(
338
+ '\treturn $RawText.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase) -or $CompletionText.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)',
339
+ );
340
+ lines.push('}');
341
+ lines.push('');
311
342
  lines.push(`function ${helperPrefix}_AddCommandResults {`);
312
343
  lines.push('\tparam($Results, $PathData, [string]$WordToComplete)');
313
344
  lines.push('\tforeach ($command in $PathData.Commands) {');
@@ -351,14 +382,15 @@ function emitPowerShellHelpers(lines: string[], helperPrefix: string, dataVarNam
351
382
  lines.push(`function ${helperPrefix}_AddEnumResults {`);
352
383
  lines.push('\tparam($Results, $Flag, [string]$WordToComplete)');
353
384
  lines.push('\tforeach ($value in $Flag.EnumValues) {');
385
+ lines.push(`\t\t$completionText = ${helperPrefix}_FormatCompletionValue -Value $value`);
354
386
  lines.push(
355
- '\t\tif (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $value.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {',
387
+ `\t\tif (-not (${helperPrefix}_MatchesCompletionPrefix -WordToComplete $WordToComplete -RawText $value -CompletionText $completionText)) {`,
356
388
  );
357
389
  lines.push('\t\t\tcontinue');
358
390
  lines.push('\t\t}');
359
391
  lines.push('');
360
392
  lines.push('\t\t$Results.Add([CompletionResult]::new(');
361
- lines.push('\t\t\t$value,');
393
+ lines.push('\t\t\t$completionText,');
362
394
  lines.push('\t\t\t$value,');
363
395
  lines.push('\t\t\t[CompletionResultType]::ParameterValue,');
364
396
  lines.push('\t\t\t$Flag.Description');
@@ -369,15 +401,17 @@ function emitPowerShellHelpers(lines: string[], helperPrefix: string, dataVarNam
369
401
  lines.push(`function ${helperPrefix}_AddInlineEnumResults {`);
370
402
  lines.push('\tparam($Results, $InlineValue, [string]$WordToComplete)');
371
403
  lines.push('\tforeach ($value in $InlineValue.Flag.EnumValues) {');
372
- lines.push('\t\t$completion = "$($InlineValue.InlinePrefix)$value"');
404
+ lines.push('\t\t$rawCompletion = "$($InlineValue.InlinePrefix)$value"');
405
+ lines.push(`\t\t$formattedValue = ${helperPrefix}_FormatCompletionValue -Value $value`);
406
+ lines.push('\t\t$completionText = "$($InlineValue.InlinePrefix)$formattedValue"');
373
407
  lines.push(
374
- '\t\tif (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $completion.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {',
408
+ `\t\tif (-not (${helperPrefix}_MatchesCompletionPrefix -WordToComplete $WordToComplete -RawText $rawCompletion -CompletionText $completionText)) {`,
375
409
  );
376
410
  lines.push('\t\t\tcontinue');
377
411
  lines.push('\t\t}');
378
412
  lines.push('');
379
413
  lines.push('\t\t$Results.Add([CompletionResult]::new(');
380
- lines.push('\t\t\t$completion,');
414
+ lines.push('\t\t\t$completionText,');
381
415
  lines.push('\t\t\t$value,');
382
416
  lines.push('\t\t\t[CompletionResultType]::ParameterValue,');
383
417
  lines.push('\t\t\t$InlineValue.Flag.Description');
@@ -87,11 +87,11 @@ function resolveOptions(options: JsonSchemaOptions | undefined): ResolvedOptions
87
87
  /**
88
88
  * `$schema` URL for definition documents.
89
89
  *
90
- * Resolves via the `@kjanat/dreamcli/schema` package export on the CDN.
90
+ * Resolves via the actual file path on the CDN (`dreamcli.schema.json`).
91
91
  * For offline or local-first workflows, use
92
92
  * `./node_modules/@kjanat/dreamcli/dreamcli.schema.json`.
93
93
  */
94
- const DEFINITION_SCHEMA_URL = 'https://cdn.jsdelivr.net/npm/@kjanat/dreamcli/schema';
94
+ const DEFINITION_SCHEMA_URL = 'https://cdn.jsdelivr.net/npm/@kjanat/dreamcli/dreamcli.schema.json';
95
95
 
96
96
  /** Meta-schema URL for JSON Schema draft 2020-12 (input validation). */
97
97
  const JSON_SCHEMA_DRAFT = 'https://json-schema.org/draft/2020-12/schema';
@@ -6,193 +6,176 @@
6
6
 
7
7
  const definitionMetaSchemaDescriptions = {
8
8
  root: {
9
- description:
10
- 'Runtime descriptor for the CLI program.\n\nStores the program name, version, description, and registered commands.\\\nBuilt incrementally by CLIBuilder.',
9
+ description: "Runtime descriptor for the CLI program.\n\nStores the program name, version, description, and registered commands.\\\nBuilt incrementally by CLIBuilder.",
11
10
  properties: {
12
- name: {
13
- description: 'Program name (used in help text, usage lines, and completion scripts).',
11
+ "name": {
12
+ description: "Program name (used in help text, usage lines, and completion scripts).",
14
13
  },
15
- version: {
16
- description: 'Program version (shown by `--version`).',
14
+ "version": {
15
+ description: "Program version (shown by `--version`).",
17
16
  },
18
- description: {
19
- description: 'Program description (shown in root help).',
17
+ "description": {
18
+ description: "Program description (shown in root help).",
20
19
  },
21
- defaultCommand: {
22
- description:
23
- 'Default command dispatched when no subcommand matches.\n\nWhen set, the CLI root behaves like a hybrid command group: subcommands\ndispatch by name as usual, but empty argv or flags-only argv falls\nthrough to this command instead of showing root help.\n\nSet via the .default() builder method.',
20
+ "defaultCommand": {
21
+ description: "Default command dispatched when no subcommand matches.\n\nWhen set, the CLI root behaves like a hybrid command group: subcommands\ndispatch by name as usual, but empty argv or flags-only argv falls\nthrough to this command instead of showing root help.\n\nSet via the .default() builder method.",
24
22
  },
25
- commands: {
26
- description: 'Registered commands (type-erased for heterogeneous storage).',
23
+ "commands": {
24
+ description: "Registered commands (type-erased for heterogeneous storage).",
27
25
  },
28
26
  },
29
27
  },
30
28
  defs: {
31
- command: {
32
- description:
33
- "Runtime descriptor produced by CommandBuilder.\n\nConsumers (parser, help generator, CLI dispatcher) read this to\nunderstand the command's shape — flags, args, aliases, subcommands,\nmiddleware, and interactive resolver.",
29
+ "command": {
30
+ description: "Runtime descriptor produced by CommandBuilder.\n\nConsumers (parser, help generator, CLI dispatcher) read this to\nunderstand the command's shape — flags, args, aliases, subcommands,\nmiddleware, and interactive resolver.",
34
31
  properties: {
35
- name: {
32
+ "name": {
36
33
  description: "The command name (used for dispatch, e.g. `'deploy'`).",
37
34
  },
38
- description: {
39
- description: 'Human-readable description for help text.',
35
+ "description": {
36
+ description: "Human-readable description for help text.",
40
37
  },
41
- aliases: {
42
- description: 'Alternative names for this command.',
38
+ "aliases": {
39
+ description: "Alternative names for this command.",
43
40
  },
44
- hidden: {
45
- description: 'Whether this command is hidden from help listings.',
41
+ "hidden": {
42
+ description: "Whether this command is hidden from help listings.",
46
43
  },
47
- examples: {
48
- description: 'Usage examples for help text.',
44
+ "examples": {
45
+ description: "Usage examples for help text.",
49
46
  },
50
- flags: {
51
- description: 'Named flag schemas, keyed by flag name.',
47
+ "flags": {
48
+ description: "Named flag schemas, keyed by flag name.",
52
49
  },
53
- args: {
54
- description: 'Ordered positional arg entries (name + schema).',
50
+ "args": {
51
+ description: "Ordered positional arg entries (name + schema).",
55
52
  },
56
- commands: {
57
- description:
58
- 'Nested subcommand schemas (for help rendering and completion).\n\nPure data — no execution closures. Populated by `.command()` on\n`CommandBuilder`. Empty for leaf commands.',
53
+ "commands": {
54
+ description: "Nested subcommand schemas (for help rendering and completion).\n\nPure data — no execution closures. Populated by `.command()` on\n`CommandBuilder`. Empty for leaf commands.",
59
55
  },
60
56
  },
61
57
  },
62
- flag: {
63
- description:
64
- "The runtime descriptor stored inside every FlagBuilder. Consumers (parser,\nhelp generator, resolution chain) read this to understand the flag's shape\nwithout touching generics.",
58
+ "flag": {
59
+ description: "The runtime descriptor stored inside every FlagBuilder. Consumers (parser,\nhelp generator, resolution chain) read this to understand the flag's shape\nwithout touching generics.",
65
60
  properties: {
66
- kind: {
67
- description: 'What kind of value this flag accepts.',
61
+ "kind": {
62
+ description: "What kind of value this flag accepts.",
68
63
  },
69
- presence: {
70
- description:
71
- "Presence describes whether a flag value is guaranteed to exist when the\naction handler runs:\n\n- `'optional'` — not required; unresolved value follows the kind-specific\n optional fallback (`undefined` for most flags, `[]` for arrays)\n- `'required'` — must be supplied; error if missing\n- `'defaulted'` — always present (falls back to default value)",
64
+ "presence": {
65
+ description: "Presence describes whether a flag value is guaranteed to exist when the\naction handler runs:\n\n- `'optional'` — not required; unresolved value follows the kind-specific\n optional fallback (`undefined` for most flags, `[]` for arrays)\n- `'required'` — must be supplied; error if missing\n- `'defaulted'` — always present (falls back to default value)",
72
66
  },
73
- defaultValue: {
74
- description: 'Runtime default value (if any).',
67
+ "defaultValue": {
68
+ description: "Runtime default value (if any).",
75
69
  },
76
- aliases: {
70
+ "aliases": {
77
71
  description: "Short/long aliases (e.g. `[{ name: 'f', hidden: false }]` for `--force`).",
78
72
  },
79
- envVar: {
80
- description: 'Environment variable name for v0.2+ resolution.',
73
+ "envVar": {
74
+ description: "Environment variable name for v0.2+ resolution.",
81
75
  },
82
- configPath: {
76
+ "configPath": {
83
77
  description: "Dotted config path for v0.2+ resolution (e.g. `'deploy.region'`).",
84
78
  },
85
- description: {
86
- description: 'Human-readable description for help text.',
79
+ "description": {
80
+ description: "Human-readable description for help text.",
87
81
  },
88
- enumValues: {
82
+ "enumValues": {
89
83
  description: "Allowed literal values when `kind === 'enum'`.",
90
84
  },
91
- elementSchema: {
85
+ "elementSchema": {
92
86
  description: "Element schema when `kind === 'array'`.",
93
87
  },
94
- prompt: {
95
- description: 'Interactive prompt configuration for v0.3+ resolution.',
88
+ "prompt": {
89
+ description: "Interactive prompt configuration for v0.3+ resolution.",
96
90
  },
97
- deprecated: {
98
- description:
99
- 'Deprecation marker.\n\n- `undefined` — not deprecated (default)\n- `true` — deprecated with no migration message\n- `string` — deprecated with a reason/migration message\n\nWhen a deprecated flag is used, a warning is emitted to stderr.\nHelp text shows `[deprecated]` or `[deprecated: <reason>]`.',
91
+ "deprecated": {
92
+ description: "Deprecation marker.\n\n- `undefined` — not deprecated (default)\n- `true` — deprecated with no migration message\n- `string` — deprecated with a reason/migration message\n\nWhen a deprecated flag is used, a warning is emitted to stderr.\nHelp text shows `[deprecated]` or `[deprecated: <reason>]`.",
100
93
  },
101
- propagate: {
102
- description:
103
- 'Whether this flag propagates to subcommands in nested command trees.\n\nWhen `true`, the flag is automatically available to all descendant\ncommands. A child command that defines a flag with the same name\nshadows the propagated parent flag.',
94
+ "propagate": {
95
+ description: "Whether this flag propagates to subcommands in nested command trees.\n\nWhen `true`, the flag is automatically available to all descendant\ncommands. A child command that defines a flag with the same name\nshadows the propagated parent flag.",
104
96
  },
105
97
  },
106
98
  },
107
- arg: {
108
- description:
109
- "The runtime descriptor stored inside every ArgBuilder. Consumers (parser,\nhelp generator) read this to understand the arg's shape without touching\ngenerics.",
99
+ "arg": {
100
+ description: "The runtime descriptor stored inside every ArgBuilder. Consumers (parser,\nhelp generator) read this to understand the arg's shape without touching\ngenerics.",
110
101
  properties: {
111
- name: {
112
- description:
113
- 'A named positional argument entry in the command schema.\n\nPairs a user-facing arg name with its ArgSchema descriptor.\nThe array ordering in CommandSchema.args determines CLI position.',
102
+ "name": {
103
+ description: "A named positional argument entry in the command schema.\n\nPairs a user-facing arg name with its ArgSchema descriptor.\nThe array ordering in CommandSchema.args determines CLI position.",
114
104
  },
115
- kind: {
116
- description: 'What kind of value this arg accepts.',
105
+ "kind": {
106
+ description: "What kind of value this arg accepts.",
117
107
  },
118
- presence: {
119
- description:
120
- "Presence describes whether a positional arg is guaranteed to exist when the\naction handler runs:\n\n- `'required'` — must be supplied; error if missing (default)\n- `'optional'` — may be `undefined` if not supplied\n- `'defaulted'` — always present (falls back to default value)",
108
+ "presence": {
109
+ description: "Presence describes whether a positional arg is guaranteed to exist when the\naction handler runs:\n\n- `'required'` — must be supplied; error if missing (default)\n- `'optional'` — may be `undefined` if not supplied\n- `'defaulted'` — always present (falls back to default value)",
121
110
  },
122
- variadic: {
123
- description: 'Whether this arg consumes all remaining positionals.',
111
+ "variadic": {
112
+ description: "Whether this arg consumes all remaining positionals.",
124
113
  },
125
- stdinMode: {
126
- description: 'Whether this arg may read from stdin during resolution.',
114
+ "stdinMode": {
115
+ description: "Whether this arg may read from stdin during resolution.",
127
116
  },
128
- defaultValue: {
129
- description: 'Runtime default value (if any).',
117
+ "defaultValue": {
118
+ description: "Runtime default value (if any).",
130
119
  },
131
- description: {
132
- description: 'Human-readable description for help text.',
120
+ "description": {
121
+ description: "Human-readable description for help text.",
133
122
  },
134
- envVar: {
135
- description:
136
- "Environment variable name for env resolution.\n\nWhen set and the CLI value is absent, the resolver reads this env var\nand coerces the string to the arg's declared kind.",
123
+ "envVar": {
124
+ description: "Environment variable name for env resolution.\n\nWhen set and the CLI value is absent, the resolver reads this env var\nand coerces the string to the arg's declared kind.",
137
125
  },
138
- enumValues: {
126
+ "enumValues": {
139
127
  description: "Allowed literal values when `kind === 'enum'`.",
140
128
  },
141
- deprecated: {
142
- description:
143
- 'Deprecation marker.\n\n- `undefined` — not deprecated (default)\n- `true` — deprecated with no migration message\n- `string` — deprecated with a reason/migration message\n\nWhen a deprecated arg is used, a warning is emitted to stderr.\nHelp text shows `[deprecated]` or `[deprecated: <reason>]`.',
129
+ "deprecated": {
130
+ description: "Deprecation marker.\n\n- `undefined` — not deprecated (default)\n- `true` — deprecated with no migration message\n- `string` — deprecated with a reason/migration message\n\nWhen a deprecated arg is used, a warning is emitted to stderr.\nHelp text shows `[deprecated]` or `[deprecated: <reason>]`.",
144
131
  },
145
132
  },
146
133
  },
147
- prompt: {
148
- description:
149
- "Discriminated union of all prompt configurations.\n\nUse the `kind` field to narrow:\n```ts\nif (config.kind === 'select') {\n config.choices // readonly SelectChoice[] | undefined\n}\n```",
134
+ "prompt": {
135
+ description: "Discriminated union of all prompt configurations.\n\nUse the `kind` field to narrow:\n```ts\nif (config.kind === 'select') {\n config.choices // readonly SelectChoice[] | undefined\n}\n```",
150
136
  properties: {
151
- kind: {
152
- description:
153
- "The kind of interactive prompt to present.\n\n- `'confirm'` — yes/no boolean question\n- `'input'` — free-text string input\n- `'select'` — single selection from a list\n- `'multiselect'` — multiple selections from a list",
137
+ "kind": {
138
+ description: "The kind of interactive prompt to present.\n\n- `'confirm'` — yes/no boolean question\n- `'input'` — free-text string input\n- `'select'` — single selection from a list\n- `'multiselect'` — multiple selections from a list",
154
139
  },
155
- message: {
156
- description: 'The question displayed to the user.',
140
+ "message": {
141
+ description: "The question displayed to the user.",
157
142
  },
158
- placeholder: {
159
- description: 'Placeholder text shown before user types (informational only).',
143
+ "placeholder": {
144
+ description: "Placeholder text shown before user types (informational only).",
160
145
  },
161
- choices: {
162
- description:
163
- 'Available choices. When omitted for `enum` flags, the enum values\nfrom the flag schema are used automatically.',
146
+ "choices": {
147
+ description: "Available choices. When omitted for `enum` flags, the enum values\nfrom the flag schema are used automatically.",
164
148
  },
165
- min: {
166
- description: 'Minimum number of selections required.',
149
+ "min": {
150
+ description: "Minimum number of selections required.",
167
151
  },
168
- max: {
169
- description: 'Maximum number of selections allowed.',
152
+ "max": {
153
+ description: "Maximum number of selections allowed.",
170
154
  },
171
155
  },
172
156
  },
173
- choice: {
174
- description:
175
- 'A selectable option for SelectPromptConfig and MultiselectPromptConfig prompts.',
157
+ "choice": {
158
+ description: "A selectable option for SelectPromptConfig and MultiselectPromptConfig prompts.",
176
159
  properties: {
177
- value: {
178
- description: 'The value returned when this choice is selected.',
160
+ "value": {
161
+ description: "The value returned when this choice is selected.",
179
162
  },
180
- label: {
181
- description: 'Display label shown to the user.',
163
+ "label": {
164
+ description: "Display label shown to the user.",
182
165
  },
183
- description: {
184
- description: 'Optional description shown alongside the choice.',
166
+ "description": {
167
+ description: "Optional description shown alongside the choice.",
185
168
  },
186
169
  },
187
170
  },
188
- example: {
189
- description: 'A single usage example shown in help text.',
171
+ "example": {
172
+ description: "A single usage example shown in help text.",
190
173
  properties: {
191
- command: {
174
+ "command": {
192
175
  description: "The command invocation (e.g. `'deploy production --force'`).",
193
176
  },
194
- description: {
195
- description: 'Optional description of what this example does.',
177
+ "description": {
178
+ description: "Optional description of what this example does.",
196
179
  },
197
180
  },
198
181
  },
@@ -8,8 +8,9 @@
8
8
  import { ValidationError } from '#internals/core/errors/index.ts';
9
9
  import type { PromptEngine } from '#internals/core/prompt/index.ts';
10
10
  import { resolvePromptConfig } from '#internals/core/prompt/index.ts';
11
- import type { ErasedInteractiveResolver, FlagSchema } from '#internals/core/schema/index.ts';
12
- import type { PromptConfig } from '#internals/core/schema/prompt.ts';
11
+ import type { ErasedInteractiveResolver } from '#internals/core/schema/command.ts';
12
+ import type { FlagKind, FlagSchema } from '#internals/core/schema/flag.ts';
13
+ import type { PromptConfig, PromptKind } from '#internals/core/schema/prompt.ts';
13
14
  import { coerceValue } from './coerce.ts';
14
15
  import { resolveConfigPath } from './config.ts';
15
16
  import type { DeprecationWarning } from './contracts.ts';
@@ -165,12 +166,60 @@ async function resolveFlags(
165
166
  return resolved;
166
167
  }
167
168
 
169
+ /** Maps each flag kind to the prompt kinds that produce compatible values. */
170
+ const COMPATIBLE_PROMPT_KINDS: Record<FlagKind, readonly PromptKind[]> = {
171
+ boolean: ['confirm'],
172
+ string: ['input', 'select'],
173
+ number: ['input'],
174
+ enum: ['select', 'input'],
175
+ array: ['multiselect'],
176
+ custom: ['input', 'select', 'confirm', 'multiselect'],
177
+ };
178
+
179
+ /**
180
+ * Check whether a prompt kind is compatible with the flag's declared kind.
181
+ *
182
+ * @returns `undefined` when compatible, or a {@link ValidationError} with
183
+ * code `'CONSTRAINT_VIOLATED'` and an actionable `suggest` message when not.
184
+ * @internal
185
+ */
186
+ function validatePromptFlagCompatibility(
187
+ flagName: string,
188
+ flagKind: FlagKind,
189
+ promptKind: PromptKind,
190
+ ): ValidationError | undefined {
191
+ const allowed = COMPATIBLE_PROMPT_KINDS[flagKind];
192
+ if (allowed.includes(promptKind)) return undefined;
193
+
194
+ return new ValidationError(
195
+ `Prompt kind '${promptKind}' is not compatible with ${flagKind} flag --${flagName}. Use '${allowed[0]}' instead`,
196
+ {
197
+ code: 'CONSTRAINT_VIOLATED',
198
+ details: { flag: flagName, flagKind, promptKind, allowed },
199
+ suggest: `Change the prompt to { kind: '${allowed[0]}' } for --${flagName}`,
200
+ },
201
+ );
202
+ }
203
+
204
+ /**
205
+ * Validate prompt/flag compatibility, run the prompt engine, and coerce the result.
206
+ *
207
+ * Returns early with a {@link ValidationError} if the prompt kind is
208
+ * incompatible with the flag kind (checked via {@link COMPATIBLE_PROMPT_KINDS}
209
+ * before the prompter is invoked).
210
+ * @internal
211
+ */
168
212
  async function resolvePromptValueWithConfig(
169
213
  flagName: string,
170
214
  schema: FlagSchema,
171
215
  promptConfig: PromptConfig,
172
216
  prompter: PromptEngine,
173
217
  ): Promise<PromptResolveResult> {
218
+ const mismatch = validatePromptFlagCompatibility(flagName, schema.kind, promptConfig.kind);
219
+ if (mismatch !== undefined) {
220
+ return { ok: false, error: mismatch };
221
+ }
222
+
174
223
  const resolvedConfig = resolvePromptConfig(promptConfig, schema.enumValues);
175
224
  const result = await prompter.promptOne(resolvedConfig);
176
225
 
@@ -181,6 +230,7 @@ async function resolvePromptValueWithConfig(
181
230
  return coerceValue(flagName, { kind: 'prompt' }, result.value, schema);
182
231
  }
183
232
 
233
+ /** Build a human-readable suggestion listing all available sources for a required flag. @internal */
184
234
  function buildRequiredFlagSuggest(name: string, schema: FlagSchema): string {
185
235
  const sources: string[] = [];
186
236
  sources.push(`Provide --${name}${schema.kind !== 'boolean' ? ' <value>' : ''}`);
@@ -202,4 +252,4 @@ function buildRequiredFlagSuggest(name: string, schema: FlagSchema): string {
202
252
  return sources.length === 2 ? `${rest.join('')} or ${last}` : `${rest.join(', ')}, or ${last}`;
203
253
  }
204
254
 
205
- export { resolveFlags };
255
+ export { COMPATIBLE_PROMPT_KINDS, resolveFlags };