@kjanat/dreamcli 1.0.0 → 2.0.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 (217) hide show
  1. package/CHANGELOG.md +63 -6
  2. package/LICENSE +1 -1
  3. package/README.md +296 -164
  4. package/dist/core/cli/dispatch.d.mts +85 -0
  5. package/dist/core/cli/dispatch.mjs +1 -0
  6. package/dist/core/cli/index.d.mts +418 -0
  7. package/dist/core/cli/index.mjs +1 -0
  8. package/dist/core/cli/planner.d.mts +143 -0
  9. package/dist/core/cli/planner.mjs +1 -0
  10. package/dist/core/cli/plugin.d.mts +94 -0
  11. package/dist/core/cli/plugin.mjs +1 -0
  12. package/dist/core/cli/propagate.d.mts +39 -0
  13. package/dist/core/cli/propagate.mjs +1 -0
  14. package/dist/core/cli/root-help.d.mts +28 -0
  15. package/dist/core/cli/root-help.mjs +7 -0
  16. package/dist/core/cli/root-surface.d.mts +42 -0
  17. package/dist/core/cli/root-surface.mjs +1 -0
  18. package/dist/core/cli/runtime-preflight.d.mts +149 -0
  19. package/dist/core/cli/runtime-preflight.mjs +1 -0
  20. package/dist/core/completion/index.d.mts +46 -0
  21. package/dist/core/completion/index.mjs +1 -0
  22. package/dist/core/completion/shells/bash.d.mts +24 -0
  23. package/dist/core/completion/shells/bash.mjs +3 -0
  24. package/dist/core/completion/shells/fish.d.mts +20 -0
  25. package/dist/core/completion/shells/fish.mjs +2 -0
  26. package/dist/core/completion/shells/powershell.d.mts +14 -0
  27. package/dist/core/completion/shells/powershell.mjs +2 -0
  28. package/dist/core/completion/shells/shared.d.mts +139 -0
  29. package/dist/core/completion/shells/shared.mjs +1 -0
  30. package/dist/core/completion/shells/zsh.d.mts +24 -0
  31. package/dist/core/completion/shells/zsh.mjs +2 -0
  32. package/dist/core/config/index.d.mts +161 -0
  33. package/dist/core/config/index.mjs +1 -0
  34. package/dist/core/config/package-json.d.mts +68 -0
  35. package/dist/core/config/package-json.mjs +1 -0
  36. package/dist/core/errors/index.d.mts +126 -0
  37. package/dist/core/errors/index.mjs +1 -0
  38. package/dist/core/execution/index.d.mts +49 -0
  39. package/dist/core/execution/index.mjs +1 -0
  40. package/dist/core/help/index.d.mts +49 -0
  41. package/dist/core/help/index.mjs +8 -0
  42. package/dist/core/json-schema/index.d.mts +109 -0
  43. package/dist/core/json-schema/index.mjs +55 -0
  44. package/dist/core/json-schema/meta-descriptions.generated.d.mts +185 -0
  45. package/dist/core/json-schema/meta-descriptions.generated.mjs +28 -0
  46. package/dist/core/output/activity.d.mts +194 -0
  47. package/dist/core/output/activity.mjs +1 -0
  48. package/dist/core/output/contracts.d.mts +88 -0
  49. package/dist/core/output/contracts.mjs +1 -0
  50. package/dist/core/output/display-value.d.mts +19 -0
  51. package/dist/core/output/display-value.mjs +1 -0
  52. package/dist/core/output/index.d.mts +280 -0
  53. package/dist/core/output/index.mjs +2 -0
  54. package/dist/core/output/renderers.d.mts +46 -0
  55. package/dist/core/output/renderers.mjs +1 -0
  56. package/dist/core/output/writer.d.mts +40 -0
  57. package/dist/core/output/writer.mjs +1 -0
  58. package/dist/core/parse/index.d.mts +79 -0
  59. package/dist/core/parse/index.mjs +1 -0
  60. package/dist/core/prompt/index.d.mts +205 -0
  61. package/dist/core/prompt/index.mjs +6 -0
  62. package/dist/core/resolve/args.d.mts +8 -0
  63. package/dist/core/resolve/args.mjs +1 -0
  64. package/dist/core/resolve/coerce.d.mts +22 -0
  65. package/dist/core/resolve/coerce.mjs +1 -0
  66. package/dist/core/resolve/config.d.mts +10 -0
  67. package/dist/core/resolve/config.mjs +1 -0
  68. package/dist/core/resolve/contracts.d.mts +112 -0
  69. package/dist/core/resolve/errors.d.mts +11 -0
  70. package/dist/core/resolve/errors.mjs +2 -0
  71. package/dist/core/resolve/flags.d.mts +10 -0
  72. package/dist/core/resolve/flags.mjs +1 -0
  73. package/dist/core/resolve/index.d.mts +42 -0
  74. package/dist/core/resolve/index.mjs +1 -0
  75. package/dist/core/resolve/property.d.mts +47 -0
  76. package/dist/core/resolve/property.mjs +1 -0
  77. package/dist/core/schema/activity.d.mts +169 -0
  78. package/dist/core/schema/arg.d.mts +559 -0
  79. package/dist/core/schema/arg.mjs +1 -0
  80. package/dist/core/schema/command.d.mts +960 -0
  81. package/dist/core/schema/command.mjs +1 -0
  82. package/dist/core/schema/flag.d.mts +491 -0
  83. package/dist/core/schema/flag.mjs +1 -0
  84. package/dist/core/schema/index.d.mts +8 -0
  85. package/dist/core/schema/middleware.d.mts +122 -0
  86. package/dist/core/schema/middleware.mjs +1 -0
  87. package/dist/core/schema/prompt.d.mts +117 -0
  88. package/dist/core/schema/run.d.mts +171 -0
  89. package/dist/core/schema-dsl/runtime.d.mts +144 -0
  90. package/dist/core/schema-dsl/runtime.mjs +2 -0
  91. package/dist/core/schema-dsl/to-json-schema.d.mts +30 -0
  92. package/dist/core/schema-dsl/to-json-schema.mjs +1 -0
  93. package/dist/core/testkit/index.d.mts +54 -0
  94. package/dist/core/testkit/index.mjs +1 -0
  95. package/dist/index.d.mts +28 -920
  96. package/dist/index.mjs +1 -10
  97. package/dist/runtime/adapter.d.mts +212 -0
  98. package/dist/{adapter-B37d9oia.mjs → runtime/adapter.mjs} +1 -1
  99. package/dist/runtime/auto.d.mts +26 -0
  100. package/dist/runtime/auto.mjs +1 -0
  101. package/dist/runtime/bun.d.mts +28 -0
  102. package/dist/runtime/bun.mjs +1 -0
  103. package/dist/runtime/deno.d.mts +76 -0
  104. package/dist/runtime/deno.mjs +2 -0
  105. package/dist/runtime/detect.d.mts +86 -0
  106. package/dist/runtime/detect.mjs +1 -0
  107. package/dist/runtime/index.d.mts +7 -0
  108. package/dist/runtime/node.d.mts +65 -0
  109. package/dist/runtime/node.mjs +2 -0
  110. package/dist/runtime/paths.d.mts +31 -0
  111. package/dist/runtime/paths.mjs +1 -0
  112. package/dist/runtime/support.d.mts +42 -0
  113. package/dist/runtime/support.mjs +1 -0
  114. package/dist/runtime.d.mts +6 -252
  115. package/dist/runtime.mjs +1 -1
  116. package/dist/testkit.d.mts +5 -24
  117. package/dist/testkit.mjs +1 -1
  118. package/dist/version.d.mts +16 -0
  119. package/dist/version.mjs +1 -0
  120. package/dreamcli.schema.json +338 -0
  121. package/examples/basic.ts +2 -2
  122. package/examples/gh/package.json +7 -11
  123. package/examples/gh/src/commands/auth.ts +2 -2
  124. package/examples/gh/src/commands/issue.ts +4 -4
  125. package/examples/gh/src/commands/pr.ts +4 -4
  126. package/examples/gh/src/docs.ts +11 -0
  127. package/examples/gh/src/lib/auth.ts +1 -1
  128. package/examples/gh/src/main.test.ts +6 -5
  129. package/examples/gh/src/main.ts +8 -6
  130. package/examples/interactive.ts +3 -3
  131. package/examples/json-mode.ts +4 -6
  132. package/examples/middleware.ts +3 -3
  133. package/examples/multi-command.ts +3 -3
  134. package/examples/spinner-progress.ts +5 -5
  135. package/examples/testing.ts +8 -6
  136. package/package.json +70 -44
  137. package/src/core/cli/dispatch.ts +4 -0
  138. package/src/core/cli/index.ts +185 -632
  139. package/src/core/cli/planner.ts +413 -0
  140. package/src/core/cli/plugin.ts +7 -1
  141. package/src/core/cli/propagate.ts +1 -1
  142. package/src/core/cli/runtime-preflight.ts +409 -0
  143. package/src/core/completion/index.ts +15 -9
  144. package/src/core/completion/shells/bash.ts +6 -3
  145. package/src/core/completion/shells/fish.ts +245 -10
  146. package/src/core/completion/shells/powershell.ts +390 -9
  147. package/src/core/completion/shells/shared.ts +4 -4
  148. package/src/core/completion/shells/zsh.ts +12 -7
  149. package/src/core/config/index.ts +7 -4
  150. package/src/core/config/package-json.ts +6 -2
  151. package/src/core/errors/index.ts +23 -8
  152. package/src/core/execution/index.ts +270 -0
  153. package/src/core/help/index.ts +13 -15
  154. package/src/core/json-schema/index.ts +193 -7
  155. package/src/core/json-schema/meta-descriptions.generated.ts +202 -0
  156. package/src/core/output/contracts.ts +194 -0
  157. package/src/core/output/index.ts +47 -82
  158. package/src/core/output/renderers.ts +125 -0
  159. package/src/core/parse/index.ts +39 -21
  160. package/src/core/prompt/index.ts +44 -27
  161. package/src/core/resolve/args.ts +144 -0
  162. package/src/core/resolve/coerce.ts +432 -0
  163. package/src/core/resolve/config.ts +26 -0
  164. package/src/core/resolve/contracts.ts +135 -0
  165. package/src/core/resolve/errors.ts +227 -0
  166. package/src/core/resolve/flags.ts +205 -0
  167. package/src/core/resolve/index.ts +41 -1264
  168. package/src/core/resolve/property.ts +99 -0
  169. package/src/core/schema/activity.ts +3 -0
  170. package/src/core/schema/arg.ts +26 -14
  171. package/src/core/schema/command.ts +265 -38
  172. package/src/core/schema/flag.ts +120 -15
  173. package/src/core/schema/index.ts +11 -2
  174. package/src/core/schema/middleware.ts +6 -6
  175. package/src/core/schema/prompt.ts +9 -1
  176. package/src/core/schema/run.ts +25 -17
  177. package/src/core/schema-dsl/index.ts +109 -0
  178. package/src/core/schema-dsl/parse.ts +262 -0
  179. package/src/core/schema-dsl/runtime.ts +609 -0
  180. package/src/core/schema-dsl/to-json-schema.ts +102 -0
  181. package/src/core/testkit/index.ts +55 -297
  182. package/src/index.ts +10 -4
  183. package/src/runtime/adapter.ts +13 -10
  184. package/src/runtime/auto.ts +3 -3
  185. package/src/runtime/bun.ts +4 -4
  186. package/src/runtime/deno.ts +43 -29
  187. package/src/runtime/detect.ts +4 -1
  188. package/src/runtime/index.ts +1 -1
  189. package/src/runtime/node.ts +43 -21
  190. package/src/runtime/paths.ts +9 -3
  191. package/src/runtime/support.ts +20 -4
  192. package/src/runtime.ts +1 -1
  193. package/src/testkit.ts +10 -8
  194. package/dist/adapter-CCSh5juX.cjs +0 -1
  195. package/dist/adapter-DIwO-q7K.d.mts +0 -3447
  196. package/dist/adapter-DQnxxLiE.d.cts +0 -3447
  197. package/dist/auto-5cjZaF9V.mjs +0 -3
  198. package/dist/auto-B0eSgoDw.cjs +0 -3
  199. package/dist/index.cjs +0 -10
  200. package/dist/index.d.cts +0 -920
  201. package/dist/runtime.cjs +0 -1
  202. package/dist/runtime.d.cts +0 -253
  203. package/dist/testkit-CEDYPvhF.mjs +0 -14
  204. package/dist/testkit-ClIKijxC.cjs +0 -14
  205. package/dist/testkit.cjs +0 -1
  206. package/dist/testkit.d.cts +0 -25
  207. package/examples/gh/tsconfig.json +0 -37
  208. package/examples/tsconfig.json +0 -17
  209. package/src/core/cli/AGENTS.md +0 -72
  210. package/src/core/completion/AGENTS.md +0 -72
  211. package/src/core/completion/completion-test-helpers.ts +0 -48
  212. package/src/core/output/AGENTS.md +0 -69
  213. package/src/core/resolve/AGENTS.md +0 -69
  214. package/src/core/schema/AGENTS.md +0 -61
  215. package/src/core/testkit/AGENTS.md +0 -55
  216. package/src/runtime/AGENTS.md +0 -74
  217. package/src/runtime/test-helpers.ts +0 -40
@@ -6,157 +6,36 @@
6
6
  * between CLI and default.
7
7
  * v0.3 adds: **prompt resolution** between config and default.
8
8
  *
9
- * The resolver takes raw `ParseResult` (from the parser) and a
10
- * `CommandSchema`, applies the resolution chain, and validates
9
+ * The resolver takes raw {@linkcode ParseResult} (from the parser) and a
10
+ * {@linkcode CommandSchema}, applies the resolution chain, and validates
11
11
  * that all required flags/args are present. On success it returns a
12
- * `ResolveResult` with fully resolved values; on failure it throws
13
- * `ValidationError`.
12
+ * {@linkcode ResolveResult} with fully resolved values; on failure it throws
13
+ * {@linkcode ValidationError}.
14
14
  *
15
15
  * @module dreamcli/core/resolve
16
16
  */
17
17
 
18
- import type { ValidationErrorCode } from '#internals/core/errors/index.ts';
19
- import { ValidationError } from '#internals/core/errors/index.ts';
18
+ import { isValidationError, type ValidationError } from '#internals/core/errors/index.ts';
20
19
  import type { ParseResult } from '#internals/core/parse/index.ts';
21
- import type { PromptEngine } from '#internals/core/prompt/index.ts';
22
- import { resolvePromptConfig } from '#internals/core/prompt/index.ts';
23
- import type {
24
- ArgSchema,
25
- CommandArgEntry,
26
- CommandSchema,
27
- ErasedInteractiveResolver,
28
- FlagSchema,
29
- } from '#internals/core/schema/index.ts';
30
- import type { PromptConfig } from '#internals/core/schema/prompt.ts';
31
-
32
- // --- Resolve options — injectable external state for the resolution chain
33
-
34
- /**
35
- * Options controlling the resolution chain.
36
- *
37
- * These provide external state (env vars, config objects) that the resolver
38
- * reads from when CLI-provided values are absent.
39
- */
40
- interface ResolveOptions {
41
- /**
42
- * Full stdin contents for args configured with `.stdin()`.
43
- *
44
- * When an arg has `stdinMode: true`, resolution checks this value after
45
- * CLI argv and before env/default. `null` means stdin was checked but no
46
- * piped data was available.
47
- */
48
- readonly stdinData?: string | null;
49
-
50
- /**
51
- * Environment variables to resolve against.
52
- *
53
- * For each flag with `schema.envVar` set, the resolver looks up the
54
- * env var value here. Values are coerced to the flag's declared kind.
55
- *
56
- * @example
57
- * ```ts
58
- * resolve(schema, parsed, { env: { DEPLOY_REGION: 'eu' } })
59
- * ```
60
- */
61
- readonly env?: Readonly<Record<string, string | undefined>>;
62
-
63
- /**
64
- * Configuration object to resolve against.
65
- *
66
- * For each flag with `schema.configPath` set, the resolver looks up the
67
- * value at the dotted path (e.g. `'deploy.region'`). Config values may
68
- * already be typed (number, boolean, array) so coercion is lenient —
69
- * only validates kind compatibility rather than string-parsing.
70
- *
71
- * Config is plain JSON — file loading is the caller's responsibility.
72
- *
73
- * @example
74
- * ```ts
75
- * resolve(schema, parsed, { config: { deploy: { region: 'eu' } } })
76
- * ```
77
- */
78
- readonly config?: Readonly<Record<string, unknown>>;
79
-
80
- /**
81
- * Prompt engine for interactive flag resolution.
82
- *
83
- * When provided, flags with `schema.prompt` configured that have no
84
- * value after CLI/env/config resolution will be prompted interactively.
85
- *
86
- * When absent (or in non-interactive contexts), prompting is skipped
87
- * and resolution falls through to default/required.
88
- *
89
- * @example
90
- * ```ts
91
- * resolve(schema, parsed, { prompter: createTestPrompter(['eu']) })
92
- * ```
93
- */
94
- readonly prompter?: PromptEngine;
95
- }
96
-
97
- // --- Result type
98
-
99
- /**
100
- * Fully resolved flag and arg values — guaranteed present for required
101
- * and defaulted entries.
102
- *
103
- * At runtime the maps are `Record<string, unknown>` because the generic
104
- * type info lives in the builder phantom types, not here. Type narrowing
105
- * happens at the `CommandBuilder.action()` boundary via `InferFlags`/
106
- * `InferArgs`.
107
- */
108
- interface ResolveResult {
109
- /** Resolved flag values keyed by canonical flag name. */
110
- readonly flags: Readonly<Record<string, unknown>>;
111
- /** Resolved arg values keyed by arg name. */
112
- readonly args: Readonly<Record<string, unknown>>;
113
- /**
114
- * Deprecation notices for flags/args that were explicitly provided.
115
- *
116
- * Populated when a deprecated flag or arg receives a value from any
117
- * explicit source (CLI, env, config, prompt). Not populated for
118
- * default fallthrough.
119
- *
120
- * Consumers decide how to render these — the resolve layer provides
121
- * structured data, not formatted strings.
122
- */
123
- readonly deprecations: readonly DeprecationWarning[];
124
- }
125
-
126
- /**
127
- * Structured deprecation notice emitted when a deprecated flag or arg
128
- * is explicitly provided.
129
- *
130
- * Consumers (testkit, CLI layer) decide formatting. The resolve layer
131
- * only collects facts.
132
- */
133
- interface DeprecationWarning {
134
- /** Whether the deprecated entity is a flag or a positional arg. */
135
- readonly kind: 'flag' | 'arg';
136
- /** Canonical name of the flag or arg. */
137
- readonly name: string;
138
- /**
139
- * Deprecation reason/migration guidance, or `true` for generic
140
- * deprecation with no specific message.
141
- */
142
- readonly message: string | true;
143
- }
144
-
145
- // --- Resolver
20
+ import type { CommandSchema } from '#internals/core/schema/index.ts';
21
+ import { resolveArgs } from './args.ts';
22
+ import type { DeprecationWarning, ResolveOptions, ResolveResult } from './contracts.ts';
23
+ import { collectValidationErrors, isNonEmpty, throwAggregatedErrors } from './errors.ts';
24
+ import { resolveFlags } from './flags.ts';
146
25
 
147
26
  /**
148
27
  * Resolve parsed values against a command schema.
149
28
  *
150
29
  * Low-level API: most applications should rely on `cli().run()`, `.execute()`,
151
- * or `runCommand()`, which already call `resolve()` at the right time. Reach
152
- * for this function when testing precedence rules directly or building custom
153
- * execution flows around `CommandSchema`.
30
+ * or `runCommand()`, which already call {@linkcode resolve} at the right time.
31
+ * Reach for this function when testing precedence rules directly or building
32
+ * custom execution flows around {@linkcode CommandSchema}.
154
33
  *
155
34
  * Resolution order:
156
- * 1. CLI parsed value (from `ParseResult`)
157
- * 2. Env variable (from `ResolveOptions.env`, if flag declares `envVar`)
158
- * 3. Config value (from `ResolveOptions.config`, if flag declares `configPath`)
159
- * 4. Prompt (from `ResolveOptions.prompter`, if flag declares `prompt`)
35
+ * 1. CLI parsed value (from {@linkcode ParseResult})
36
+ * 2. Env variable (from {@linkcode ResolveOptions.env}, if flag declares `envVar`)
37
+ * 3. Config value (from {@linkcode ResolveOptions.config}, if flag declares `configPath`)
38
+ * 4. Prompt (from {@linkcode ResolveOptions.prompter}, if flag declares `prompt`)
160
39
  * 5. Default value (from schema)
161
40
  *
162
41
  * After resolution, validates that all required flags and args have
@@ -167,7 +46,7 @@ interface DeprecationWarning {
167
46
  * @param parsed - Raw parsed values from the parser
168
47
  * @param options - External state for the resolution chain
169
48
  * @returns Fully resolved flag and arg values
170
- * @throws ValidationError if any required flag or arg is missing,
49
+ * @throws {@linkcode ValidationError} if any required flag or arg is missing,
171
50
  * or if an env/config value fails coercion
172
51
  *
173
52
  * @example
@@ -188,1144 +67,42 @@ async function resolve(
188
67
  const config = options?.config ?? {};
189
68
  const prompter = options?.prompter;
190
69
  const deprecations: DeprecationWarning[] = [];
191
- const flags = await resolveFlags(
192
- schema.flags,
193
- parsed.flags,
194
- env,
195
- config,
196
- prompter,
197
- schema.interactive,
198
- deprecations,
199
- );
200
- const args = resolveArgs(schema.args, parsed.args, stdinData, env, deprecations);
201
- return { flags, args, deprecations };
202
- }
203
-
204
- // --- Flag resolution
205
-
206
- /**
207
- * Resolve flag values: CLI -> env -> config -> interactive/prompt -> default,
208
- * then validate required.
209
- *
210
- * Two-pass approach when a command-level interactive resolver is present:
211
- *
212
- * **Pass 1 (all flags):** Resolve from CLI → env → config. Collect partially
213
- * resolved values and track which flags still need values.
214
- *
215
- * **Interactive resolver call:** If the command has an `.interactive()` resolver,
216
- * call it with the partially resolved flags. It returns prompt configs for
217
- * flags it wants to prompt, overriding/supplementing per-flag `.prompt()` configs.
218
- *
219
- * **Pass 2 (unresolved flags):** For each unresolved flag:
220
- * 1. If interactive resolver returned a `PromptConfig` for it → use that config
221
- * 2. Else if the flag has a per-flag `.prompt()` config → use it
222
- * 3. Else → fall through to default/required validation
223
- *
224
- * Without an interactive resolver, behaviour is identical to the single-pass
225
- * approach (per-flag prompt configs used directly).
226
- *
227
- * Optional array flags that were not provided and have no explicit default get
228
- * an empty array `[]` (more useful than `undefined` for consumers). Required
229
- * array flags still fail validation when no source resolves them.
230
- *
231
- * @param flagSchemas - Flag schemas keyed by canonical name
232
- * @param parsedFlags - Raw parsed values from the parser (CLI source)
233
- * @param env - Environment variables to resolve against
234
- * @param config - Configuration object to resolve against
235
- * @param prompter - Prompt engine for interactive resolution (may be `undefined`)
236
- * @param interactive - Command-level interactive resolver (may be `undefined`)
237
- * @param deprecations - Mutable array to collect deprecation warnings into
238
- * @returns Fully resolved flag values keyed by canonical name
239
- */
240
- async function resolveFlags(
241
- flagSchemas: Readonly<Record<string, FlagSchema>>,
242
- parsedFlags: Readonly<Record<string, unknown>>,
243
- env: Readonly<Record<string, string | undefined>>,
244
- config: Readonly<Record<string, unknown>>,
245
- prompter: PromptEngine | undefined,
246
- interactive: ErasedInteractiveResolver | undefined,
247
- deprecations: DeprecationWarning[],
248
- ): Promise<Readonly<Record<string, unknown>>> {
249
- const resolved: Record<string, unknown> = {};
70
+ let flags: Readonly<Record<string, unknown>> = {};
71
+ let args: Readonly<Record<string, unknown>> = {};
250
72
  const errors: ValidationError[] = [];
251
73
 
252
- // Track flags that had hard coercion errors during CLI/env/config — these
253
- // should NOT be prompted or defaulted (the error is authoritative).
254
- const hardErrorFlags = new Set<string>();
255
-
256
- // -- Pass 1: CLI → env → config -------------------------------------------
257
- for (const [name, schema] of Object.entries(flagSchemas)) {
258
- const parsedValue = parsedFlags[name];
259
-
260
- if (parsedValue !== undefined) {
261
- if (schema.deprecated !== undefined) {
262
- deprecations.push({ kind: 'flag', name, message: schema.deprecated });
263
- }
264
- resolved[name] = parsedValue;
265
- continue;
266
- }
267
-
268
- if (schema.envVar !== undefined) {
269
- const envValue = env[schema.envVar];
270
- if (envValue !== undefined) {
271
- const coerced = coerceValue(name, { kind: 'env', envVar: schema.envVar }, envValue, schema);
272
- if (coerced.ok) {
273
- if (schema.deprecated !== undefined) {
274
- deprecations.push({ kind: 'flag', name, message: schema.deprecated });
275
- }
276
- resolved[name] = coerced.value;
277
- continue;
278
- }
279
- errors.push(coerced.error);
280
- hardErrorFlags.add(name);
281
- continue;
282
- }
283
- }
284
-
285
- if (schema.configPath !== undefined) {
286
- const configValue = resolveConfigPath(config, schema.configPath);
287
- if (configValue !== undefined) {
288
- const coerced = coerceValue(
289
- name,
290
- { kind: 'config', configPath: schema.configPath },
291
- configValue,
292
- schema,
293
- );
294
- if (coerced.ok) {
295
- if (schema.deprecated !== undefined) {
296
- deprecations.push({ kind: 'flag', name, message: schema.deprecated });
297
- }
298
- resolved[name] = coerced.value;
299
- continue;
300
- }
301
- errors.push(coerced.error);
302
- hardErrorFlags.add(name);
303
- }
304
- }
305
-
306
- // Not yet resolved — will be handled in pass 2
307
- }
308
-
309
- // -- Interactive resolver call (v0.3) ------------------------------------
310
- // Call the command-level interactive resolver with partially resolved flags.
311
- // It returns prompt configs for flags it wants prompted.
312
- const interactiveConfigs =
313
- interactive !== undefined ? interactive({ flags: resolved }) : undefined;
314
-
315
- // -- Pass 2: prompt → default → required ----------------------------------
316
- for (const [name, schema] of Object.entries(flagSchemas)) {
317
- // Already resolved in pass 1 or had a hard error
318
- if (name in resolved || hardErrorFlags.has(name)) {
319
- continue;
320
- }
321
-
322
- // Determine which prompt config to use for this flag:
323
- //
324
- // The interactive resolver returns a record where each key maps to:
325
- // - a PromptConfig → use it (overrides per-flag)
326
- // - `false` → explicitly suppress prompting for this flag
327
- // - undefined/null (or key absent) → fall back to per-flag .prompt() config
328
- //
329
- // The `false` suppression matches the idiomatic `&&` pattern from the PRD:
330
- // `region: !flags.region && { kind: 'select', ... }`
331
- // When `flags.region` is truthy, `&&` evaluates to `false`.
332
- const interactiveConfig = interactiveConfigs?.[name];
333
-
334
- let effectivePromptConfig: PromptConfig | undefined;
335
- if (
336
- interactiveConfig !== undefined &&
337
- interactiveConfig !== null &&
338
- interactiveConfig !== false &&
339
- interactiveConfig !== 0 &&
340
- interactiveConfig !== ''
341
- ) {
342
- // Interactive returned a PromptConfig — use it
343
- effectivePromptConfig = interactiveConfig;
344
- } else if (interactiveConfig === false) {
345
- // Interactive explicitly returned false — suppress prompting
346
- effectivePromptConfig = undefined;
347
- } else {
348
- // undefined, null, 0, '', or not mentioned — fall back to per-flag
349
- effectivePromptConfig = schema.prompt;
350
- }
351
-
352
- if (effectivePromptConfig !== undefined && prompter !== undefined) {
353
- const promptResult = await resolvePromptValueWithConfig(
354
- name,
355
- schema,
356
- effectivePromptConfig,
357
- prompter,
358
- );
359
- if (promptResult.ok) {
360
- if (schema.deprecated !== undefined) {
361
- deprecations.push({ kind: 'flag', name, message: schema.deprecated });
362
- }
363
- resolved[name] = promptResult.value;
364
- continue;
365
- }
366
- if (promptResult.error !== undefined) {
367
- errors.push(promptResult.error);
368
- continue;
369
- }
370
- // Prompt was cancelled or not answered — fall through to default/required
371
- }
372
-
373
- if (schema.defaultValue !== undefined) {
374
- resolved[name] = schema.defaultValue;
375
- continue;
376
- }
377
-
378
- if (schema.kind === 'array' && schema.presence !== 'required') {
379
- resolved[name] = [];
380
- continue;
381
- }
382
-
383
- if (schema.presence === 'required') {
384
- const details: Record<string, unknown> = { flag: name, kind: schema.kind };
385
- if (schema.envVar !== undefined) details.envVar = schema.envVar;
386
- if (schema.configPath !== undefined) details.configPath = schema.configPath;
387
- errors.push(
388
- new ValidationError(`Missing required flag --${name}`, {
389
- code: 'REQUIRED_FLAG',
390
- details,
391
- suggest: buildRequiredFlagSuggest(name, schema),
392
- }),
393
- );
394
- continue;
395
- }
396
-
397
- // Optional with no default — explicitly set undefined so the key exists
398
- // in the result object (consistent shape for consumers)
399
- resolved[name] = undefined;
400
- }
401
-
402
- if (isNonEmpty(errors)) {
403
- throwAggregatedErrors(errors);
404
- }
405
-
406
- return resolved;
407
- }
408
-
409
- // --- Prompt value resolution
410
-
411
- /**
412
- * Result of attempting to resolve a flag value via prompting.
413
- *
414
- * Three outcomes:
415
- * - `ok: true` — prompt answered, value coerced successfully
416
- * - `ok: false, error: ValidationError` — prompt answered but coercion failed
417
- * - `ok: false, error: undefined` — prompt cancelled or not answered (fall through)
418
- */
419
- type PromptResolveResult =
420
- | { readonly ok: true; readonly value: unknown }
421
- | { readonly ok: false; readonly error: ValidationError | undefined };
422
-
423
- /**
424
- * Prompt the user for a flag value using an explicit prompt config.
425
- *
426
- * Used by both per-flag prompt resolution and command-level interactive
427
- * resolver prompt resolution. The config may come from `schema.prompt`
428
- * or from the interactive resolver's returned prompt configs.
429
- *
430
- * Prepares a `ResolvedPromptConfig` (merging enum values from the flag
431
- * schema), calls the engine, and coerces the raw answer to the flag's
432
- * declared kind.
433
- *
434
- * @param flagName - Canonical flag name (for error messages)
435
- * @param schema - Flag schema declaring the expected kind
436
- * @param promptConfig - Prompt configuration to use
437
- * @param prompter - Prompt engine to call
438
- * @returns Three-state {@link PromptResolveResult}: value, coercion error, or cancelled
439
- */
440
- async function resolvePromptValueWithConfig(
441
- flagName: string,
442
- schema: FlagSchema,
443
- promptConfig: PromptConfig,
444
- prompter: PromptEngine,
445
- ): Promise<PromptResolveResult> {
446
- const resolvedConfig = resolvePromptConfig(promptConfig, schema.enumValues);
447
- const result = await prompter.promptOne(resolvedConfig);
448
-
449
- if (!result.answered) {
450
- // User cancelled — fall through to default/required
451
- return { ok: false, error: undefined };
452
- }
453
-
454
- // Coerce the prompt value to the flag's kind
455
- return coerceValue(flagName, { kind: 'prompt' }, result.value, schema);
456
- }
457
-
458
- // --- Required flag suggestion builder
459
-
460
- /**
461
- * Build an actionable suggestion listing all configured resolution sources
462
- * for a required flag that was not provided.
463
- *
464
- * Generates CI-friendly hints like:
465
- * - `"Provide --region <value>, set DEPLOY_REGION, or add deploy.region to config"`
466
- * - `"Provide --force"` (boolean, no env/config)
467
- *
468
- * The ordering mirrors the resolution chain: CLI → env → config.
469
- *
470
- * @param name - Canonical flag name
471
- * @param schema - {@link FlagSchema} for the missing flag
472
- * @returns Human-readable suggestion string
473
- */
474
- function buildRequiredFlagSuggest(name: string, schema: FlagSchema): string {
475
- const sources: string[] = [];
476
-
477
- // CLI source (always present)
478
- sources.push(`Provide --${name}${schema.kind !== 'boolean' ? ' <value>' : ''}`);
479
-
480
- // Env source (if configured)
481
- if (schema.envVar !== undefined) {
482
- sources.push(`set ${schema.envVar}`);
483
- }
484
-
485
- // Config source (if configured)
486
- if (schema.configPath !== undefined) {
487
- sources.push(`add ${schema.configPath} to config`);
488
- }
489
-
490
- // Join with natural language connectors: "A", "A or B", "A, B, or C"
491
- if (sources.length <= 1) {
492
- return sources.join('');
493
- }
494
- const rest = sources.slice(0, -1);
495
- const last = sources.slice(-1).join('');
496
- return sources.length === 2 ? `${rest.join('')} or ${last}` : `${rest.join(', ')}, or ${last}`;
497
- }
498
-
499
- // --- Unified value coercion
500
-
501
- /**
502
- * Describes the source of a raw value being coerced.
503
- *
504
- * Used to parameterize error messages, source-specific details, and
505
- * minor behavioral differences (prompt accepts 'y'/'n', trims array
506
- * elements) in the unified {@link coerceValue} function.
507
- */
508
- type CoerceSource =
509
- | { readonly kind: 'env'; readonly envVar: string }
510
- | { readonly kind: 'config'; readonly configPath: string }
511
- | { readonly kind: 'prompt' };
512
-
513
- /**
514
- * Result of attempting to coerce a raw value to a flag's declared kind.
515
- *
516
- * Two-state discriminated union: `ok: true` carries the coerced value,
517
- * `ok: false` carries a `ValidationError` describing the mismatch.
518
- *
519
- * The prompt caller wraps this in a three-state result at its own call
520
- * site (adding the `error: undefined` "cancelled" case).
521
- */
522
- type CoerceResult =
523
- | { readonly ok: true; readonly value: unknown }
524
- | { readonly ok: false; readonly error: ValidationError };
525
-
526
- /**
527
- * Format a source label for error messages (e.g. "from env MY_VAR", "from config deploy.region").
528
- *
529
- * @param source - {@link CoerceSource} to format
530
- * @returns Human-readable source label
531
- */
532
- function sourceLabel(source: CoerceSource): string {
533
- switch (source.kind) {
534
- case 'env':
535
- return `from env ${source.envVar}`;
536
- case 'config':
537
- return `from config ${source.configPath}`;
538
- case 'prompt':
539
- return 'from prompt';
540
- }
541
- }
542
-
543
- /**
544
- * Build source-specific detail keys for error objects.
545
- *
546
- * @param source - {@link CoerceSource} to extract details from
547
- * @returns Record with source-identifying keys
548
- */
549
- function sourceDetails(source: CoerceSource): Record<string, unknown> {
550
- switch (source.kind) {
551
- case 'env':
552
- return { envVar: source.envVar };
553
- case 'config':
554
- return { configPath: source.configPath };
555
- case 'prompt':
556
- return { source: 'prompt' };
557
- }
558
- }
559
-
560
- /**
561
- * Build a coercion error with source-aware message and details.
562
- *
563
- * @param flagName - Canonical flag name
564
- * @param source - {@link CoerceSource} where the value originated
565
- * @param code - Validation error code
566
- * @param expected - Expected type label
567
- * @param raw - Raw value that failed coercion
568
- * @param messageSuffix - Error message prefix (source label is appended)
569
- * @param suggest - Actionable suggestion for the user
570
- * @param extraDetails - Additional detail keys merged into the error
571
- * @returns Failure {@link CoerceResult} wrapping the error
572
- */
573
- function coercionError(
574
- flagName: string,
575
- source: CoerceSource,
576
- code: ValidationErrorCode,
577
- expected: string,
578
- raw: unknown,
579
- messageSuffix: string,
580
- suggest: string,
581
- extraDetails?: Record<string, unknown>,
582
- ): CoerceResult {
583
- return {
584
- ok: false,
585
- error: new ValidationError(`${messageSuffix} ${sourceLabel(source)} for flag --${flagName}`, {
586
- code,
587
- details: { flag: flagName, ...sourceDetails(source), value: raw, expected, ...extraDetails },
588
- suggest,
589
- }),
590
- };
591
- }
592
-
593
- /**
594
- * Coerce a raw value to the flag's declared kind.
595
- *
596
- * Unified coercion for all three resolution sources (env, config, prompt).
597
- * Behavioral differences are parameterized by the {@link CoerceSource}:
598
- *
599
- * - **String leniency**: env input is always `string` (passthrough); config
600
- * accepts `number | boolean` via `String()`; prompt accepts anything.
601
- * - **Boolean truthy/falsy**: prompt additionally accepts `'y'` / `'n'`.
602
- * - **Number NaN guard**: unconditional on numeric input (fixes a latent
603
- * bug where prompt previously lacked this check).
604
- * - **Array trim**: prompt trims whitespace after comma-split.
605
- *
606
- * @param flagName - Canonical flag name (for error messages)
607
- * @param source - Where the raw value came from (env/config/prompt)
608
- * @param raw - Raw value to coerce
609
- * @param schema - Flag schema declaring the expected kind
610
- * @returns {@link CoerceResult} — success with coerced value or failure with error
611
- */
612
- function coerceValue(
613
- flagName: string,
614
- source: CoerceSource,
615
- raw: unknown,
616
- schema: FlagSchema,
617
- ): CoerceResult {
618
- switch (schema.kind) {
619
- case 'string': {
620
- if (typeof raw === 'string') return { ok: true, value: raw };
621
- // Env input is always string — non-string paths only apply to config/prompt
622
- if (source.kind === 'prompt') return { ok: true, value: String(raw) };
623
- if (source.kind === 'config' && (typeof raw === 'number' || typeof raw === 'boolean')) {
624
- return { ok: true, value: String(raw) };
625
- }
626
- return coercionError(
627
- flagName,
628
- source,
629
- 'TYPE_MISMATCH',
630
- 'string',
631
- raw,
632
- 'Invalid string value',
633
- source.kind === 'config'
634
- ? `Set ${source.configPath} to a string in your config`
635
- : `Enter a valid string for --${flagName}`,
636
- );
637
- }
638
-
639
- case 'number': {
640
- if (typeof raw === 'number') {
641
- // Guard against NaN on numeric input (all sources)
642
- if (Number.isNaN(raw)) {
643
- return coercionError(
644
- flagName,
645
- source,
646
- 'TYPE_MISMATCH',
647
- 'number',
648
- raw,
649
- 'Invalid number value NaN',
650
- source.kind === 'env'
651
- ? `Set ${source.envVar} to a valid number`
652
- : source.kind === 'config'
653
- ? `Set ${source.configPath} to a valid number in your config`
654
- : `Enter a valid number for --${flagName}`,
655
- );
656
- }
657
- return { ok: true, value: raw };
658
- }
659
- if (typeof raw === 'string') {
660
- const n = Number(raw);
661
- if (!Number.isNaN(n)) return { ok: true, value: n };
662
- }
663
- return coercionError(
664
- flagName,
665
- source,
666
- 'TYPE_MISMATCH',
667
- 'number',
668
- raw,
669
- typeof raw === 'string' ? `Invalid number value '${raw}'` : 'Invalid number value',
670
- source.kind === 'env'
671
- ? `Set ${source.envVar} to a valid number`
672
- : source.kind === 'config'
673
- ? `Set ${source.configPath} to a valid number in your config`
674
- : `Enter a valid number for --${flagName}`,
675
- );
676
- }
677
-
678
- case 'boolean': {
679
- if (typeof raw === 'boolean') return { ok: true, value: raw };
680
- if (typeof raw === 'string') {
681
- const lower = raw.toLowerCase();
682
- const truthy =
683
- lower === 'true' ||
684
- lower === '1' ||
685
- lower === 'yes' ||
686
- (source.kind === 'prompt' && lower === 'y');
687
- if (truthy) return { ok: true, value: true };
688
- const falsy =
689
- lower === 'false' ||
690
- lower === '0' ||
691
- lower === 'no' ||
692
- lower === '' ||
693
- (source.kind === 'prompt' && lower === 'n');
694
- if (falsy) return { ok: true, value: false };
695
- }
696
- return coercionError(
697
- flagName,
698
- source,
699
- 'TYPE_MISMATCH',
700
- 'boolean',
701
- raw,
702
- typeof raw === 'string' ? `Invalid boolean value '${raw}'` : 'Invalid boolean value',
703
- source.kind === 'env'
704
- ? `Set ${source.envVar} to true/false, 1/0, or yes/no`
705
- : source.kind === 'config'
706
- ? `Set ${source.configPath} to true or false in your config`
707
- : `Answer yes or no for --${flagName}`,
708
- );
709
- }
710
-
711
- case 'enum': {
712
- const allowed = schema.enumValues ?? [];
713
- if (typeof raw === 'string' && allowed.includes(raw)) {
714
- return { ok: true, value: raw };
715
- }
716
- return {
717
- ok: false,
718
- error: new ValidationError(
719
- `Invalid value '${String(raw)}' ${sourceLabel(source)} for flag --${flagName}. Allowed: ${allowed.join(', ')}`,
720
- {
721
- code: 'INVALID_ENUM',
722
- details: { flag: flagName, ...sourceDetails(source), value: raw, allowed },
723
- suggest:
724
- source.kind === 'env'
725
- ? `Set ${source.envVar} to one of: ${allowed.join(', ')}`
726
- : source.kind === 'config'
727
- ? `Set ${source.configPath} to one of: ${allowed.join(', ')}`
728
- : `Select one of: ${allowed.join(', ')}`,
729
- },
730
- ),
731
- };
732
- }
733
-
734
- case 'custom': {
735
- if (schema.parseFn) {
736
- try {
737
- return { ok: true, value: schema.parseFn(raw) };
738
- } catch (err) {
739
- const message = err instanceof Error ? err.message : String(err);
740
- const sourceRef =
741
- source.kind === 'env'
742
- ? `env ${source.envVar}`
743
- : source.kind === 'config'
744
- ? `config ${source.configPath}`
745
- : 'prompt value';
746
- return {
747
- ok: false,
748
- error: new ValidationError(
749
- `Failed to parse ${sourceRef} for flag --${flagName}: ${message}`,
750
- {
751
- code: 'TYPE_MISMATCH',
752
- details: {
753
- flag: flagName,
754
- ...sourceDetails(source),
755
- value: raw,
756
- expected: 'custom',
757
- },
758
- suggest:
759
- source.kind === 'env'
760
- ? `Set ${source.envVar} to a valid value for --${flagName}`
761
- : source.kind === 'config'
762
- ? `Set ${source.configPath} to a valid value for --${flagName} in your config`
763
- : `Enter a valid value for --${flagName}`,
764
- },
765
- ),
766
- };
767
- }
768
- }
769
- return { ok: true, value: raw };
770
- }
771
-
772
- case 'array': {
773
- // Accept actual arrays (config/prompt may provide these)
774
- if (Array.isArray(raw)) {
775
- if (schema.elementSchema) {
776
- const coerced: unknown[] = [];
777
- for (const element of raw) {
778
- const result = coerceValue(flagName, source, element, schema.elementSchema);
779
- if (!result.ok) return result;
780
- coerced.push(result.value);
781
- }
782
- return { ok: true, value: coerced };
783
- }
784
- return { ok: true, value: raw };
785
- }
786
- // Comma-separated string splitting
787
- if (typeof raw === 'string') {
788
- if (raw === '') return { ok: true, value: [] };
789
- const parts = raw.split(',');
790
- if (schema.elementSchema) {
791
- const coerced: unknown[] = [];
792
- for (const part of parts) {
793
- const element = source.kind === 'prompt' ? part.trim() : part;
794
- const result = coerceValue(flagName, source, element, schema.elementSchema);
795
- if (!result.ok) return result;
796
- coerced.push(result.value);
797
- }
798
- return { ok: true, value: coerced };
799
- }
800
- return {
801
- ok: true,
802
- value: source.kind === 'prompt' ? parts.map((p) => p.trim()) : parts,
803
- };
804
- }
805
- return coercionError(
806
- flagName,
807
- source,
808
- 'TYPE_MISMATCH',
809
- 'array',
810
- raw,
811
- 'Invalid array value',
812
- source.kind === 'env'
813
- ? `Set ${source.envVar} to comma-separated values`
814
- : source.kind === 'config'
815
- ? `Set ${source.configPath} to an array in your config`
816
- : `Provide valid values for --${flagName}`,
817
- );
74
+ try {
75
+ flags = await resolveFlags(
76
+ schema.flags,
77
+ parsed.flags,
78
+ env,
79
+ config,
80
+ prompter,
81
+ schema.interactive,
82
+ deprecations,
83
+ );
84
+ } catch (error) {
85
+ if (!isValidationError(error)) {
86
+ throw error;
818
87
  }
88
+ errors.push(...collectValidationErrors(error));
819
89
  }
820
- }
821
-
822
- // --- Config path resolution
823
-
824
- /**
825
- * Resolve a dotted path against a nested config object.
826
- *
827
- * For path `'deploy.region'` and config `{ deploy: { region: 'eu' } }`,
828
- * returns `'eu'`. Returns `undefined` if any segment is missing or
829
- * a non-object intermediate is encountered.
830
- *
831
- * @param config - Root config object
832
- * @param path - Dotted path (e.g. `'deploy.region'`)
833
- * @returns Resolved value, or `undefined` if any segment is missing
834
- */
835
- function resolveConfigPath(config: Readonly<Record<string, unknown>>, path: string): unknown {
836
- const segments = path.split('.');
837
- let current: unknown = config;
838
-
839
- for (const segment of segments) {
840
- if (current === null || current === undefined || typeof current !== 'object') {
841
- return undefined;
842
- }
843
- if (!Object.hasOwn(current, segment)) {
844
- return undefined;
845
- }
846
- current = (current as Record<string, unknown>)[segment];
847
- }
848
-
849
- return current;
850
- }
851
-
852
- // --- Arg resolution
853
-
854
- /**
855
- * Resolve arg values: CLI → stdin → env → default, then validate required.
856
- *
857
- * For each declared arg in the schema (ordered):
858
- * 1. If the parser produced a value → use it
859
- * 2. Else if `.stdin()` is enabled and stdin data is available → coerce + use
860
- * 3. Else if the arg declares `envVar` and the env record has it → coerce + use
861
- * 4. Else if the schema has a default → use it
862
- * 5. Else if variadic with no value → use `[]`
863
- * 6. Else if required → collect a validation error
864
- * 7. Else (optional) → leave absent (`undefined` when accessed)
865
- *
866
- * @param argEntries - Ordered arg schemas from the command
867
- * @param parsedArgs - Raw parsed arg values from the parser
868
- * @param stdinData - Full stdin contents, or `null`/`undefined` if unavailable
869
- * @param env - Environment variables to resolve against
870
- * @param deprecations - Mutable array to collect deprecation warnings into
871
- * @returns Fully resolved arg values keyed by arg name
872
- */
873
- function resolveArgs(
874
- argEntries: readonly CommandArgEntry[],
875
- parsedArgs: Readonly<Record<string, unknown>>,
876
- stdinData: string | null | undefined,
877
- env: Readonly<Record<string, string | undefined>>,
878
- deprecations: DeprecationWarning[],
879
- ): Readonly<Record<string, unknown>> {
880
- const resolved: Record<string, unknown> = {};
881
- const errors: ValidationError[] = [];
882
90
 
883
- for (const entry of argEntries) {
884
- const { name, schema } = entry;
885
- const parsedValue = parsedArgs[name];
886
- const usesCliValue =
887
- parsedValue !== undefined &&
888
- (!schema.stdinMode || parsedValue !== '-') &&
889
- !(schema.variadic && Array.isArray(parsedValue) && parsedValue.length === 0);
890
-
891
- if (usesCliValue) {
892
- if (schema.deprecated !== undefined) {
893
- deprecations.push({ kind: 'arg', name, message: schema.deprecated });
894
- }
895
- resolved[name] = parsedValue;
896
- continue;
897
- }
898
-
899
- if (schema.stdinMode && (parsedValue === undefined || parsedValue === '-')) {
900
- if (stdinData !== undefined && stdinData !== null) {
901
- const coerced = coerceArgStringValue(name, { kind: 'stdin' }, stdinData, schema);
902
- if (coerced.ok) {
903
- if (schema.deprecated !== undefined) {
904
- deprecations.push({ kind: 'arg', name, message: schema.deprecated });
905
- }
906
- resolved[name] = coerced.value;
907
- continue;
908
- }
909
- errors.push(coerced.error);
910
- continue;
911
- }
91
+ try {
92
+ args = resolveArgs(schema.args, parsed.args, stdinData, env, deprecations);
93
+ } catch (error) {
94
+ if (!isValidationError(error)) {
95
+ throw error;
912
96
  }
913
-
914
- // 3. Env variable
915
- if (schema.envVar !== undefined) {
916
- const envValue = env[schema.envVar];
917
- if (envValue !== undefined) {
918
- const coerced = coerceArgStringValue(
919
- name,
920
- { kind: 'env', envVar: schema.envVar },
921
- envValue,
922
- schema,
923
- );
924
- if (coerced.ok) {
925
- if (schema.deprecated !== undefined) {
926
- deprecations.push({ kind: 'arg', name, message: schema.deprecated });
927
- }
928
- resolved[name] = coerced.value;
929
- continue;
930
- }
931
- errors.push(coerced.error);
932
- continue;
933
- }
934
- }
935
-
936
- if (schema.defaultValue !== undefined) {
937
- resolved[name] = schema.defaultValue;
938
- continue;
939
- }
940
-
941
- if (schema.variadic) {
942
- // Variadic with no parsed values and no default → empty array
943
- // (unless required — then error)
944
- if (schema.presence === 'required') {
945
- errors.push(
946
- new ValidationError(`Missing required argument <${name}>`, {
947
- code: 'REQUIRED_ARG',
948
- details: { arg: name, variadic: true },
949
- suggest: buildRequiredArgSuggest(name, schema, true),
950
- }),
951
- );
952
- continue;
953
- }
954
- resolved[name] = [];
955
- continue;
956
- }
957
-
958
- if (schema.presence === 'required') {
959
- errors.push(
960
- new ValidationError(`Missing required argument <${name}>`, {
961
- code: 'REQUIRED_ARG',
962
- details: { arg: name },
963
- suggest: buildRequiredArgSuggest(name, schema),
964
- }),
965
- );
966
- continue;
967
- }
968
-
969
- // Optional with no default
970
- resolved[name] = undefined;
97
+ errors.push(...collectValidationErrors(error));
971
98
  }
972
99
 
973
100
  if (isNonEmpty(errors)) {
974
101
  throwAggregatedErrors(errors);
975
102
  }
976
103
 
977
- return resolved;
978
- }
979
-
980
- // --- Arg env coercion
981
-
982
- /**
983
- * Describes the source of a raw string being coerced for an arg.
984
- *
985
- * Arg stdin/env resolution both provide strings, but the source still affects
986
- * error messages and suggestions.
987
- */
988
-
989
- type ArgStringSource =
990
- | { readonly kind: 'env'; readonly envVar: string }
991
- | { readonly kind: 'stdin' };
992
-
993
- /**
994
- * Format an arg source label for error messages.
995
- *
996
- * @param source - {@link ArgStringSource} to format
997
- * @returns Human-readable source label
998
- */
999
- function argSourceLabel(source: ArgStringSource): string {
1000
- return source.kind === 'env' ? `from env ${source.envVar}` : 'from stdin';
1001
- }
1002
-
1003
- /**
1004
- * Build source-specific detail keys for arg error objects.
1005
- *
1006
- * @param source - {@link ArgStringSource} to extract details from
1007
- * @returns Record with source-identifying keys
1008
- */
1009
- function argSourceDetails(source: ArgStringSource): Record<string, unknown> {
1010
- return source.kind === 'env' ? { envVar: source.envVar } : { source: 'stdin' };
1011
- }
1012
-
1013
- /**
1014
- * Build an arg coercion suggestion based on source and expected kind.
1015
- *
1016
- * @param argName - Positional arg name
1017
- * @param source - {@link ArgStringSource} where the value originated
1018
- * @param expected - Expected kind (`'number'` or `'custom'`)
1019
- * @returns Actionable suggestion string
1020
- */
1021
- function buildArgCoercionSuggest(
1022
- argName: string,
1023
- source: ArgStringSource,
1024
- expected: 'number' | 'custom',
1025
- ): string {
1026
- if (source.kind === 'env') {
1027
- return expected === 'number'
1028
- ? `Set ${source.envVar} to a valid number`
1029
- : `Set ${source.envVar} to a valid value for <${argName}>`;
1030
- }
1031
-
1032
- return expected === 'number'
1033
- ? `Pipe a valid number to stdin for <${argName}>`
1034
- : `Pipe a valid value to stdin for <${argName}>`;
1035
- }
1036
-
1037
- // Arg stdin/env coercion currently only covers string-backed arg kinds
1038
- // (`string | number | enum | custom`). Mapping `stdin` to the flag-side
1039
- // `prompt` source is therefore safe today because prompt-only behaviors such
1040
- // as boolean `y`/`n` parsing and array trimming cannot apply. If arg sources
1041
- // are extended to support boolean or array coercion later, this helper must
1042
- // be updated to preserve those distinctions explicitly.
1043
- /**
1044
- * Map an {@link ArgStringSource} to the equivalent {@link CoerceSource} for flag coercion reuse.
1045
- *
1046
- * @param source - Arg source to convert
1047
- * @returns Equivalent {@link CoerceSource}
1048
- */
1049
- function argSourceToCoerceSource(source: ArgStringSource): CoerceSource {
1050
- return source.kind === 'env' ? { kind: 'env', envVar: source.envVar } : { kind: 'prompt' };
1051
- }
1052
-
1053
- /**
1054
- * Convert an {@link ArgSchema} to a {@link FlagSchema} for coercion reuse.
1055
- *
1056
- * @param schema - Arg schema to convert
1057
- * @returns Equivalent flag schema
1058
- */
1059
- function argSchemaToFlagSchema(schema: ArgSchema): FlagSchema {
1060
- const base = {
1061
- presence: 'optional' as const,
1062
- defaultValue: undefined,
1063
- aliases: [],
1064
- envVar: undefined,
1065
- configPath: undefined,
1066
- description: schema.description,
1067
- prompt: undefined,
1068
- deprecated: schema.deprecated,
1069
- propagate: false,
1070
- enumValues: undefined,
1071
- elementSchema: undefined,
1072
- parseFn: undefined as ((raw: unknown) => unknown) | undefined,
1073
- };
1074
-
1075
- switch (schema.kind) {
1076
- case 'string':
1077
- return { ...base, kind: 'string' };
1078
- case 'number':
1079
- return { ...base, kind: 'number' };
1080
- case 'enum':
1081
- return { ...base, kind: 'enum', enumValues: schema.enumValues };
1082
- case 'custom': {
1083
- if (schema.parseFn === undefined) {
1084
- return { ...base, kind: 'custom', parseFn: undefined };
1085
- }
1086
- const parseFn = schema.parseFn;
1087
- return {
1088
- ...base,
1089
- kind: 'custom',
1090
- parseFn: (raw: unknown): unknown => parseFn(typeof raw === 'string' ? raw : String(raw)),
1091
- };
1092
- }
1093
- default: {
1094
- const _exhaustive: never = schema.kind;
1095
- return _exhaustive;
1096
- }
1097
- }
1098
- }
1099
-
1100
- /**
1101
- * Build a redacted error message for arg coercion failures (hides raw values).
1102
- *
1103
- * @param argName - Positional arg name
1104
- * @param source - {@link ArgStringSource} where the value originated
1105
- * @param schema - {@link ArgSchema} declaring the expected kind
1106
- * @param error - Original coercion error (used for enum allowed list)
1107
- * @returns Redacted error message string
1108
- */
1109
- function redactArgCoercionMessage(
1110
- argName: string,
1111
- source: ArgStringSource,
1112
- schema: ArgSchema,
1113
- error: ValidationError,
1114
- ): string {
1115
- switch (schema.kind) {
1116
- case 'number':
1117
- return `Invalid number value '<redacted>' ${argSourceLabel(source)} for argument <${argName}>`;
1118
- case 'enum': {
1119
- const allowed = Array.isArray(error.details?.allowed)
1120
- ? error.details.allowed.filter((value): value is string => typeof value === 'string')
1121
- : [];
1122
- return `Invalid value '<redacted>' ${argSourceLabel(source)} for argument <${argName}>. Allowed: ${allowed.join(', ')}`;
1123
- }
1124
- case 'custom': {
1125
- const match = /: ([^:]+)$/.exec(error.message);
1126
- const suffix = match?.[1];
1127
- return suffix !== undefined
1128
- ? `Invalid value '<redacted>' ${argSourceLabel(source)} for argument <${argName}>: ${suffix}`
1129
- : `Invalid value '<redacted>' ${argSourceLabel(source)} for argument <${argName}>`;
1130
- }
1131
- case 'string':
1132
- return `Invalid value '<redacted>' ${argSourceLabel(source)} for argument <${argName}>`;
1133
- default: {
1134
- const _exhaustive: never = schema.kind;
1135
- return _exhaustive;
1136
- }
1137
- }
1138
- }
1139
-
1140
- /**
1141
- * Build redacted detail keys for arg coercion error objects.
1142
- *
1143
- * @param argName - Positional arg name
1144
- * @param source - {@link ArgStringSource} where the value originated
1145
- * @param schema - {@link ArgSchema} declaring the expected kind
1146
- * @param error - Original coercion error (used for enum allowed list)
1147
- * @returns Redacted details record (raw value omitted)
1148
- */
1149
- function redactArgCoercionDetails(
1150
- argName: string,
1151
- source: ArgStringSource,
1152
- schema: ArgSchema,
1153
- error: ValidationError,
1154
- ): Readonly<Record<string, unknown>> {
1155
- return {
1156
- arg: argName,
1157
- ...argSourceDetails(source),
1158
- ...(schema.kind === 'number' || schema.kind === 'custom' ? { expected: schema.kind } : {}),
1159
- ...(schema.kind === 'enum' && Array.isArray(error.details?.allowed)
1160
- ? {
1161
- allowed: error.details.allowed.filter(
1162
- (value): value is string => typeof value === 'string',
1163
- ),
1164
- }
1165
- : {}),
1166
- };
1167
- }
1168
-
1169
- /**
1170
- * Build a redacted suggestion for arg coercion failures.
1171
- *
1172
- * @param argName - Positional arg name
1173
- * @param source - {@link ArgStringSource} where the value originated
1174
- * @param schema - {@link ArgSchema} declaring the expected kind
1175
- * @param error - Original coercion error (used for enum allowed list)
1176
- * @returns Suggestion string, or `undefined` for string-kind args
1177
- */
1178
- function redactArgCoercionSuggest(
1179
- argName: string,
1180
- source: ArgStringSource,
1181
- schema: ArgSchema,
1182
- error: ValidationError,
1183
- ): string | undefined {
1184
- if (schema.kind === 'number' || schema.kind === 'custom') {
1185
- return buildArgCoercionSuggest(argName, source, schema.kind);
1186
- }
1187
-
1188
- if (schema.kind === 'enum') {
1189
- const allowed = Array.isArray(error.details?.allowed)
1190
- ? error.details.allowed.filter((value): value is string => typeof value === 'string')
1191
- : [];
1192
- const allowedList = allowed.join(', ');
1193
- return source.kind === 'env'
1194
- ? `Set ${source.envVar} to one of: ${allowedList}`
1195
- : `Provide one of: ${allowedList}`;
1196
- }
1197
-
1198
- return undefined;
1199
- }
1200
-
1201
- /**
1202
- * Coerce a raw stdin/env string to the arg's declared kind.
1203
- *
1204
- * Arg kinds are a strict subset of flag kinds (`string | number | enum | custom`),
1205
- * so coercion is simpler: strings and enums validate, numbers parse via
1206
- * `Number()`, and custom args invoke their parse function.
1207
- *
1208
- * @param argName - Positional arg name (for error messages)
1209
- * @param source - {@link ArgStringSource} where the value originated
1210
- * @param raw - Raw string value to coerce
1211
- * @param schema - {@link ArgSchema} declaring the expected kind
1212
- * @returns {@link CoerceResult} with redacted error messages on failure
1213
- */
1214
- function coerceArgStringValue(
1215
- argName: string,
1216
- source: ArgStringSource,
1217
- raw: string,
1218
- schema: ArgSchema,
1219
- ): CoerceResult {
1220
- const coerced = coerceValue(
1221
- argName,
1222
- argSourceToCoerceSource(source),
1223
- raw,
1224
- argSchemaToFlagSchema(schema),
1225
- );
1226
- if (coerced.ok) {
1227
- return coerced;
1228
- }
1229
-
1230
- const suggest = redactArgCoercionSuggest(argName, source, schema, coerced.error);
1231
- const options =
1232
- suggest === undefined
1233
- ? {
1234
- code: coerced.error.code,
1235
- details: redactArgCoercionDetails(argName, source, schema, coerced.error),
1236
- }
1237
- : {
1238
- code: coerced.error.code,
1239
- details: redactArgCoercionDetails(argName, source, schema, coerced.error),
1240
- suggest,
1241
- };
1242
-
1243
- return {
1244
- ok: false,
1245
- error: new ValidationError(
1246
- redactArgCoercionMessage(argName, source, schema, coerced.error),
1247
- options,
1248
- ),
1249
- };
1250
- }
1251
-
1252
- // --- Required arg suggestion builder
1253
-
1254
- /**
1255
- * Build an actionable suggestion for a required arg that was not provided.
1256
- *
1257
- * Mirrors {@link buildRequiredFlagSuggest} but for positional args.
1258
- *
1259
- * @param name - Positional arg name
1260
- * @param schema - {@link ArgSchema} for the missing arg
1261
- * @param variadic - Whether the arg is variadic (changes wording)
1262
- * @returns Human-readable suggestion string
1263
- */
1264
- function buildRequiredArgSuggest(name: string, schema: ArgSchema, variadic?: boolean): string {
1265
- const sources: [string, ...string[]] = [
1266
- variadic ? `Provide at least one value for <${name}>` : `Provide a value for <${name}>`,
1267
- ];
1268
-
1269
- if (schema.stdinMode) {
1270
- sources.push(`pipe a value to stdin or pass '-'`);
1271
- }
1272
-
1273
- if (schema.envVar !== undefined) {
1274
- sources.push(`set ${schema.envVar}`);
1275
- }
1276
-
1277
- if (sources.length === 1) {
1278
- return sources[0];
1279
- }
1280
-
1281
- if (sources.length === 2) {
1282
- return `${sources[0]} or ${sources[1]}`;
1283
- }
1284
-
1285
- return `${sources.slice(0, -1).join(', ')}, or ${sources[sources.length - 1]}`;
1286
- }
1287
-
1288
- // --- Type narrowing helpers
1289
-
1290
- /**
1291
- * Narrow a plain array to a non-empty tuple.
1292
- *
1293
- * @param arr - Array to check
1294
- * @returns `true` (with narrowed type) if the array has at least one element
1295
- */
1296
- function isNonEmpty<T>(arr: readonly T[]): arr is readonly [T, ...T[]] {
1297
- return arr.length > 0;
1298
- }
1299
-
1300
- // --- Error aggregation
1301
-
1302
- /**
1303
- * Throw a single `ValidationError` that aggregates multiple missing-value
1304
- * errors. The first error's code is used as the primary; all errors are
1305
- * listed in `details.errors` for programmatic access.
1306
- *
1307
- * If there's exactly one error, throw it directly (no wrapping overhead).
1308
- *
1309
- * @param errors - Non-empty array of validation errors to aggregate
1310
- * @throws ValidationError always — either the single error or an aggregate
1311
- */
1312
- function throwAggregatedErrors(errors: readonly [ValidationError, ...ValidationError[]]): never {
1313
- if (errors.length === 1) {
1314
- throw errors[0];
1315
- }
1316
-
1317
- const messages = errors.map((e) => e.message);
1318
- throw new ValidationError(`Multiple validation errors:\n - ${messages.join('\n - ')}`, {
1319
- code: errors[0].code,
1320
- details: {
1321
- errors: errors.map((e) => e.toJSON()),
1322
- count: errors.length,
1323
- },
1324
- suggest: 'Fix all missing required values listed above',
1325
- });
104
+ return { flags, args, deprecations };
1326
105
  }
1327
106
 
1328
- // --- Exports
1329
-
1330
107
  export type { DeprecationWarning, ResolveOptions, ResolveResult };
1331
108
  export { resolve };