@kjanat/dreamcli 0.0.0 → 1.0.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.
- package/CHANGELOG.md +667 -0
- package/LICENSE +22 -0
- package/README.md +370 -0
- package/dist/adapter-B37d9oia.mjs +1 -0
- package/dist/adapter-CCSh5juX.cjs +1 -0
- package/dist/adapter-DIwO-q7K.d.mts +3447 -0
- package/dist/adapter-DQnxxLiE.d.cts +3447 -0
- package/dist/auto-5cjZaF9V.mjs +3 -0
- package/dist/auto-B0eSgoDw.cjs +3 -0
- package/dist/index.cjs +10 -0
- package/dist/index.d.cts +920 -0
- package/dist/index.d.mts +920 -0
- package/dist/index.mjs +10 -0
- package/dist/runtime.cjs +1 -0
- package/dist/runtime.d.cts +253 -0
- package/dist/runtime.d.mts +253 -0
- package/dist/runtime.mjs +1 -0
- package/dist/testkit-CEDYPvhF.mjs +14 -0
- package/dist/testkit-ClIKijxC.cjs +14 -0
- package/dist/testkit.cjs +1 -0
- package/dist/testkit.d.cts +25 -0
- package/dist/testkit.d.mts +25 -0
- package/dist/testkit.mjs +1 -0
- package/examples/basic.ts +33 -0
- package/examples/gh/package.json +48 -0
- package/examples/gh/src/commands/auth.ts +66 -0
- package/examples/gh/src/commands/issue.ts +120 -0
- package/examples/gh/src/commands/pr.ts +125 -0
- package/examples/gh/src/data/issues.yaml +5 -0
- package/examples/gh/src/data/issues.yaml.d.ts +17 -0
- package/examples/gh/src/data/pull-requests.yaml +7 -0
- package/examples/gh/src/data/pull-requests.yaml.d.ts +18 -0
- package/examples/gh/src/lib/auth.ts +37 -0
- package/examples/gh/src/lib/utils.ts +17 -0
- package/examples/gh/src/main.test.ts +306 -0
- package/examples/gh/src/main.ts +38 -0
- package/examples/gh/tsconfig.json +37 -0
- package/examples/interactive.ts +66 -0
- package/examples/json-mode.ts +93 -0
- package/examples/middleware.ts +71 -0
- package/examples/multi-command.ts +66 -0
- package/examples/spinner-progress.ts +49 -0
- package/examples/testing.ts +145 -0
- package/examples/tsconfig.json +17 -0
- package/package.json +123 -2
- package/src/core/cli/AGENTS.md +72 -0
- package/src/core/cli/dispatch.ts +282 -0
- package/src/core/cli/index.ts +1425 -0
- package/src/core/cli/plugin.ts +111 -0
- package/src/core/cli/propagate.ts +97 -0
- package/src/core/cli/root-help.ts +269 -0
- package/src/core/cli/root-surface.ts +74 -0
- package/src/core/completion/AGENTS.md +72 -0
- package/src/core/completion/completion-test-helpers.ts +48 -0
- package/src/core/completion/index.ts +82 -0
- package/src/core/completion/shells/bash.ts +456 -0
- package/src/core/completion/shells/fish.ts +24 -0
- package/src/core/completion/shells/powershell.ts +24 -0
- package/src/core/completion/shells/shared.ts +283 -0
- package/src/core/completion/shells/zsh.ts +376 -0
- package/src/core/config/index.ts +404 -0
- package/src/core/config/package-json.ts +216 -0
- package/src/core/errors/index.ts +178 -0
- package/src/core/help/index.ts +559 -0
- package/src/core/json-schema/index.ts +705 -0
- package/src/core/output/AGENTS.md +69 -0
- package/src/core/output/activity.ts +568 -0
- package/src/core/output/display-value.ts +48 -0
- package/src/core/output/index.ts +704 -0
- package/src/core/output/writer.ts +46 -0
- package/src/core/parse/index.ts +643 -0
- package/src/core/prompt/index.ts +566 -0
- package/src/core/resolve/AGENTS.md +69 -0
- package/src/core/resolve/index.ts +1331 -0
- package/src/core/schema/AGENTS.md +61 -0
- package/src/core/schema/activity.ts +237 -0
- package/src/core/schema/arg.ts +707 -0
- package/src/core/schema/command.ts +1263 -0
- package/src/core/schema/flag.ts +651 -0
- package/src/core/schema/index.ts +82 -0
- package/src/core/schema/middleware.ts +171 -0
- package/src/core/schema/prompt.ts +148 -0
- package/src/core/schema/run.ts +187 -0
- package/src/core/testkit/AGENTS.md +55 -0
- package/src/core/testkit/index.ts +365 -0
- package/src/index.ts +164 -0
- package/src/runtime/AGENTS.md +74 -0
- package/src/runtime/adapter.ts +300 -0
- package/src/runtime/auto.ts +110 -0
- package/src/runtime/bun.ts +55 -0
- package/src/runtime/deno.ts +355 -0
- package/src/runtime/detect.ts +102 -0
- package/src/runtime/index.ts +21 -0
- package/src/runtime/node-builtins.d.ts +23 -0
- package/src/runtime/node.ts +278 -0
- package/src/runtime/paths.ts +56 -0
- package/src/runtime/support.ts +119 -0
- package/src/runtime/test-helpers.ts +40 -0
- package/src/runtime.ts +31 -0
- package/src/testkit.ts +23 -0
- package/src/version.ts +20 -0
|
@@ -0,0 +1,1331 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolution chain: CLI -> env -> config -> prompt -> default.
|
|
3
|
+
*
|
|
4
|
+
* v0.1 implemented: **CLI parsed value -> default value**.
|
|
5
|
+
* v0.2 adds: **env variable resolution** and **config object resolution**
|
|
6
|
+
* between CLI and default.
|
|
7
|
+
* v0.3 adds: **prompt resolution** between config and default.
|
|
8
|
+
*
|
|
9
|
+
* The resolver takes raw `ParseResult` (from the parser) and a
|
|
10
|
+
* `CommandSchema`, applies the resolution chain, and validates
|
|
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`.
|
|
14
|
+
*
|
|
15
|
+
* @module dreamcli/core/resolve
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { ValidationErrorCode } from '#internals/core/errors/index.ts';
|
|
19
|
+
import { ValidationError } from '#internals/core/errors/index.ts';
|
|
20
|
+
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
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Resolve parsed values against a command schema.
|
|
149
|
+
*
|
|
150
|
+
* 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`.
|
|
154
|
+
*
|
|
155
|
+
* 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`)
|
|
160
|
+
* 5. Default value (from schema)
|
|
161
|
+
*
|
|
162
|
+
* After resolution, validates that all required flags and args have
|
|
163
|
+
* a value. Collects **all** validation errors before throwing, so the
|
|
164
|
+
* user sees every missing field at once.
|
|
165
|
+
*
|
|
166
|
+
* @param schema - The command schema defining flags and args
|
|
167
|
+
* @param parsed - Raw parsed values from the parser
|
|
168
|
+
* @param options - External state for the resolution chain
|
|
169
|
+
* @returns Fully resolved flag and arg values
|
|
170
|
+
* @throws ValidationError if any required flag or arg is missing,
|
|
171
|
+
* or if an env/config value fails coercion
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* ```ts
|
|
175
|
+
* const parsed = parse(deploy.schema, ['production']);
|
|
176
|
+
* const resolved = await resolve(deploy.schema, parsed, {
|
|
177
|
+
* env: { DEPLOY_REGION: 'eu' },
|
|
178
|
+
* });
|
|
179
|
+
* ```
|
|
180
|
+
*/
|
|
181
|
+
async function resolve(
|
|
182
|
+
schema: CommandSchema,
|
|
183
|
+
parsed: ParseResult,
|
|
184
|
+
options?: ResolveOptions,
|
|
185
|
+
): Promise<ResolveResult> {
|
|
186
|
+
const stdinData = options?.stdinData;
|
|
187
|
+
const env = options?.env ?? {};
|
|
188
|
+
const config = options?.config ?? {};
|
|
189
|
+
const prompter = options?.prompter;
|
|
190
|
+
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> = {};
|
|
250
|
+
const errors: ValidationError[] = [];
|
|
251
|
+
|
|
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
|
+
);
|
|
818
|
+
}
|
|
819
|
+
}
|
|
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
|
+
|
|
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
|
+
}
|
|
912
|
+
}
|
|
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;
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
if (isNonEmpty(errors)) {
|
|
974
|
+
throwAggregatedErrors(errors);
|
|
975
|
+
}
|
|
976
|
+
|
|
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
|
+
});
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
// --- Exports
|
|
1329
|
+
|
|
1330
|
+
export type { DeprecationWarning, ResolveOptions, ResolveResult };
|
|
1331
|
+
export { resolve };
|