padrone 1.4.0 → 1.6.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 +115 -0
- package/README.md +108 -283
- package/dist/args-Cnq0nwSM.mjs +272 -0
- package/dist/args-Cnq0nwSM.mjs.map +1 -0
- package/dist/codegen/index.d.mts +28 -3
- package/dist/codegen/index.d.mts.map +1 -1
- package/dist/codegen/index.mjs +169 -19
- package/dist/codegen/index.mjs.map +1 -1
- package/dist/commands-B_gufyR9.mjs +514 -0
- package/dist/commands-B_gufyR9.mjs.map +1 -0
- package/dist/{completion.mjs → completion-BEuflbDO.mjs} +86 -108
- package/dist/completion-BEuflbDO.mjs.map +1 -0
- package/dist/docs/index.d.mts +22 -2
- package/dist/docs/index.d.mts.map +1 -1
- package/dist/docs/index.mjs +92 -7
- package/dist/docs/index.mjs.map +1 -1
- package/dist/errors-CL63UOzt.mjs +137 -0
- package/dist/errors-CL63UOzt.mjs.map +1 -0
- package/dist/{formatter-ClUK5hcQ.d.mts → formatter-DrvhDMrq.d.mts} +35 -6
- package/dist/formatter-DrvhDMrq.d.mts.map +1 -0
- package/dist/help-B5Kk83of.mjs +849 -0
- package/dist/help-B5Kk83of.mjs.map +1 -0
- package/dist/index-BaU3X6dY.d.mts +1178 -0
- package/dist/index-BaU3X6dY.d.mts.map +1 -0
- package/dist/index.d.mts +763 -36
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3608 -1534
- package/dist/index.mjs.map +1 -1
- package/dist/mcp-BM-d0nZi.mjs +377 -0
- package/dist/mcp-BM-d0nZi.mjs.map +1 -0
- package/dist/serve-Bk0JUlCj.mjs +402 -0
- package/dist/serve-Bk0JUlCj.mjs.map +1 -0
- package/dist/stream-DC4H8YTx.mjs +77 -0
- package/dist/stream-DC4H8YTx.mjs.map +1 -0
- package/dist/test.d.mts +5 -8
- package/dist/test.d.mts.map +1 -1
- package/dist/test.mjs +5 -27
- package/dist/test.mjs.map +1 -1
- package/dist/{update-check-EbNDkzyV.mjs → update-check-CZ2VqjnV.mjs} +16 -17
- package/dist/update-check-CZ2VqjnV.mjs.map +1 -0
- package/dist/zod.d.mts +32 -0
- package/dist/zod.d.mts.map +1 -0
- package/dist/zod.mjs +50 -0
- package/dist/zod.mjs.map +1 -0
- package/package.json +20 -9
- package/src/cli/completions.ts +14 -11
- package/src/cli/docs.ts +13 -16
- package/src/cli/doctor.ts +213 -24
- package/src/cli/index.ts +28 -82
- package/src/cli/init.ts +12 -10
- package/src/cli/link.ts +22 -18
- package/src/cli/wrap.ts +14 -11
- package/src/codegen/discovery.ts +80 -28
- package/src/codegen/index.ts +2 -1
- package/src/codegen/parsers/bash.ts +179 -0
- package/src/codegen/schema-to-code.ts +2 -1
- package/src/core/args.ts +296 -0
- package/src/core/commands.ts +373 -0
- package/src/core/create.ts +268 -0
- package/src/{runtime.ts → core/default-runtime.ts} +70 -135
- package/src/{errors.ts → core/errors.ts} +22 -0
- package/src/core/exec.ts +259 -0
- package/src/core/interceptors.ts +302 -0
- package/src/{parse.ts → core/parse.ts} +36 -89
- package/src/core/program-methods.ts +301 -0
- package/src/core/results.ts +229 -0
- package/src/core/runtime.ts +246 -0
- package/src/core/validate.ts +247 -0
- package/src/docs/index.ts +124 -11
- package/src/extension/auto-output.ts +95 -0
- package/src/extension/color.ts +38 -0
- package/src/extension/completion.ts +49 -0
- package/src/extension/config.ts +262 -0
- package/src/extension/env.ts +101 -0
- package/src/extension/help.ts +192 -0
- package/src/extension/index.ts +43 -0
- package/src/extension/ink.ts +93 -0
- package/src/extension/interactive.ts +106 -0
- package/src/extension/logger.ts +214 -0
- package/src/extension/man.ts +51 -0
- package/src/extension/mcp.ts +52 -0
- package/src/extension/progress-renderer.ts +338 -0
- package/src/extension/progress.ts +299 -0
- package/src/extension/repl.ts +94 -0
- package/src/extension/serve.ts +48 -0
- package/src/extension/signal.ts +87 -0
- package/src/extension/stdin.ts +62 -0
- package/src/extension/suggestions.ts +114 -0
- package/src/extension/timing.ts +81 -0
- package/src/extension/tracing.ts +175 -0
- package/src/extension/update-check.ts +77 -0
- package/src/extension/utils.ts +51 -0
- package/src/extension/version.ts +63 -0
- package/src/{completion.ts → feature/completion.ts} +130 -57
- package/src/{interactive.ts → feature/interactive.ts} +47 -6
- package/src/feature/mcp.ts +387 -0
- package/src/{repl-loop.ts → feature/repl-loop.ts} +26 -16
- package/src/feature/serve.ts +438 -0
- package/src/feature/test.ts +262 -0
- package/src/{update-check.ts → feature/update-check.ts} +16 -16
- package/src/{wrap.ts → feature/wrap.ts} +27 -27
- package/src/index.ts +120 -11
- package/src/output/colorizer.ts +154 -0
- package/src/{formatter.ts → output/formatter.ts} +281 -135
- package/src/{help.ts → output/help.ts} +62 -15
- package/src/{zod.d.ts → schema/zod.d.ts} +1 -1
- package/src/schema/zod.ts +50 -0
- package/src/test.ts +2 -285
- package/src/types/args-meta.ts +151 -0
- package/src/types/builder.ts +697 -0
- package/src/types/command.ts +157 -0
- package/src/types/index.ts +59 -0
- package/src/types/interceptor.ts +296 -0
- package/src/types/preferences.ts +83 -0
- package/src/types/result.ts +71 -0
- package/src/types/schema.ts +19 -0
- package/src/util/dotenv.ts +244 -0
- package/src/{shell-utils.ts → util/shell-utils.ts} +26 -9
- package/src/util/stream.ts +101 -0
- package/src/{type-helpers.ts → util/type-helpers.ts} +23 -16
- package/src/{type-utils.ts → util/type-utils.ts} +99 -37
- package/src/util/utils.ts +51 -0
- package/src/zod.ts +1 -0
- package/dist/args-CVDbyyzG.mjs +0 -199
- package/dist/args-CVDbyyzG.mjs.map +0 -1
- package/dist/chunk-y_GBKt04.mjs +0 -5
- package/dist/completion.d.mts +0 -64
- package/dist/completion.d.mts.map +0 -1
- package/dist/completion.mjs.map +0 -1
- package/dist/formatter-ClUK5hcQ.d.mts.map +0 -1
- package/dist/help-CcBe91bV.mjs +0 -1254
- package/dist/help-CcBe91bV.mjs.map +0 -1
- package/dist/types-DjIdJN5G.d.mts +0 -1059
- package/dist/types-DjIdJN5G.d.mts.map +0 -1
- package/dist/update-check-EbNDkzyV.mjs.map +0 -1
- package/src/args.ts +0 -461
- package/src/colorizer.ts +0 -41
- package/src/command-utils.ts +0 -532
- package/src/create.ts +0 -1477
- package/src/types.ts +0 -1109
- package/src/utils.ts +0 -140
package/src/create.ts
DELETED
|
@@ -1,1477 +0,0 @@
|
|
|
1
|
-
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
-
import type { Schema } from 'ai';
|
|
3
|
-
import { coerceArgs, detectUnknownArgs, extractSchemaMetadata, parsePositionalConfig, parseStdinConfig, preprocessArgs } from './args.ts';
|
|
4
|
-
import {
|
|
5
|
-
commandSymbol,
|
|
6
|
-
findCommandByName,
|
|
7
|
-
getCommandRuntime,
|
|
8
|
-
hasInteractiveConfig,
|
|
9
|
-
isAsyncBranded,
|
|
10
|
-
makeThenable,
|
|
11
|
-
mergeCommands,
|
|
12
|
-
noop,
|
|
13
|
-
outputValue,
|
|
14
|
-
repathCommandTree,
|
|
15
|
-
runPluginChain,
|
|
16
|
-
suggestSimilar,
|
|
17
|
-
thenMaybe,
|
|
18
|
-
warnIfUnexpectedAsync,
|
|
19
|
-
wrapWithLifecycle,
|
|
20
|
-
} from './command-utils.ts';
|
|
21
|
-
import type { ShellType } from './completion.ts';
|
|
22
|
-
import { ConfigError, RoutingError, ValidationError } from './errors.ts';
|
|
23
|
-
import { generateHelp } from './help.ts';
|
|
24
|
-
import { promptInteractiveFields } from './interactive.ts';
|
|
25
|
-
import { getNestedValue, parseCliInputToParts, setNestedValue } from './parse.ts';
|
|
26
|
-
import { createReplIterator } from './repl-loop.ts';
|
|
27
|
-
import { resolveStdin } from './runtime.ts';
|
|
28
|
-
import type {
|
|
29
|
-
AnyPadroneCommand,
|
|
30
|
-
AnyPadroneProgram,
|
|
31
|
-
PadroneActionContext,
|
|
32
|
-
PadroneAPI,
|
|
33
|
-
PadroneCommand,
|
|
34
|
-
PadroneEvalPreferences,
|
|
35
|
-
PadronePlugin,
|
|
36
|
-
PadroneProgram,
|
|
37
|
-
PadroneReplPreferences,
|
|
38
|
-
PluginExecuteContext,
|
|
39
|
-
PluginExecuteResult,
|
|
40
|
-
PluginParseContext,
|
|
41
|
-
PluginParseResult,
|
|
42
|
-
PluginValidateContext,
|
|
43
|
-
PluginValidateResult,
|
|
44
|
-
} from './types.ts';
|
|
45
|
-
import { getVersion } from './utils.ts';
|
|
46
|
-
import { createWrapHandler } from './wrap.ts';
|
|
47
|
-
|
|
48
|
-
export { asyncSchema, buildReplCompleter } from './command-utils.ts';
|
|
49
|
-
|
|
50
|
-
export function createPadrone<TProgramName extends string>(name: TProgramName): PadroneProgram<TProgramName, '', ''> {
|
|
51
|
-
return createPadroneBuilder({ name, path: '', commands: [] } as any) as unknown as PadroneProgram<TProgramName, '', ''>;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export function createPadroneBuilder<TBuilder extends PadroneProgram = PadroneProgram>(
|
|
55
|
-
inputCommand: AnyPadroneCommand,
|
|
56
|
-
): TBuilder & { [commandSymbol]: AnyPadroneCommand } {
|
|
57
|
-
// Re-parent direct subcommands so getCommandRuntime walks to the current root,
|
|
58
|
-
// not a stale parent from before .runtime()/.configure()/etc.
|
|
59
|
-
const existingCommand =
|
|
60
|
-
inputCommand.commands?.length && inputCommand.commands.some((c) => c.parent && c.parent !== inputCommand)
|
|
61
|
-
? {
|
|
62
|
-
...inputCommand,
|
|
63
|
-
commands: inputCommand.commands.map((c) => (c.parent && c.parent !== inputCommand ? { ...c, parent: inputCommand } : c)),
|
|
64
|
-
}
|
|
65
|
-
: inputCommand;
|
|
66
|
-
|
|
67
|
-
/** Creates the action context passed to command handlers. References `builder` which is defined later but only called at runtime. */
|
|
68
|
-
const createActionContext = (cmd: AnyPadroneCommand): PadroneActionContext => ({
|
|
69
|
-
runtime: getCommandRuntime(cmd),
|
|
70
|
-
command: cmd,
|
|
71
|
-
program: builder as any,
|
|
72
|
-
});
|
|
73
|
-
|
|
74
|
-
const find: AnyPadroneProgram['find'] = (command) => {
|
|
75
|
-
if (typeof command !== 'string') return findCommandByName(command.path, existingCommand.commands) as any;
|
|
76
|
-
return findCommandByName(command, existingCommand.commands) as any;
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* Parses CLI input to find the command and extract raw arguments without validation.
|
|
81
|
-
*/
|
|
82
|
-
const parseCommand = (input: string | undefined) => {
|
|
83
|
-
input ??= getCommandRuntime(existingCommand).argv().join(' ') || undefined;
|
|
84
|
-
if (!input) {
|
|
85
|
-
// No input: check for default '' command
|
|
86
|
-
const defaultCommand = findCommandByName('', existingCommand.commands);
|
|
87
|
-
if (defaultCommand) {
|
|
88
|
-
return { command: defaultCommand, rawArgs: {} as Record<string, unknown>, args: [] as string[], unmatchedTerms: [] as string[] };
|
|
89
|
-
}
|
|
90
|
-
return { command: existingCommand, rawArgs: {} as Record<string, unknown>, args: [] as string[], unmatchedTerms: [] as string[] };
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
const parts = parseCliInputToParts(input);
|
|
94
|
-
|
|
95
|
-
const terms = parts.filter((p) => p.type === 'term').map((p) => p.value);
|
|
96
|
-
const args = parts.filter((p) => p.type === 'arg').map((p) => p.value);
|
|
97
|
-
|
|
98
|
-
let curCommand: AnyPadroneCommand | undefined = existingCommand;
|
|
99
|
-
let unmatchedTerms: string[] = [];
|
|
100
|
-
|
|
101
|
-
// If the first term is the program name, skip it
|
|
102
|
-
if (terms[0] === existingCommand.name) terms.shift();
|
|
103
|
-
|
|
104
|
-
for (let i = 0; i < terms.length; i++) {
|
|
105
|
-
const term = terms[i] || '';
|
|
106
|
-
const found = findCommandByName(term, curCommand.commands);
|
|
107
|
-
|
|
108
|
-
if (found) {
|
|
109
|
-
curCommand = found;
|
|
110
|
-
} else {
|
|
111
|
-
unmatchedTerms = terms.slice(i);
|
|
112
|
-
args.unshift(...unmatchedTerms);
|
|
113
|
-
break;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
// If no unmatched terms remain, check for a default '' subcommand.
|
|
118
|
-
// This handles both the root level (no input) and nested commands (e.g., "advanced" with a '' subcommand).
|
|
119
|
-
if (unmatchedTerms.length === 0 && curCommand.commands?.length) {
|
|
120
|
-
const defaultCommand = findCommandByName('', curCommand.commands);
|
|
121
|
-
if (defaultCommand) {
|
|
122
|
-
curCommand = defaultCommand;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
if (!curCommand) return { command: existingCommand, rawArgs: {} as Record<string, unknown>, args, unmatchedTerms };
|
|
127
|
-
|
|
128
|
-
// Extract argument metadata from the nested arguments object in meta
|
|
129
|
-
const argsMeta = curCommand.meta?.fields;
|
|
130
|
-
const schemaMetadata = curCommand.argsSchema
|
|
131
|
-
? extractSchemaMetadata(curCommand.argsSchema, argsMeta, curCommand.meta?.autoAlias)
|
|
132
|
-
: { flags: {}, aliases: {} };
|
|
133
|
-
const { flags, aliases } = schemaMetadata;
|
|
134
|
-
|
|
135
|
-
// Get array arguments from schema (arrays are always variadic)
|
|
136
|
-
const arrayArguments = new Set<string>();
|
|
137
|
-
if (curCommand.argsSchema) {
|
|
138
|
-
try {
|
|
139
|
-
const jsonSchema = curCommand.argsSchema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }) as Record<string, any>;
|
|
140
|
-
if (jsonSchema.type === 'object' && jsonSchema.properties) {
|
|
141
|
-
for (const [key, prop] of Object.entries(jsonSchema.properties as Record<string, any>)) {
|
|
142
|
-
if (prop?.type === 'array') arrayArguments.add(key);
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
} catch {
|
|
146
|
-
// Ignore schema parsing errors
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
const argParts = parts.filter((p) => p.type === 'named' || p.type === 'alias');
|
|
151
|
-
const rawArgs: Record<string, unknown> = {};
|
|
152
|
-
|
|
153
|
-
for (const arg of argParts) {
|
|
154
|
-
// Resolve flags (single-char, from alias parts: -v) and aliases (multi-char, from named parts: --dry-run)
|
|
155
|
-
let key: string[];
|
|
156
|
-
if (arg.type === 'alias' && arg.key.length === 1 && flags[arg.key[0]!]) {
|
|
157
|
-
key = [flags[arg.key[0]!]!];
|
|
158
|
-
} else if (arg.type === 'named' && arg.key.length === 1 && aliases[arg.key[0]!]) {
|
|
159
|
-
key = [aliases[arg.key[0]!]!];
|
|
160
|
-
} else {
|
|
161
|
-
key = arg.key;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
const rootKey = key[0]!;
|
|
165
|
-
|
|
166
|
-
// Handle negated boolean arguments (--no-verbose)
|
|
167
|
-
if (arg.type === 'named' && arg.negated) {
|
|
168
|
-
setNestedValue(rawArgs, key, false);
|
|
169
|
-
continue;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
const value = arg.value ?? true;
|
|
173
|
-
|
|
174
|
-
// Handle array arguments - accumulate values into arrays (arrays are always variadic)
|
|
175
|
-
if (arrayArguments.has(rootKey)) {
|
|
176
|
-
const existing = getNestedValue(rawArgs, key);
|
|
177
|
-
if (existing !== undefined) {
|
|
178
|
-
if (Array.isArray(existing)) {
|
|
179
|
-
if (Array.isArray(value)) {
|
|
180
|
-
existing.push(...value);
|
|
181
|
-
} else {
|
|
182
|
-
existing.push(value);
|
|
183
|
-
}
|
|
184
|
-
} else {
|
|
185
|
-
if (Array.isArray(value)) {
|
|
186
|
-
setNestedValue(rawArgs, key, [existing, ...value]);
|
|
187
|
-
} else {
|
|
188
|
-
setNestedValue(rawArgs, key, [existing, value]);
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
} else {
|
|
192
|
-
setNestedValue(rawArgs, key, Array.isArray(value) ? value : [value]);
|
|
193
|
-
}
|
|
194
|
-
} else {
|
|
195
|
-
setNestedValue(rawArgs, key, value);
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
return { command: curCommand, rawArgs, args, unmatchedTerms };
|
|
200
|
-
};
|
|
201
|
-
|
|
202
|
-
/**
|
|
203
|
-
* Preprocesses raw arguments: applies env/config values and maps positional arguments.
|
|
204
|
-
* Also performs auto-coercion (string→number/boolean) and unknown arg detection.
|
|
205
|
-
*/
|
|
206
|
-
const buildCommandArgs = (
|
|
207
|
-
command: AnyPadroneCommand,
|
|
208
|
-
rawArgs: Record<string, unknown>,
|
|
209
|
-
args: string[],
|
|
210
|
-
context?: { stdinData?: Record<string, unknown>; envData?: Record<string, unknown>; configData?: Record<string, unknown> },
|
|
211
|
-
): Record<string, unknown> => {
|
|
212
|
-
// Apply preprocessing (stdin, env, and config bindings)
|
|
213
|
-
let preprocessedArgs = preprocessArgs(rawArgs, {
|
|
214
|
-
flags: {}, // Already resolved in parseCommand
|
|
215
|
-
aliases: {}, // Already resolved in parseCommand
|
|
216
|
-
stdinData: context?.stdinData,
|
|
217
|
-
envData: context?.envData,
|
|
218
|
-
configData: context?.configData,
|
|
219
|
-
});
|
|
220
|
-
|
|
221
|
-
// Parse positional configuration
|
|
222
|
-
const positionalConfig = command.meta?.positional ? parsePositionalConfig(command.meta.positional) : [];
|
|
223
|
-
|
|
224
|
-
// Map positional arguments to their named arguments
|
|
225
|
-
if (positionalConfig.length > 0) {
|
|
226
|
-
let argIndex = 0;
|
|
227
|
-
for (let i = 0; i < positionalConfig.length; i++) {
|
|
228
|
-
const { name, variadic } = positionalConfig[i]!;
|
|
229
|
-
if (argIndex >= args.length) break;
|
|
230
|
-
|
|
231
|
-
if (variadic) {
|
|
232
|
-
// Collect remaining args (but leave room for non-variadic args after)
|
|
233
|
-
const remainingPositionals = positionalConfig.slice(i + 1);
|
|
234
|
-
const nonVariadicAfter = remainingPositionals.filter((p) => !p.variadic).length;
|
|
235
|
-
const variadicEnd = args.length - nonVariadicAfter;
|
|
236
|
-
preprocessedArgs[name] = args.slice(argIndex, variadicEnd);
|
|
237
|
-
argIndex = variadicEnd;
|
|
238
|
-
} else if (i === positionalConfig.length - 1 && args.length > argIndex + 1) {
|
|
239
|
-
// Last non-variadic positional: join all remaining tokens (e.g. `-- Hello world` → "Hello world")
|
|
240
|
-
preprocessedArgs[name] = args.slice(argIndex).join(' ');
|
|
241
|
-
argIndex = args.length;
|
|
242
|
-
} else {
|
|
243
|
-
preprocessedArgs[name] = args[argIndex];
|
|
244
|
-
argIndex++;
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
// Auto-coerce CLI string values to match schema types (string→number, string→boolean)
|
|
250
|
-
if (command.argsSchema) {
|
|
251
|
-
preprocessedArgs = coerceArgs(preprocessedArgs, command.argsSchema);
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
return preprocessedArgs;
|
|
255
|
-
};
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* Detects unknown options in args that aren't defined in the schema.
|
|
259
|
-
* Returns unknown key info with suggestions, or empty array if schema is loose.
|
|
260
|
-
*/
|
|
261
|
-
const checkUnknownArgs = (
|
|
262
|
-
command: AnyPadroneCommand,
|
|
263
|
-
preprocessedArgs: Record<string, unknown>,
|
|
264
|
-
): { key: string; suggestion: string }[] => {
|
|
265
|
-
if (!command.argsSchema) return [];
|
|
266
|
-
|
|
267
|
-
const argsMeta = command.meta?.fields;
|
|
268
|
-
const { flags, aliases } = extractSchemaMetadata(command.argsSchema, argsMeta, command.meta?.autoAlias);
|
|
269
|
-
|
|
270
|
-
return detectUnknownArgs(preprocessedArgs, command.argsSchema, flags, aliases, suggestSimilar);
|
|
271
|
-
};
|
|
272
|
-
|
|
273
|
-
/**
|
|
274
|
-
* Validates preprocessed arguments against the command's schema.
|
|
275
|
-
* First checks for unknown args (strict by default), then runs schema validation.
|
|
276
|
-
* Returns sync or async result depending on the schema's validate method.
|
|
277
|
-
*/
|
|
278
|
-
const validateCommandArgs = (command: AnyPadroneCommand, preprocessedArgs: Record<string, unknown>) => {
|
|
279
|
-
// Check for unknown args before schema validation (strict by default)
|
|
280
|
-
const unknownArgs = checkUnknownArgs(command, preprocessedArgs);
|
|
281
|
-
if (unknownArgs.length > 0) {
|
|
282
|
-
const issues: StandardSchemaV1.Issue[] = unknownArgs.map(({ key, suggestion }) => ({
|
|
283
|
-
path: [key],
|
|
284
|
-
message: suggestion ? `Unknown option: "${key}". ${suggestion}` : `Unknown option: "${key}"`,
|
|
285
|
-
}));
|
|
286
|
-
return { args: undefined, argsResult: { issues } as any };
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
const argsParsed = command.argsSchema ? command.argsSchema['~standard'].validate(preprocessedArgs) : { value: preprocessedArgs };
|
|
290
|
-
|
|
291
|
-
// Return undefined for args when there's no schema and no meaningful args
|
|
292
|
-
const hasArgs = command.argsSchema || Object.keys(preprocessedArgs).length > 0;
|
|
293
|
-
|
|
294
|
-
const buildResult = (parsed: StandardSchemaV1.Result<unknown>) => ({
|
|
295
|
-
args: parsed.issues ? undefined : hasArgs ? (parsed.value as any) : undefined,
|
|
296
|
-
argsResult: parsed as any,
|
|
297
|
-
});
|
|
298
|
-
|
|
299
|
-
return thenMaybe(argsParsed, buildResult);
|
|
300
|
-
};
|
|
301
|
-
|
|
302
|
-
/**
|
|
303
|
-
* Preprocesses and validates raw arguments against the command's schema.
|
|
304
|
-
* Returns sync or async result depending on the schema's validate method.
|
|
305
|
-
*/
|
|
306
|
-
const validateArgs = (
|
|
307
|
-
command: AnyPadroneCommand,
|
|
308
|
-
rawArgs: Record<string, unknown>,
|
|
309
|
-
args: string[],
|
|
310
|
-
context?: { stdinData?: Record<string, unknown>; envData?: Record<string, unknown>; configData?: Record<string, unknown> },
|
|
311
|
-
) => {
|
|
312
|
-
const preprocessedArgs = buildCommandArgs(command, rawArgs, args, context);
|
|
313
|
-
return validateCommandArgs(command, preprocessedArgs);
|
|
314
|
-
};
|
|
315
|
-
|
|
316
|
-
const parse: AnyPadroneProgram['parse'] = (input) => {
|
|
317
|
-
const state: Record<string, unknown> = {};
|
|
318
|
-
|
|
319
|
-
// Parse phase (with plugins)
|
|
320
|
-
const parseCtx: PluginParseContext = { input: input as string | undefined, command: existingCommand, state };
|
|
321
|
-
const coreParse = (): PluginParseResult => {
|
|
322
|
-
const { command, rawArgs, args } = parseCommand(parseCtx.input);
|
|
323
|
-
return { command, rawArgs, positionalArgs: args };
|
|
324
|
-
};
|
|
325
|
-
|
|
326
|
-
// Parse phase: root plugins only
|
|
327
|
-
const rootPlugins = existingCommand.plugins ?? [];
|
|
328
|
-
const parsedOrPromise = runPluginChain('parse', rootPlugins, parseCtx, coreParse);
|
|
329
|
-
|
|
330
|
-
const continueAfterParse = (parsed: PluginParseResult) => {
|
|
331
|
-
const { command } = parsed;
|
|
332
|
-
|
|
333
|
-
// Validate phase: collected from parent chain
|
|
334
|
-
const commandPlugins = collectPlugins(command);
|
|
335
|
-
const validateCtx: PluginValidateContext = {
|
|
336
|
-
command,
|
|
337
|
-
rawArgs: parsed.rawArgs,
|
|
338
|
-
positionalArgs: parsed.positionalArgs,
|
|
339
|
-
state,
|
|
340
|
-
};
|
|
341
|
-
|
|
342
|
-
const coreValidate = (): PluginValidateResult | Promise<PluginValidateResult> => {
|
|
343
|
-
// Resolve env schema: command's own envSchema > inherited from parent/root
|
|
344
|
-
const resolveEnvSchema = (cmd: AnyPadroneCommand): AnyPadroneCommand['envSchema'] => {
|
|
345
|
-
if (cmd.envSchema !== undefined) return cmd.envSchema;
|
|
346
|
-
if (cmd.parent) return resolveEnvSchema(cmd.parent);
|
|
347
|
-
return undefined;
|
|
348
|
-
};
|
|
349
|
-
const envSchema = resolveEnvSchema(command);
|
|
350
|
-
|
|
351
|
-
const readStdinForParse = (): Record<string, unknown> | Promise<Record<string, unknown>> => {
|
|
352
|
-
const stdinConfig = command.meta?.stdin;
|
|
353
|
-
if (!stdinConfig) return {};
|
|
354
|
-
|
|
355
|
-
const { field, as } = parseStdinConfig(stdinConfig);
|
|
356
|
-
|
|
357
|
-
// Skip if the field was already provided via CLI flags
|
|
358
|
-
if (field in validateCtx.rawArgs && validateCtx.rawArgs[field] !== undefined) return {};
|
|
359
|
-
|
|
360
|
-
const runtime = getCommandRuntime(existingCommand);
|
|
361
|
-
const stdin = resolveStdin(runtime as any);
|
|
362
|
-
if (!stdin) return {};
|
|
363
|
-
|
|
364
|
-
if (as === 'lines') {
|
|
365
|
-
return (async () => {
|
|
366
|
-
const lines: string[] = [];
|
|
367
|
-
for await (const line of stdin.lines()) {
|
|
368
|
-
lines.push(line);
|
|
369
|
-
}
|
|
370
|
-
return { [field]: lines };
|
|
371
|
-
})();
|
|
372
|
-
}
|
|
373
|
-
return stdin.text().then((text) => (text ? { [field]: text } : {}));
|
|
374
|
-
};
|
|
375
|
-
|
|
376
|
-
const finalize = (
|
|
377
|
-
envData: Record<string, unknown> | undefined,
|
|
378
|
-
stdinData: Record<string, unknown> | undefined,
|
|
379
|
-
): PluginValidateResult | Promise<PluginValidateResult> => {
|
|
380
|
-
const validated = validateArgs(command, validateCtx.rawArgs, validateCtx.positionalArgs, { stdinData, envData });
|
|
381
|
-
return thenMaybe(validated, (v) => v as PluginValidateResult);
|
|
382
|
-
};
|
|
383
|
-
|
|
384
|
-
let envData: Record<string, unknown> | undefined;
|
|
385
|
-
const afterEnv = (envResult: Record<string, unknown> | undefined) => {
|
|
386
|
-
const stdinDataOrPromise = readStdinForParse();
|
|
387
|
-
return thenMaybe(stdinDataOrPromise, (stdinData) => {
|
|
388
|
-
const hasStdinData = Object.keys(stdinData).length > 0;
|
|
389
|
-
return finalize(envResult, hasStdinData ? stdinData : undefined);
|
|
390
|
-
});
|
|
391
|
-
};
|
|
392
|
-
|
|
393
|
-
if (envSchema) {
|
|
394
|
-
const runtime = getCommandRuntime(existingCommand);
|
|
395
|
-
const rawEnv = runtime.env();
|
|
396
|
-
const envValidated = envSchema['~standard'].validate(rawEnv);
|
|
397
|
-
|
|
398
|
-
return thenMaybe(envValidated, (result) => {
|
|
399
|
-
if (!result.issues) {
|
|
400
|
-
envData = result.value as unknown as Record<string, unknown>;
|
|
401
|
-
}
|
|
402
|
-
return afterEnv(envData);
|
|
403
|
-
});
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
return afterEnv(envData);
|
|
407
|
-
};
|
|
408
|
-
|
|
409
|
-
const validatedOrPromise = runPluginChain('validate', commandPlugins, validateCtx, coreValidate);
|
|
410
|
-
|
|
411
|
-
return warnIfUnexpectedAsync(
|
|
412
|
-
thenMaybe(validatedOrPromise, (v) => ({
|
|
413
|
-
command: command as any,
|
|
414
|
-
args: v.args,
|
|
415
|
-
argsResult: v.argsResult,
|
|
416
|
-
})),
|
|
417
|
-
command,
|
|
418
|
-
);
|
|
419
|
-
};
|
|
420
|
-
|
|
421
|
-
return makeThenable(thenMaybe(parsedOrPromise, continueAfterParse)) as any;
|
|
422
|
-
};
|
|
423
|
-
|
|
424
|
-
const stringify: AnyPadroneProgram['stringify'] = (command = '' as any, args) => {
|
|
425
|
-
const commandObj = typeof command === 'string' ? findCommandByName(command, existingCommand.commands) : (command as AnyPadroneCommand);
|
|
426
|
-
if (!commandObj) throw new RoutingError(`Command "${command ?? ''}" not found`);
|
|
427
|
-
|
|
428
|
-
const parts: string[] = [];
|
|
429
|
-
|
|
430
|
-
if (commandObj.path) parts.push(commandObj.path);
|
|
431
|
-
|
|
432
|
-
// Get positional config to determine which args are positional
|
|
433
|
-
const positionalConfig = commandObj.meta?.positional ? parsePositionalConfig(commandObj.meta.positional) : [];
|
|
434
|
-
const positionalNames = new Set(positionalConfig.map((p) => p.name));
|
|
435
|
-
|
|
436
|
-
// Output positional arguments first in order
|
|
437
|
-
if (args && typeof args === 'object') {
|
|
438
|
-
for (const { name, variadic } of positionalConfig) {
|
|
439
|
-
const value = (args as Record<string, unknown>)[name];
|
|
440
|
-
if (value === undefined) continue;
|
|
441
|
-
|
|
442
|
-
if (variadic && Array.isArray(value)) {
|
|
443
|
-
for (const v of value) {
|
|
444
|
-
const vStr = String(v);
|
|
445
|
-
if (vStr.includes(' ')) parts.push(`"${vStr}"`);
|
|
446
|
-
else parts.push(vStr);
|
|
447
|
-
}
|
|
448
|
-
} else {
|
|
449
|
-
const argStr = String(value);
|
|
450
|
-
if (argStr.includes(' ')) parts.push(`"${argStr}"`);
|
|
451
|
-
else parts.push(argStr);
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
// Helper to stringify a value with a given key prefix
|
|
456
|
-
const stringifyValue = (key: string, value: unknown) => {
|
|
457
|
-
if (value === undefined) return;
|
|
458
|
-
|
|
459
|
-
if (typeof value === 'boolean') {
|
|
460
|
-
if (value) parts.push(`--${key}`);
|
|
461
|
-
else parts.push(`--no-${key}`);
|
|
462
|
-
} else if (Array.isArray(value)) {
|
|
463
|
-
// Handle variadic arguments - output each value separately
|
|
464
|
-
for (const v of value) {
|
|
465
|
-
const vStr = String(v);
|
|
466
|
-
if (vStr.includes(' ')) parts.push(`--${key}="${vStr}"`);
|
|
467
|
-
else parts.push(`--${key}=${vStr}`);
|
|
468
|
-
}
|
|
469
|
-
} else if (typeof value === 'object' && value !== null) {
|
|
470
|
-
// Handle nested objects - convert to dot notation
|
|
471
|
-
for (const [nestedKey, nestedValue] of Object.entries(value)) {
|
|
472
|
-
stringifyValue(`${key}.${nestedKey}`, nestedValue);
|
|
473
|
-
}
|
|
474
|
-
} else if (typeof value === 'string') {
|
|
475
|
-
if (value.includes(' ')) parts.push(`--${key}="${value}"`);
|
|
476
|
-
else parts.push(`--${key}=${value}`);
|
|
477
|
-
} else {
|
|
478
|
-
parts.push(`--${key}=${value}`);
|
|
479
|
-
}
|
|
480
|
-
};
|
|
481
|
-
|
|
482
|
-
// Output remaining arguments (non-positional)
|
|
483
|
-
for (const [key, value] of Object.entries(args)) {
|
|
484
|
-
if (value === undefined || positionalNames.has(key)) continue;
|
|
485
|
-
stringifyValue(key, value);
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
return parts.join(' ');
|
|
490
|
-
};
|
|
491
|
-
|
|
492
|
-
type DetailLevel = 'minimal' | 'standard' | 'full';
|
|
493
|
-
type FormatLevel = 'text' | 'ansi' | 'console' | 'markdown' | 'html' | 'json' | 'auto';
|
|
494
|
-
|
|
495
|
-
/**
|
|
496
|
-
* Check if help, version, or completion flags/commands are present in the input.
|
|
497
|
-
* Returns the appropriate action to take, or null if normal execution should proceed.
|
|
498
|
-
*/
|
|
499
|
-
const checkBuiltinCommands = (
|
|
500
|
-
input: string | undefined,
|
|
501
|
-
):
|
|
502
|
-
| { type: 'help'; command?: AnyPadroneCommand; detail?: DetailLevel; format?: FormatLevel }
|
|
503
|
-
| { type: 'version' }
|
|
504
|
-
| { type: 'completion'; shell?: ShellType; setup?: boolean }
|
|
505
|
-
| { type: 'repl'; scope?: string }
|
|
506
|
-
| null => {
|
|
507
|
-
if (!input) return null;
|
|
508
|
-
|
|
509
|
-
const parts = parseCliInputToParts(input);
|
|
510
|
-
const terms = parts.filter((p) => p.type === 'term').map((p) => p.value);
|
|
511
|
-
const args = parts.filter((p) => p.type === 'named' || p.type === 'alias');
|
|
512
|
-
|
|
513
|
-
// Helper to check if a key array matches a single key string
|
|
514
|
-
const keyIs = (key: string[], name: string) => key.length === 1 && key[0] === name;
|
|
515
|
-
|
|
516
|
-
// Check for --help, -h flags (these take precedence over commands)
|
|
517
|
-
const hasHelpFlag = args.some((p) => (p.type === 'named' && keyIs(p.key, 'help')) || (p.type === 'alias' && keyIs(p.key, 'h')));
|
|
518
|
-
|
|
519
|
-
// Extract detail level from --detail=<level> or -d <level>
|
|
520
|
-
const getDetailLevel = (): DetailLevel | undefined => {
|
|
521
|
-
for (const arg of args) {
|
|
522
|
-
if (arg.type === 'named' && keyIs(arg.key, 'detail') && typeof arg.value === 'string') {
|
|
523
|
-
if (arg.value === 'minimal' || arg.value === 'standard' || arg.value === 'full') {
|
|
524
|
-
return arg.value;
|
|
525
|
-
}
|
|
526
|
-
}
|
|
527
|
-
if (arg.type === 'alias' && keyIs(arg.key, 'd') && typeof arg.value === 'string') {
|
|
528
|
-
if (arg.value === 'minimal' || arg.value === 'standard' || arg.value === 'full') {
|
|
529
|
-
return arg.value;
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
}
|
|
533
|
-
return undefined;
|
|
534
|
-
};
|
|
535
|
-
const detail = getDetailLevel();
|
|
536
|
-
|
|
537
|
-
// Extract format from --format=<value> or -f <value>
|
|
538
|
-
const getFormat = (): FormatLevel | undefined => {
|
|
539
|
-
const validFormats: FormatLevel[] = ['text', 'ansi', 'console', 'markdown', 'html', 'json', 'auto'];
|
|
540
|
-
for (const arg of args) {
|
|
541
|
-
if (arg.type === 'named' && keyIs(arg.key, 'format') && typeof arg.value === 'string') {
|
|
542
|
-
if (validFormats.includes(arg.value as FormatLevel)) {
|
|
543
|
-
return arg.value as FormatLevel;
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
if (arg.type === 'alias' && keyIs(arg.key, 'f') && typeof arg.value === 'string') {
|
|
547
|
-
if (validFormats.includes(arg.value as FormatLevel)) {
|
|
548
|
-
return arg.value as FormatLevel;
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
}
|
|
552
|
-
return undefined;
|
|
553
|
-
};
|
|
554
|
-
const format = getFormat();
|
|
555
|
-
|
|
556
|
-
// Check for --version, -v, -V flags
|
|
557
|
-
const hasVersionFlag = args.some(
|
|
558
|
-
(p) => (p.type === 'named' && keyIs(p.key, 'version')) || (p.type === 'alias' && (keyIs(p.key, 'v') || keyIs(p.key, 'V'))),
|
|
559
|
-
);
|
|
560
|
-
|
|
561
|
-
// If the first term is the program name, skip it
|
|
562
|
-
const normalizedTerms = [...terms];
|
|
563
|
-
if (normalizedTerms[0] === existingCommand.name) normalizedTerms.shift();
|
|
564
|
-
|
|
565
|
-
// Check if user has defined 'help', 'version', or 'completion' commands (they take precedence)
|
|
566
|
-
const userHelpCommand = findCommandByName('help', existingCommand.commands);
|
|
567
|
-
const userVersionCommand = findCommandByName('version', existingCommand.commands);
|
|
568
|
-
const userCompletionCommand = findCommandByName('completion', existingCommand.commands);
|
|
569
|
-
|
|
570
|
-
// Check for 'help' command (only if user hasn't defined one)
|
|
571
|
-
// Supports both 'help <command>' and '<command> help' forms
|
|
572
|
-
if (!userHelpCommand && normalizedTerms[0] === 'help') {
|
|
573
|
-
// help <command> - get help for specific command
|
|
574
|
-
const commandName = normalizedTerms.slice(1).join(' ');
|
|
575
|
-
const targetCommand = commandName ? findCommandByName(commandName, existingCommand.commands) : undefined;
|
|
576
|
-
return { type: 'help', command: targetCommand, detail, format };
|
|
577
|
-
}
|
|
578
|
-
if (!userHelpCommand && normalizedTerms.length > 0 && normalizedTerms[normalizedTerms.length - 1] === 'help') {
|
|
579
|
-
// <command> help - get help for specific command (trailing form)
|
|
580
|
-
const commandTerms = normalizedTerms.slice(0, -1);
|
|
581
|
-
// Walk the command tree to find the deepest matching command
|
|
582
|
-
let targetCommand: AnyPadroneCommand | undefined;
|
|
583
|
-
let current = existingCommand;
|
|
584
|
-
for (const term of commandTerms) {
|
|
585
|
-
const found = findCommandByName(term, current.commands);
|
|
586
|
-
if (found) {
|
|
587
|
-
targetCommand = found;
|
|
588
|
-
current = found;
|
|
589
|
-
} else {
|
|
590
|
-
break;
|
|
591
|
-
}
|
|
592
|
-
}
|
|
593
|
-
return { type: 'help', command: targetCommand, detail, format };
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
// Check for 'version' command (only if user hasn't defined one)
|
|
597
|
-
if (!userVersionCommand && normalizedTerms[0] === 'version') {
|
|
598
|
-
return { type: 'version' };
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
// Check for 'completion' command (only if user hasn't defined one)
|
|
602
|
-
if (!userCompletionCommand && normalizedTerms[0] === 'completion') {
|
|
603
|
-
const shellArg = normalizedTerms[1] as ShellType | undefined;
|
|
604
|
-
const validShells: ShellType[] = ['bash', 'zsh', 'fish', 'powershell'];
|
|
605
|
-
const shell = shellArg && validShells.includes(shellArg) ? shellArg : undefined;
|
|
606
|
-
const setup = args.some((p) => p.type === 'named' && keyIs(p.key, 'setup'));
|
|
607
|
-
return { type: 'completion', shell, setup };
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
// Handle help flag - find the command being requested
|
|
611
|
-
if (hasHelpFlag) {
|
|
612
|
-
// Filter out help-related terms and flags to find the target command
|
|
613
|
-
const commandTerms = normalizedTerms.filter((t) => t !== 'help');
|
|
614
|
-
const commandName = commandTerms.join(' ');
|
|
615
|
-
const targetCommand = commandName ? findCommandByName(commandName, existingCommand.commands) : undefined;
|
|
616
|
-
return { type: 'help', command: targetCommand, detail, format };
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
// Handle version flag (only for root command, i.e., no subcommand terms)
|
|
620
|
-
if (hasVersionFlag && normalizedTerms.length === 0) {
|
|
621
|
-
return { type: 'version' };
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
// Check for --repl flag
|
|
625
|
-
const hasReplFlag = args.some((p) => p.type === 'named' && keyIs(p.key, 'repl'));
|
|
626
|
-
if (hasReplFlag) {
|
|
627
|
-
const scope = normalizedTerms.length > 0 ? normalizedTerms.join(' ') : undefined;
|
|
628
|
-
return { type: 'repl', scope };
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
return null;
|
|
632
|
-
};
|
|
633
|
-
|
|
634
|
-
/**
|
|
635
|
-
* Extract the config file path from --config=<path> or -c <path> flags.
|
|
636
|
-
*/
|
|
637
|
-
const extractConfigPath = (input: string | undefined): string | undefined => {
|
|
638
|
-
if (!input) return undefined;
|
|
639
|
-
|
|
640
|
-
const parts = parseCliInputToParts(input);
|
|
641
|
-
const args = parts.filter((p) => p.type === 'named' || p.type === 'alias');
|
|
642
|
-
|
|
643
|
-
for (const arg of args) {
|
|
644
|
-
if (arg.type === 'named' && arg.key.length === 1 && arg.key[0] === 'config' && typeof arg.value === 'string') {
|
|
645
|
-
return arg.value;
|
|
646
|
-
}
|
|
647
|
-
if (arg.type === 'alias' && arg.key.length === 1 && arg.key[0] === 'c' && typeof arg.value === 'string') {
|
|
648
|
-
return arg.value;
|
|
649
|
-
}
|
|
650
|
-
}
|
|
651
|
-
return undefined;
|
|
652
|
-
};
|
|
653
|
-
|
|
654
|
-
/**
|
|
655
|
-
* Core execution logic shared by eval() and cli().
|
|
656
|
-
* errorMode controls validation error behavior:
|
|
657
|
-
* - 'soft': return result with issues (eval behavior)
|
|
658
|
-
* - 'hard': print error + help and throw (cli-without-input behavior)
|
|
659
|
-
*/
|
|
660
|
-
const execCommand = (resolvedInput: string | undefined, evalOptions?: PadroneEvalPreferences, errorMode: 'soft' | 'hard' = 'soft') => {
|
|
661
|
-
const baseRuntime = getCommandRuntime(existingCommand);
|
|
662
|
-
const runtime = evalOptions?.runtime
|
|
663
|
-
? Object.assign({}, baseRuntime, Object.fromEntries(Object.entries(evalOptions.runtime).filter(([, v]) => v !== undefined)))
|
|
664
|
-
: baseRuntime;
|
|
665
|
-
|
|
666
|
-
// Check for built-in help/version/completion commands and flags (bypass plugins)
|
|
667
|
-
const builtin = checkBuiltinCommands(resolvedInput);
|
|
668
|
-
|
|
669
|
-
if (builtin) {
|
|
670
|
-
if (builtin.type === 'help') {
|
|
671
|
-
const helpText = generateHelp(existingCommand, builtin.command ?? existingCommand, {
|
|
672
|
-
detail: builtin.detail,
|
|
673
|
-
format: builtin.format ?? runtime.format,
|
|
674
|
-
});
|
|
675
|
-
runtime.output(helpText);
|
|
676
|
-
return {
|
|
677
|
-
command: existingCommand,
|
|
678
|
-
args: undefined,
|
|
679
|
-
result: helpText,
|
|
680
|
-
} as any;
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
if (builtin.type === 'version') {
|
|
684
|
-
const version = getVersion(existingCommand.version);
|
|
685
|
-
runtime.output(version);
|
|
686
|
-
return {
|
|
687
|
-
command: existingCommand,
|
|
688
|
-
args: undefined,
|
|
689
|
-
result: version,
|
|
690
|
-
} as any;
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
if (builtin.type === 'completion') {
|
|
694
|
-
return import('./completion.ts').then(({ detectShell, generateCompletionOutput, setupCompletions }) => {
|
|
695
|
-
if (builtin.setup) {
|
|
696
|
-
const shell = builtin.shell ?? detectShell();
|
|
697
|
-
if (!shell) {
|
|
698
|
-
throw new Error('Could not detect shell. Specify one: completion bash --setup');
|
|
699
|
-
}
|
|
700
|
-
const result = setupCompletions(existingCommand.name, shell);
|
|
701
|
-
const message = `${result.updated ? 'Updated' : 'Added'} ${existingCommand.name} completions in ${result.file}`;
|
|
702
|
-
runtime.output(message);
|
|
703
|
-
return {
|
|
704
|
-
command: existingCommand,
|
|
705
|
-
args: undefined,
|
|
706
|
-
result: message,
|
|
707
|
-
};
|
|
708
|
-
}
|
|
709
|
-
const completionScript = generateCompletionOutput(existingCommand, builtin.shell);
|
|
710
|
-
runtime.output(completionScript);
|
|
711
|
-
return {
|
|
712
|
-
command: existingCommand,
|
|
713
|
-
args: undefined,
|
|
714
|
-
result: completionScript,
|
|
715
|
-
};
|
|
716
|
-
}) as any;
|
|
717
|
-
}
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
// Shared plugin state for this execution
|
|
721
|
-
const state: Record<string, unknown> = {};
|
|
722
|
-
const rootPlugins = existingCommand.plugins ?? [];
|
|
723
|
-
|
|
724
|
-
const runPipeline = () => {
|
|
725
|
-
// ── Phase 1: Parse ──────────────────────────────────────────────────
|
|
726
|
-
const parseCtx: PluginParseContext = { input: resolvedInput, command: existingCommand, state };
|
|
727
|
-
|
|
728
|
-
const coreParse = (): PluginParseResult => {
|
|
729
|
-
const { command, rawArgs, args, unmatchedTerms } = parseCommand(parseCtx.input);
|
|
730
|
-
|
|
731
|
-
// Default help: command with no action → show its help when there's nothing to execute.
|
|
732
|
-
const hasSubcommands = command.commands && command.commands.length > 0;
|
|
733
|
-
const hasSchema = command.argsSchema != null;
|
|
734
|
-
if (!command.action && (hasSubcommands || !hasSchema) && unmatchedTerms.length === 0) {
|
|
735
|
-
const helpText = generateHelp(existingCommand, command, { format: runtime.format });
|
|
736
|
-
runtime.output(helpText);
|
|
737
|
-
return {
|
|
738
|
-
command: command,
|
|
739
|
-
rawArgs: { '~help': helpText } as Record<string, unknown>,
|
|
740
|
-
positionalArgs: [],
|
|
741
|
-
};
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
// Reject unmatched terms when the matched command doesn't accept positional args
|
|
745
|
-
if (unmatchedTerms.length > 0) {
|
|
746
|
-
const hasPositionalConfig = command.meta?.positional && command.meta.positional.length > 0;
|
|
747
|
-
if (!hasPositionalConfig) {
|
|
748
|
-
const isRootCommand = command === existingCommand;
|
|
749
|
-
const commandDisplayName = command.name || command.aliases?.[0] || command.path || '(default)';
|
|
750
|
-
|
|
751
|
-
// Collect candidate names for fuzzy suggestion
|
|
752
|
-
const candidateNames: string[] = [];
|
|
753
|
-
if (isRootCommand && existingCommand.commands) {
|
|
754
|
-
for (const cmd of existingCommand.commands) {
|
|
755
|
-
if (!cmd.hidden) {
|
|
756
|
-
candidateNames.push(cmd.name);
|
|
757
|
-
if (cmd.aliases) candidateNames.push(...cmd.aliases);
|
|
758
|
-
}
|
|
759
|
-
}
|
|
760
|
-
} else if (command.commands) {
|
|
761
|
-
for (const cmd of command.commands) {
|
|
762
|
-
if (!cmd.hidden) {
|
|
763
|
-
candidateNames.push(cmd.name);
|
|
764
|
-
if (cmd.aliases) candidateNames.push(...cmd.aliases);
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
const suggestion = suggestSimilar(unmatchedTerms[0]!, candidateNames);
|
|
770
|
-
const suggestions = suggestion ? [suggestion] : [];
|
|
771
|
-
const baseMsg = isRootCommand
|
|
772
|
-
? `Unknown command: ${unmatchedTerms[0]}`
|
|
773
|
-
: `Unexpected arguments for '${commandDisplayName}': ${unmatchedTerms.join(' ')}`;
|
|
774
|
-
const errorMsg = suggestions.length ? `${baseMsg}\n\n ${suggestions[0]}` : baseMsg;
|
|
775
|
-
|
|
776
|
-
if (errorMode === 'hard') {
|
|
777
|
-
runtime.error(errorMsg);
|
|
778
|
-
// When we have a suggestion, show a compact single-line "Available commands" note
|
|
779
|
-
// instead of the full help text to avoid overwhelming the user
|
|
780
|
-
if (suggestions.length > 0) {
|
|
781
|
-
const targetCmd = isRootCommand ? existingCommand : command;
|
|
782
|
-
const visibleCommands = (targetCmd.commands ?? []).filter((c) => !c.hidden && c.name);
|
|
783
|
-
if (visibleCommands.length > 0) {
|
|
784
|
-
const cmdList = visibleCommands.map((c) => c.name).join(', ');
|
|
785
|
-
runtime.output(`\nAvailable commands: ${cmdList}`);
|
|
786
|
-
}
|
|
787
|
-
} else {
|
|
788
|
-
const helpText = generateHelp(existingCommand, isRootCommand ? existingCommand : command, { format: runtime.format });
|
|
789
|
-
runtime.error(helpText);
|
|
790
|
-
}
|
|
791
|
-
throw new RoutingError(errorMsg, { suggestions, command: command.path || command.name });
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
// Soft mode: throw too — this is a routing error, not a validation issue
|
|
795
|
-
throw new RoutingError(errorMsg, { suggestions, command: command.path || command.name });
|
|
796
|
-
}
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
return { command, rawArgs, positionalArgs: args };
|
|
800
|
-
};
|
|
801
|
-
|
|
802
|
-
// Parse phase: root plugins only
|
|
803
|
-
const parsedOrPromise = runPluginChain('parse', rootPlugins, parseCtx, coreParse);
|
|
804
|
-
|
|
805
|
-
// ── Phases 2 & 3 chained after parse ────────────────────────────────
|
|
806
|
-
const continueAfterParse = (parsed: PluginParseResult) => {
|
|
807
|
-
const { command } = parsed;
|
|
808
|
-
// Validate/execute: collected from parent chain
|
|
809
|
-
const commandPlugins = collectPlugins(command);
|
|
810
|
-
|
|
811
|
-
// Short-circuit: parse returned a help result
|
|
812
|
-
if (parsed.rawArgs['~help']) {
|
|
813
|
-
return {
|
|
814
|
-
command: command,
|
|
815
|
-
args: undefined,
|
|
816
|
-
result: parsed.rawArgs['~help'],
|
|
817
|
-
} as any;
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
// ── Phase 2: Validate ───────────────────────────────────────────
|
|
821
|
-
const validateCtx: PluginValidateContext = {
|
|
822
|
-
command,
|
|
823
|
-
rawArgs: parsed.rawArgs,
|
|
824
|
-
positionalArgs: parsed.positionalArgs,
|
|
825
|
-
state,
|
|
826
|
-
};
|
|
827
|
-
|
|
828
|
-
const coreValidate = (): PluginValidateResult | Promise<PluginValidateResult> => {
|
|
829
|
-
// Determine interactivity
|
|
830
|
-
let flagInteractive: boolean | undefined;
|
|
831
|
-
if (hasInteractiveConfig(command.meta)) {
|
|
832
|
-
if (validateCtx.rawArgs.interactive !== undefined) {
|
|
833
|
-
flagInteractive = validateCtx.rawArgs.interactive !== false && validateCtx.rawArgs.interactive !== 'false';
|
|
834
|
-
delete validateCtx.rawArgs.interactive;
|
|
835
|
-
}
|
|
836
|
-
if (validateCtx.rawArgs.i !== undefined) {
|
|
837
|
-
flagInteractive = validateCtx.rawArgs.i !== false && validateCtx.rawArgs.i !== 'false';
|
|
838
|
-
delete validateCtx.rawArgs.i;
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
const runtimeDefault: boolean | undefined =
|
|
843
|
-
runtime.interactive === 'forced' ? true : runtime.interactive === 'disabled' ? false : undefined;
|
|
844
|
-
const effectiveInteractive: boolean | undefined = flagInteractive ?? evalOptions?.interactive ?? runtimeDefault;
|
|
845
|
-
// Suppress interactive prompts when the command reads stdin — prompts share stdin which is already consumed/closed.
|
|
846
|
-
const commandUsesStdin = !!command.meta?.stdin;
|
|
847
|
-
const stdinIsPiped =
|
|
848
|
-
commandUsesStdin && (runtime.stdin ? !runtime.stdin.isTTY : typeof process !== 'undefined' && process.stdin?.isTTY !== true);
|
|
849
|
-
const interactivitySuppressed =
|
|
850
|
-
runtime.interactive === 'unsupported' || effectiveInteractive === false || (stdinIsPiped && effectiveInteractive !== true);
|
|
851
|
-
const forceInteractive = !interactivitySuppressed && effectiveInteractive === true;
|
|
852
|
-
|
|
853
|
-
// Extract config file path from --config or -c flag
|
|
854
|
-
const configPath = extractConfigPath(parseCtx.input);
|
|
855
|
-
|
|
856
|
-
// Resolve config files: command's own configFiles > inherited from parent/root
|
|
857
|
-
const resolveConfigFiles = (cmd: AnyPadroneCommand): string[] | undefined => {
|
|
858
|
-
if (cmd.configFiles !== undefined) return cmd.configFiles;
|
|
859
|
-
if (cmd.parent) return resolveConfigFiles(cmd.parent);
|
|
860
|
-
return undefined;
|
|
861
|
-
};
|
|
862
|
-
const effectiveConfigFiles = resolveConfigFiles(command);
|
|
863
|
-
|
|
864
|
-
// Resolve config schema: command's own configSchema > inherited from parent/root
|
|
865
|
-
const resolveConfigSchema = (cmd: AnyPadroneCommand): AnyPadroneCommand['configSchema'] => {
|
|
866
|
-
if (cmd.configSchema !== undefined) return cmd.configSchema;
|
|
867
|
-
if (cmd.parent) return resolveConfigSchema(cmd.parent);
|
|
868
|
-
return undefined;
|
|
869
|
-
};
|
|
870
|
-
const configSchema = resolveConfigSchema(command);
|
|
871
|
-
|
|
872
|
-
// Resolve env schema: command's own envSchema > inherited from parent/root
|
|
873
|
-
const resolveEnvSchema = (cmd: AnyPadroneCommand): AnyPadroneCommand['envSchema'] => {
|
|
874
|
-
if (cmd.envSchema !== undefined) return cmd.envSchema;
|
|
875
|
-
if (cmd.parent) return resolveEnvSchema(cmd.parent);
|
|
876
|
-
return undefined;
|
|
877
|
-
};
|
|
878
|
-
const envSchema = resolveEnvSchema(command);
|
|
879
|
-
|
|
880
|
-
// Determine config data: explicit --config flag > auto-discovered config
|
|
881
|
-
let configData: Record<string, unknown> | undefined;
|
|
882
|
-
if (configPath) {
|
|
883
|
-
configData = runtime.loadConfigFile(configPath);
|
|
884
|
-
} else if (effectiveConfigFiles?.length) {
|
|
885
|
-
const foundConfigPath = runtime.findFile(effectiveConfigFiles);
|
|
886
|
-
if (foundConfigPath) {
|
|
887
|
-
configData = runtime.loadConfigFile(foundConfigPath) ?? configData;
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
|
|
891
|
-
// Step 1: Validate config data against schema if provided
|
|
892
|
-
const validateConfig = (): Record<string, unknown> | undefined | Promise<Record<string, unknown> | undefined> => {
|
|
893
|
-
if (configData && configSchema) {
|
|
894
|
-
const configValidated = configSchema['~standard'].validate(configData);
|
|
895
|
-
return thenMaybe(configValidated, (result) => {
|
|
896
|
-
if (result.issues) {
|
|
897
|
-
const issueMessages = result.issues
|
|
898
|
-
.map((i: StandardSchemaV1.Issue) => ` - ${i.path?.join('.') || 'root'}: ${i.message}`)
|
|
899
|
-
.join('\n');
|
|
900
|
-
throw new ConfigError(`Invalid config file:\n${issueMessages}`, {
|
|
901
|
-
command: command.path || command.name,
|
|
902
|
-
});
|
|
903
|
-
}
|
|
904
|
-
return result.value as unknown as Record<string, unknown>;
|
|
905
|
-
});
|
|
906
|
-
}
|
|
907
|
-
return configData;
|
|
908
|
-
};
|
|
909
|
-
|
|
910
|
-
// Step 2: Validate env vars
|
|
911
|
-
const validateEnv = (): Record<string, unknown> | undefined | Promise<Record<string, unknown> | undefined> => {
|
|
912
|
-
let envData: Record<string, unknown> | undefined;
|
|
913
|
-
if (envSchema) {
|
|
914
|
-
const rawEnv = runtime.env();
|
|
915
|
-
const envValidated = envSchema['~standard'].validate(rawEnv);
|
|
916
|
-
return thenMaybe(envValidated, (result) => {
|
|
917
|
-
if (!result.issues) {
|
|
918
|
-
envData = result.value as unknown as Record<string, unknown>;
|
|
919
|
-
}
|
|
920
|
-
return envData;
|
|
921
|
-
});
|
|
922
|
-
}
|
|
923
|
-
return envData;
|
|
924
|
-
};
|
|
925
|
-
|
|
926
|
-
// Step 3: Read stdin if configured and not already provided via CLI
|
|
927
|
-
const readStdin = (): Record<string, unknown> | Promise<Record<string, unknown>> => {
|
|
928
|
-
const stdinConfig = command.meta?.stdin;
|
|
929
|
-
if (!stdinConfig) return {};
|
|
930
|
-
|
|
931
|
-
const { field, as } = parseStdinConfig(stdinConfig);
|
|
932
|
-
|
|
933
|
-
// Skip if the field was already provided via CLI flags (highest precedence)
|
|
934
|
-
if (field in validateCtx.rawArgs && validateCtx.rawArgs[field] !== undefined) return {};
|
|
935
|
-
|
|
936
|
-
// Resolve stdin: use runtime's custom stdin, or default if piped.
|
|
937
|
-
// Returns undefined when stdin is a TTY or unavailable.
|
|
938
|
-
const stdin = resolveStdin(runtime as any);
|
|
939
|
-
if (!stdin) return {};
|
|
940
|
-
|
|
941
|
-
if (as === 'lines') {
|
|
942
|
-
return (async () => {
|
|
943
|
-
const lines: string[] = [];
|
|
944
|
-
for await (const line of stdin.lines()) {
|
|
945
|
-
lines.push(line);
|
|
946
|
-
}
|
|
947
|
-
return { [field]: lines };
|
|
948
|
-
})();
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
// Default: read all as text
|
|
952
|
-
return stdin.text().then((text) => {
|
|
953
|
-
// Don't inject empty stdin
|
|
954
|
-
if (!text) return {};
|
|
955
|
-
return { [field]: text };
|
|
956
|
-
});
|
|
957
|
-
};
|
|
958
|
-
|
|
959
|
-
// Step 4: Preprocess, interactive prompt, and validate
|
|
960
|
-
const finalizeValidation = (
|
|
961
|
-
validatedConfigData: Record<string, unknown> | undefined,
|
|
962
|
-
envData: Record<string, unknown> | undefined,
|
|
963
|
-
stdinData: Record<string, unknown> | undefined,
|
|
964
|
-
): PluginValidateResult | Promise<PluginValidateResult> => {
|
|
965
|
-
const preprocessedArgs = buildCommandArgs(command, validateCtx.rawArgs, validateCtx.positionalArgs, {
|
|
966
|
-
stdinData,
|
|
967
|
-
envData,
|
|
968
|
-
configData: validatedConfigData,
|
|
969
|
-
});
|
|
970
|
-
|
|
971
|
-
// Early validation: check provided args for errors before prompting.
|
|
972
|
-
// This catches unknown options and invalid values on explicitly-provided fields
|
|
973
|
-
// so the user isn't asked interactive questions for a doomed command.
|
|
974
|
-
const willPrompt = !interactivitySuppressed && runtime.prompt && hasInteractiveConfig(command.meta);
|
|
975
|
-
if (willPrompt) {
|
|
976
|
-
const unknowns = checkUnknownArgs(command, preprocessedArgs);
|
|
977
|
-
if (unknowns.length > 0) {
|
|
978
|
-
const issues: StandardSchemaV1.Issue[] = unknowns.map(({ key, suggestion }) => ({
|
|
979
|
-
path: [key],
|
|
980
|
-
message: suggestion ? `Unknown option: "${key}". ${suggestion}` : `Unknown option: "${key}"`,
|
|
981
|
-
}));
|
|
982
|
-
return { args: undefined, argsResult: { issues } as any };
|
|
983
|
-
}
|
|
984
|
-
|
|
985
|
-
// Run schema validation on what we have so far (before prompting fills missing fields).
|
|
986
|
-
// Only fail on issues for fields the user explicitly provided — skip issues for
|
|
987
|
-
// missing/undefined fields since those will be filled by interactive prompts.
|
|
988
|
-
if (command.argsSchema) {
|
|
989
|
-
const providedKeys = new Set(Object.keys(preprocessedArgs).filter((k) => preprocessedArgs[k] !== undefined));
|
|
990
|
-
const earlyCheck = command.argsSchema['~standard'].validate(preprocessedArgs);
|
|
991
|
-
const checkForProvidedFieldErrors = (result: StandardSchemaV1.Result<unknown>): PluginValidateResult | undefined => {
|
|
992
|
-
if (!result.issues) return undefined;
|
|
993
|
-
// Only keep issues whose path starts with a key the user actually provided
|
|
994
|
-
const providedFieldIssues = result.issues.filter((issue) => {
|
|
995
|
-
const rootKey = issue.path?.[0];
|
|
996
|
-
return rootKey !== undefined && providedKeys.has(String(rootKey));
|
|
997
|
-
});
|
|
998
|
-
if (providedFieldIssues.length > 0) {
|
|
999
|
-
return { args: undefined, argsResult: { issues: providedFieldIssues } as any };
|
|
1000
|
-
}
|
|
1001
|
-
return undefined;
|
|
1002
|
-
};
|
|
1003
|
-
const earlyResult = thenMaybe(earlyCheck, (result) => {
|
|
1004
|
-
const errors = checkForProvidedFieldErrors(result);
|
|
1005
|
-
if (errors) return errors;
|
|
1006
|
-
return undefined;
|
|
1007
|
-
});
|
|
1008
|
-
if (earlyResult instanceof Promise) {
|
|
1009
|
-
return earlyResult.then((err) => {
|
|
1010
|
-
if (err) return err;
|
|
1011
|
-
return continueWithPrompt(preprocessedArgs);
|
|
1012
|
-
});
|
|
1013
|
-
}
|
|
1014
|
-
if (earlyResult) return earlyResult;
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1017
|
-
|
|
1018
|
-
return continueWithPrompt(preprocessedArgs);
|
|
1019
|
-
};
|
|
1020
|
-
|
|
1021
|
-
const continueWithPrompt = (preprocessedArgs: Record<string, unknown>): PluginValidateResult | Promise<PluginValidateResult> => {
|
|
1022
|
-
const willPrompt = !interactivitySuppressed && runtime.prompt && hasInteractiveConfig(command.meta);
|
|
1023
|
-
const afterInteractive = willPrompt
|
|
1024
|
-
? promptInteractiveFields(preprocessedArgs, command, runtime, forceInteractive || undefined)
|
|
1025
|
-
: preprocessedArgs;
|
|
1026
|
-
|
|
1027
|
-
return thenMaybe(afterInteractive, (filledArgs) => {
|
|
1028
|
-
const validated = validateCommandArgs(command, filledArgs);
|
|
1029
|
-
return thenMaybe(validated, (v) => v as PluginValidateResult);
|
|
1030
|
-
});
|
|
1031
|
-
};
|
|
1032
|
-
|
|
1033
|
-
// Chain: config → env → stdin → validate
|
|
1034
|
-
const validatedConfig = validateConfig();
|
|
1035
|
-
return thenMaybe(validatedConfig, (cfgData) => {
|
|
1036
|
-
const validatedEnv = validateEnv();
|
|
1037
|
-
return thenMaybe(validatedEnv, (envData) => {
|
|
1038
|
-
const stdinDataOrPromise = readStdin();
|
|
1039
|
-
return thenMaybe(stdinDataOrPromise, (stdinData) => {
|
|
1040
|
-
const hasStdinData = Object.keys(stdinData).length > 0;
|
|
1041
|
-
return finalizeValidation(cfgData, envData, hasStdinData ? stdinData : undefined);
|
|
1042
|
-
});
|
|
1043
|
-
});
|
|
1044
|
-
});
|
|
1045
|
-
};
|
|
1046
|
-
|
|
1047
|
-
const validatedOrPromise = runPluginChain('validate', commandPlugins, validateCtx, coreValidate);
|
|
1048
|
-
|
|
1049
|
-
// ── Phase 3: Execute (or handle validation errors) ──────────────
|
|
1050
|
-
const continueAfterValidate = (v: PluginValidateResult) => {
|
|
1051
|
-
// Handle validation failures
|
|
1052
|
-
if (v.argsResult?.issues) {
|
|
1053
|
-
// Collect known option names for fuzzy suggestion on unknown keys
|
|
1054
|
-
let knownOptions: string[] | undefined;
|
|
1055
|
-
const getKnownOptions = () => {
|
|
1056
|
-
if (knownOptions) return knownOptions;
|
|
1057
|
-
knownOptions = [];
|
|
1058
|
-
if (command.argsSchema) {
|
|
1059
|
-
try {
|
|
1060
|
-
const js = command.argsSchema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }) as Record<string, any>;
|
|
1061
|
-
if (js.type === 'object' && js.properties) knownOptions = Object.keys(js.properties);
|
|
1062
|
-
} catch {
|
|
1063
|
-
/* ignore */
|
|
1064
|
-
}
|
|
1065
|
-
}
|
|
1066
|
-
return knownOptions;
|
|
1067
|
-
};
|
|
1068
|
-
|
|
1069
|
-
const issueMessages = v.argsResult.issues
|
|
1070
|
-
.map((i: StandardSchemaV1.Issue) => {
|
|
1071
|
-
const base = ` - ${i.path?.join('.') || 'root'}: ${i.message}`;
|
|
1072
|
-
// Try to suggest for unrecognized key errors
|
|
1073
|
-
const issueAny = i as any;
|
|
1074
|
-
const unrecognizedKeys: string[] | undefined =
|
|
1075
|
-
issueAny.keys ?? i.message?.match(/[Uu]nrecognized key(?:s)?[^"]*"([^"]+)"/)?.slice(1);
|
|
1076
|
-
if (unrecognizedKeys?.length) {
|
|
1077
|
-
const hints = unrecognizedKeys.map((k: string) => suggestSimilar(k, getKnownOptions())).filter(Boolean);
|
|
1078
|
-
if (hints.length) return `${base}\n ${hints.join('\n ')}`;
|
|
1079
|
-
}
|
|
1080
|
-
return base;
|
|
1081
|
-
})
|
|
1082
|
-
.join('\n');
|
|
1083
|
-
|
|
1084
|
-
if (errorMode === 'hard') {
|
|
1085
|
-
const helpText = generateHelp(existingCommand, command, { format: runtime.format });
|
|
1086
|
-
runtime.error(`Validation error:\n${issueMessages}`);
|
|
1087
|
-
runtime.error(helpText);
|
|
1088
|
-
throw new ValidationError(`Validation error:\n${issueMessages}`, v.argsResult.issues as any, {
|
|
1089
|
-
suggestions: v.argsResult.issues.flatMap((i: any) => {
|
|
1090
|
-
const keys: string[] | undefined = i.keys ?? i.message?.match(/[Uu]nrecognized key(?:s)?[^"]*"([^"]+)"/)?.slice(1);
|
|
1091
|
-
if (!keys?.length) return [];
|
|
1092
|
-
return keys.map((k: string) => suggestSimilar(k, getKnownOptions())).filter(Boolean);
|
|
1093
|
-
}),
|
|
1094
|
-
command: command.path || command.name,
|
|
1095
|
-
});
|
|
1096
|
-
}
|
|
1097
|
-
|
|
1098
|
-
// Soft mode: return result with issues, skip the action
|
|
1099
|
-
return {
|
|
1100
|
-
command: command as any,
|
|
1101
|
-
args: undefined,
|
|
1102
|
-
argsResult: v.argsResult,
|
|
1103
|
-
result: undefined,
|
|
1104
|
-
};
|
|
1105
|
-
}
|
|
1106
|
-
|
|
1107
|
-
const executeCtx: PluginExecuteContext = {
|
|
1108
|
-
command,
|
|
1109
|
-
args: v.args,
|
|
1110
|
-
state,
|
|
1111
|
-
};
|
|
1112
|
-
|
|
1113
|
-
const coreExecute = (): PluginExecuteResult => {
|
|
1114
|
-
const handler = command.action ?? noop;
|
|
1115
|
-
const ctx = evalOptions?.runtime ? { ...createActionContext(command), runtime } : createActionContext(command);
|
|
1116
|
-
const result = handler(executeCtx.args as any, ctx);
|
|
1117
|
-
return { result };
|
|
1118
|
-
};
|
|
1119
|
-
|
|
1120
|
-
const executedOrPromise = runPluginChain('execute', commandPlugins, executeCtx, coreExecute);
|
|
1121
|
-
|
|
1122
|
-
return thenMaybe(executedOrPromise, (e) => {
|
|
1123
|
-
const commandResult = {
|
|
1124
|
-
command: command as any,
|
|
1125
|
-
args: v.args,
|
|
1126
|
-
argsResult: v.argsResult,
|
|
1127
|
-
result: e.result,
|
|
1128
|
-
};
|
|
1129
|
-
|
|
1130
|
-
if (command.autoOutput ?? evalOptions?.autoOutput ?? true) {
|
|
1131
|
-
const outputOrPromise = outputValue(e.result, runtime.output);
|
|
1132
|
-
if (outputOrPromise instanceof Promise) {
|
|
1133
|
-
return outputOrPromise.then(() => commandResult);
|
|
1134
|
-
}
|
|
1135
|
-
}
|
|
1136
|
-
|
|
1137
|
-
return commandResult;
|
|
1138
|
-
});
|
|
1139
|
-
};
|
|
1140
|
-
|
|
1141
|
-
return thenMaybe(warnIfUnexpectedAsync(validatedOrPromise, command), continueAfterValidate) as any;
|
|
1142
|
-
};
|
|
1143
|
-
|
|
1144
|
-
return thenMaybe(parsedOrPromise, continueAfterParse) as any;
|
|
1145
|
-
};
|
|
1146
|
-
|
|
1147
|
-
return wrapWithLifecycle(rootPlugins, existingCommand, state, resolvedInput, runPipeline, (result) => ({
|
|
1148
|
-
command: existingCommand,
|
|
1149
|
-
args: undefined,
|
|
1150
|
-
argsResult: undefined,
|
|
1151
|
-
result,
|
|
1152
|
-
})) as any;
|
|
1153
|
-
};
|
|
1154
|
-
|
|
1155
|
-
const evalCommand: AnyPadroneProgram['eval'] = (input, evalOptions) => {
|
|
1156
|
-
return makeThenable(execCommand(input as string, evalOptions, 'soft'));
|
|
1157
|
-
};
|
|
1158
|
-
|
|
1159
|
-
/**
|
|
1160
|
-
* Collects plugins from the command's parent chain (root → ... → target).
|
|
1161
|
-
* Root/program plugins come first (outermost), target command's plugins last (innermost).
|
|
1162
|
-
*
|
|
1163
|
-
* The `programRoot` parameter provides the current program command, because
|
|
1164
|
-
* subcommands' `.parent` references may be stale (builders are immutable — each
|
|
1165
|
-
* method returns a new builder, so a subcommand's parent was captured before
|
|
1166
|
-
* `.use()` was called on the program). We substitute `programRoot` for the
|
|
1167
|
-
* top of the chain to ensure program-level plugins are always included.
|
|
1168
|
-
*/
|
|
1169
|
-
const collectPlugins = (cmd: AnyPadroneCommand): PadronePlugin[] => {
|
|
1170
|
-
const chain: PadronePlugin[][] = [];
|
|
1171
|
-
let current: AnyPadroneCommand | undefined = cmd;
|
|
1172
|
-
while (current) {
|
|
1173
|
-
// If this is the root (no parent), use existingCommand's plugins instead
|
|
1174
|
-
// to pick up plugins added after subcommands were defined.
|
|
1175
|
-
if (!current.parent) {
|
|
1176
|
-
if (existingCommand.plugins?.length) chain.unshift(existingCommand.plugins);
|
|
1177
|
-
} else {
|
|
1178
|
-
if (current.plugins?.length) chain.unshift(current.plugins);
|
|
1179
|
-
}
|
|
1180
|
-
current = current.parent;
|
|
1181
|
-
}
|
|
1182
|
-
return chain.flat();
|
|
1183
|
-
};
|
|
1184
|
-
|
|
1185
|
-
// Forward declaration — assigned by the repl method in the return object, used by cli() for --repl.
|
|
1186
|
-
let replFn: (options?: PadroneReplPreferences) => AsyncIterable<any>;
|
|
1187
|
-
const replActiveRef = { value: false };
|
|
1188
|
-
|
|
1189
|
-
const cli: AnyPadroneProgram['cli'] = (cliOptions) => {
|
|
1190
|
-
const runtime = getCommandRuntime(existingCommand);
|
|
1191
|
-
const resolvedInput = (runtime.argv().join(' ') || undefined) as string | undefined;
|
|
1192
|
-
|
|
1193
|
-
// Check for --repl flag before normal execution
|
|
1194
|
-
if (cliOptions?.repl !== false) {
|
|
1195
|
-
const builtin = checkBuiltinCommands(resolvedInput);
|
|
1196
|
-
if (builtin?.type === 'repl') {
|
|
1197
|
-
const replPrefs: PadroneReplPreferences = {
|
|
1198
|
-
...(typeof cliOptions?.repl === 'object' ? cliOptions.repl : {}),
|
|
1199
|
-
scope: builtin.scope,
|
|
1200
|
-
autoOutput: (typeof cliOptions?.repl === 'object' ? cliOptions.repl.autoOutput : undefined) ?? cliOptions?.autoOutput,
|
|
1201
|
-
};
|
|
1202
|
-
const drainRepl = async () => {
|
|
1203
|
-
for await (const _ of replFn(replPrefs)) {
|
|
1204
|
-
// Results are handled by command actions
|
|
1205
|
-
}
|
|
1206
|
-
return { command: existingCommand, args: undefined, result: undefined } as any;
|
|
1207
|
-
};
|
|
1208
|
-
return drainRepl() as any;
|
|
1209
|
-
}
|
|
1210
|
-
}
|
|
1211
|
-
|
|
1212
|
-
// Start background update check (non-blocking)
|
|
1213
|
-
let updateCheckPromise: Promise<(() => void) | undefined> | undefined;
|
|
1214
|
-
if (existingCommand.updateCheck) {
|
|
1215
|
-
// Respect --no-update-check flag
|
|
1216
|
-
const hasNoUpdateCheckFlag =
|
|
1217
|
-
resolvedInput &&
|
|
1218
|
-
parseCliInputToParts(resolvedInput).some((p) => p.type === 'named' && p.key.length === 1 && p.key[0] === 'no-update-check');
|
|
1219
|
-
if (!hasNoUpdateCheckFlag) {
|
|
1220
|
-
const currentVersion = getVersion(existingCommand.version);
|
|
1221
|
-
updateCheckPromise = import('./update-check.ts').then(({ createUpdateChecker }) =>
|
|
1222
|
-
createUpdateChecker(existingCommand.name, currentVersion, existingCommand.updateCheck!, runtime),
|
|
1223
|
-
);
|
|
1224
|
-
}
|
|
1225
|
-
}
|
|
1226
|
-
|
|
1227
|
-
const result = execCommand(resolvedInput, cliOptions, 'hard');
|
|
1228
|
-
|
|
1229
|
-
// Show update notification after command output
|
|
1230
|
-
if (updateCheckPromise) {
|
|
1231
|
-
if (result instanceof Promise) {
|
|
1232
|
-
return result.then(async (r) => {
|
|
1233
|
-
const showUpdateNotification = await updateCheckPromise;
|
|
1234
|
-
showUpdateNotification?.();
|
|
1235
|
-
return r;
|
|
1236
|
-
}) as any;
|
|
1237
|
-
}
|
|
1238
|
-
// For sync results, schedule notification for next tick (non-blocking)
|
|
1239
|
-
updateCheckPromise.then((show) => show?.());
|
|
1240
|
-
}
|
|
1241
|
-
|
|
1242
|
-
return makeThenable(result);
|
|
1243
|
-
};
|
|
1244
|
-
|
|
1245
|
-
const run: AnyPadroneProgram['run'] = (command, args) => {
|
|
1246
|
-
const commandObj = typeof command === 'string' ? findCommandByName(command, existingCommand.commands) : (command as AnyPadroneCommand);
|
|
1247
|
-
if (!commandObj) throw new RoutingError(`Command "${command ?? ''}" not found`);
|
|
1248
|
-
if (!commandObj.action) throw new RoutingError(`Command "${commandObj.path}" has no action`, { command: commandObj.path });
|
|
1249
|
-
|
|
1250
|
-
const state: Record<string, unknown> = {};
|
|
1251
|
-
const executeCtx: PluginExecuteContext = { command: commandObj, args, state };
|
|
1252
|
-
|
|
1253
|
-
const coreExecute = (): PluginExecuteResult => {
|
|
1254
|
-
const result = commandObj.action!(executeCtx.args as any, createActionContext(commandObj));
|
|
1255
|
-
return { result };
|
|
1256
|
-
};
|
|
1257
|
-
|
|
1258
|
-
const commandObjPlugins = collectPlugins(commandObj);
|
|
1259
|
-
const executedOrPromise = runPluginChain('execute', commandObjPlugins, executeCtx, coreExecute);
|
|
1260
|
-
|
|
1261
|
-
const toResult = (e: PluginExecuteResult) => ({
|
|
1262
|
-
command: commandObj as any,
|
|
1263
|
-
args: args as any,
|
|
1264
|
-
result: e.result,
|
|
1265
|
-
});
|
|
1266
|
-
|
|
1267
|
-
if (executedOrPromise instanceof Promise) {
|
|
1268
|
-
return executedOrPromise.then(toResult) as any;
|
|
1269
|
-
}
|
|
1270
|
-
return toResult(executedOrPromise);
|
|
1271
|
-
};
|
|
1272
|
-
|
|
1273
|
-
const tool: AnyPadroneProgram['tool'] = () => {
|
|
1274
|
-
const helpText = generateHelp(existingCommand, undefined, { format: 'text' });
|
|
1275
|
-
|
|
1276
|
-
const description = `Run a command. Pass the full command string including arguments. Use "help <command>" for detailed usage.\n\n${helpText}`;
|
|
1277
|
-
|
|
1278
|
-
return {
|
|
1279
|
-
type: 'function',
|
|
1280
|
-
name: existingCommand.name,
|
|
1281
|
-
strict: true,
|
|
1282
|
-
title: existingCommand.description,
|
|
1283
|
-
description,
|
|
1284
|
-
inputExamples: [{ input: { command: '<command> [positionals...] [arguments...]' } }],
|
|
1285
|
-
inputSchema: {
|
|
1286
|
-
[Symbol.for('vercel.ai.schema') as keyof Schema & symbol]: true,
|
|
1287
|
-
jsonSchema: {
|
|
1288
|
-
type: 'object',
|
|
1289
|
-
properties: { command: { type: 'string' } },
|
|
1290
|
-
additionalProperties: false,
|
|
1291
|
-
},
|
|
1292
|
-
_type: undefined as unknown as { command: string },
|
|
1293
|
-
validate: (value) => {
|
|
1294
|
-
const command = (value as any)?.command;
|
|
1295
|
-
if (typeof command === 'string') return { success: true, value: { command } };
|
|
1296
|
-
return { success: false, error: new Error('Expected an object with command property as string.') };
|
|
1297
|
-
},
|
|
1298
|
-
} satisfies Schema<{ command: string }> as Schema<{ command: string }>,
|
|
1299
|
-
needsApproval: async (input) => {
|
|
1300
|
-
const parsed = await parse(input.command);
|
|
1301
|
-
if (typeof parsed.command.needsApproval === 'function') return parsed.command.needsApproval(parsed.args);
|
|
1302
|
-
return !!parsed.command.needsApproval;
|
|
1303
|
-
},
|
|
1304
|
-
execute: async (input) => {
|
|
1305
|
-
const output: string[] = [];
|
|
1306
|
-
const errors: string[] = [];
|
|
1307
|
-
const result = await evalCommand(input.command, {
|
|
1308
|
-
autoOutput: false,
|
|
1309
|
-
runtime: {
|
|
1310
|
-
output: (...args) => output.push(args.map(String).join(' ')),
|
|
1311
|
-
error: (text) => errors.push(text),
|
|
1312
|
-
interactive: 'unsupported',
|
|
1313
|
-
format: 'text',
|
|
1314
|
-
},
|
|
1315
|
-
});
|
|
1316
|
-
return { result: result.result, logs: output.join('\n'), error: errors.join('\n') };
|
|
1317
|
-
},
|
|
1318
|
-
};
|
|
1319
|
-
};
|
|
1320
|
-
|
|
1321
|
-
const builder = {
|
|
1322
|
-
configure(config) {
|
|
1323
|
-
return createPadroneBuilder({ ...existingCommand, ...config }) as any;
|
|
1324
|
-
},
|
|
1325
|
-
runtime(runtimeConfig) {
|
|
1326
|
-
return createPadroneBuilder({ ...existingCommand, runtime: { ...existingCommand.runtime, ...runtimeConfig } }) as any;
|
|
1327
|
-
},
|
|
1328
|
-
async() {
|
|
1329
|
-
return createPadroneBuilder({ ...existingCommand, isAsync: true }) as any;
|
|
1330
|
-
},
|
|
1331
|
-
arguments(schema, meta) {
|
|
1332
|
-
// If schema is a function, call it with parent's arguments as base
|
|
1333
|
-
const resolvedArgs = typeof schema === 'function' ? schema(existingCommand.argsSchema as any) : schema;
|
|
1334
|
-
const isAsync = existingCommand.isAsync || isAsyncBranded(resolvedArgs) || hasInteractiveConfig(meta);
|
|
1335
|
-
return createPadroneBuilder({ ...existingCommand, argsSchema: resolvedArgs, meta, isAsync }) as any;
|
|
1336
|
-
},
|
|
1337
|
-
configFile(file, schema) {
|
|
1338
|
-
const configFiles = file === undefined ? undefined : Array.isArray(file) ? file : [file];
|
|
1339
|
-
const resolvedConfig = typeof schema === 'function' ? schema(existingCommand.argsSchema) : (schema ?? existingCommand.argsSchema);
|
|
1340
|
-
const isAsync = existingCommand.isAsync || isAsyncBranded(resolvedConfig);
|
|
1341
|
-
return createPadroneBuilder({ ...existingCommand, configFiles, configSchema: resolvedConfig as any, isAsync }) as any;
|
|
1342
|
-
},
|
|
1343
|
-
env(schema) {
|
|
1344
|
-
const resolvedEnv = typeof schema === 'function' ? schema(existingCommand.argsSchema) : schema;
|
|
1345
|
-
const isAsync = existingCommand.isAsync || isAsyncBranded(resolvedEnv);
|
|
1346
|
-
return createPadroneBuilder({ ...existingCommand, envSchema: resolvedEnv as any, isAsync }) as any;
|
|
1347
|
-
},
|
|
1348
|
-
action(handler = noop) {
|
|
1349
|
-
const baseHandler = existingCommand.action ?? noop;
|
|
1350
|
-
return createPadroneBuilder({
|
|
1351
|
-
...existingCommand,
|
|
1352
|
-
action: (args: any, ctx: any) => (handler as any)(args, ctx, baseHandler),
|
|
1353
|
-
}) as any;
|
|
1354
|
-
},
|
|
1355
|
-
wrap(config) {
|
|
1356
|
-
const handler = createWrapHandler(config, existingCommand.argsSchema as any, existingCommand.meta?.positional);
|
|
1357
|
-
return createPadroneBuilder({ ...existingCommand, action: handler }) as any;
|
|
1358
|
-
},
|
|
1359
|
-
command(nameOrNames, builderFn) {
|
|
1360
|
-
// Extract name and aliases from the input
|
|
1361
|
-
const name = Array.isArray(nameOrNames) ? nameOrNames[0] : nameOrNames;
|
|
1362
|
-
const aliases = Array.isArray(nameOrNames) && nameOrNames.length > 1 ? (nameOrNames.slice(1) as string[]) : undefined;
|
|
1363
|
-
|
|
1364
|
-
// Check if a command with this name already exists (override case)
|
|
1365
|
-
const existingSubcommand = existingCommand.commands?.find((c) => c.name === name) as AnyPadroneCommand | undefined;
|
|
1366
|
-
|
|
1367
|
-
const initialCommand: AnyPadroneCommand = existingSubcommand
|
|
1368
|
-
? { ...existingSubcommand, aliases: aliases ?? existingSubcommand.aliases, parent: existingCommand }
|
|
1369
|
-
: ({
|
|
1370
|
-
name,
|
|
1371
|
-
path: existingCommand.path ? `${existingCommand.path} ${name}` : name,
|
|
1372
|
-
aliases,
|
|
1373
|
-
parent: existingCommand,
|
|
1374
|
-
'~types': {} as any,
|
|
1375
|
-
} satisfies PadroneCommand);
|
|
1376
|
-
|
|
1377
|
-
const builder = createPadroneBuilder(initialCommand);
|
|
1378
|
-
|
|
1379
|
-
const commandObj =
|
|
1380
|
-
((builderFn?.(builder as any) as unknown as typeof builder)?.[commandSymbol] as AnyPadroneCommand) ?? initialCommand;
|
|
1381
|
-
|
|
1382
|
-
// Merge subcommands when overriding: existing subcommands that aren't replaced are kept
|
|
1383
|
-
const mergedCommandObj = existingSubcommand ? mergeCommands(existingSubcommand, commandObj) : commandObj;
|
|
1384
|
-
|
|
1385
|
-
// Replace existing command or append new one
|
|
1386
|
-
const commands = existingCommand.commands || [];
|
|
1387
|
-
const existingIndex = commands.findIndex((c) => c.name === name);
|
|
1388
|
-
const updatedCommands =
|
|
1389
|
-
existingIndex >= 0
|
|
1390
|
-
? [...commands.slice(0, existingIndex), mergedCommandObj, ...commands.slice(existingIndex + 1)]
|
|
1391
|
-
: [...commands, mergedCommandObj];
|
|
1392
|
-
|
|
1393
|
-
return createPadroneBuilder({ ...existingCommand, commands: updatedCommands }) as any;
|
|
1394
|
-
},
|
|
1395
|
-
|
|
1396
|
-
mount(nameOrNames, program) {
|
|
1397
|
-
const name = Array.isArray(nameOrNames) ? nameOrNames[0] : nameOrNames;
|
|
1398
|
-
const aliases = Array.isArray(nameOrNames) && nameOrNames.length > 1 ? (nameOrNames.slice(1) as string[]) : undefined;
|
|
1399
|
-
|
|
1400
|
-
// Extract the underlying command from the program
|
|
1401
|
-
const programCommand = (program as any)[commandSymbol] as AnyPadroneCommand | undefined;
|
|
1402
|
-
if (!programCommand) throw new RoutingError('Cannot mount: not a valid Padrone program');
|
|
1403
|
-
|
|
1404
|
-
// Re-path the command tree under the new name
|
|
1405
|
-
const remounted = repathCommandTree(programCommand, name, existingCommand.path || '', existingCommand);
|
|
1406
|
-
remounted.aliases = aliases;
|
|
1407
|
-
|
|
1408
|
-
// Merge with existing command if one with the same name exists
|
|
1409
|
-
const existingSubcommand = existingCommand.commands?.find((c) => c.name === name) as AnyPadroneCommand | undefined;
|
|
1410
|
-
const mergedCommandObj = existingSubcommand ? mergeCommands(existingSubcommand, remounted) : remounted;
|
|
1411
|
-
|
|
1412
|
-
const commands = existingCommand.commands || [];
|
|
1413
|
-
const existingIndex = commands.findIndex((c) => c.name === name);
|
|
1414
|
-
const updatedCommands =
|
|
1415
|
-
existingIndex >= 0
|
|
1416
|
-
? [...commands.slice(0, existingIndex), mergedCommandObj, ...commands.slice(existingIndex + 1)]
|
|
1417
|
-
: [...commands, mergedCommandObj];
|
|
1418
|
-
|
|
1419
|
-
return createPadroneBuilder({ ...existingCommand, commands: updatedCommands }) as any;
|
|
1420
|
-
},
|
|
1421
|
-
|
|
1422
|
-
use(plugin: PadronePlugin) {
|
|
1423
|
-
return createPadroneBuilder({
|
|
1424
|
-
...existingCommand,
|
|
1425
|
-
plugins: [...(existingCommand.plugins ?? []), plugin],
|
|
1426
|
-
}) as any;
|
|
1427
|
-
},
|
|
1428
|
-
|
|
1429
|
-
updateCheck(config = {}) {
|
|
1430
|
-
return createPadroneBuilder({ ...existingCommand, updateCheck: config }) as any;
|
|
1431
|
-
},
|
|
1432
|
-
|
|
1433
|
-
run,
|
|
1434
|
-
find,
|
|
1435
|
-
parse,
|
|
1436
|
-
stringify,
|
|
1437
|
-
eval: evalCommand,
|
|
1438
|
-
cli,
|
|
1439
|
-
tool,
|
|
1440
|
-
|
|
1441
|
-
repl: (replFn = (options?: PadroneReplPreferences) => {
|
|
1442
|
-
return createReplIterator({ existingCommand, evalCommand, replActiveRef }, options);
|
|
1443
|
-
}),
|
|
1444
|
-
|
|
1445
|
-
api() {
|
|
1446
|
-
function buildApi(command: AnyPadroneCommand) {
|
|
1447
|
-
const runCommand = ((args) => run(command, args).result) as PadroneAPI<AnyPadroneCommand>;
|
|
1448
|
-
if (!command.commands) return runCommand;
|
|
1449
|
-
for (const cmd of command.commands) runCommand[cmd.name] = buildApi(cmd);
|
|
1450
|
-
return runCommand;
|
|
1451
|
-
}
|
|
1452
|
-
|
|
1453
|
-
return buildApi(existingCommand);
|
|
1454
|
-
},
|
|
1455
|
-
|
|
1456
|
-
help(command, prefs) {
|
|
1457
|
-
const commandObj = !command
|
|
1458
|
-
? existingCommand
|
|
1459
|
-
: typeof command === 'string'
|
|
1460
|
-
? findCommandByName(command, existingCommand.commands)
|
|
1461
|
-
: (command as AnyPadroneCommand);
|
|
1462
|
-
if (!commandObj) throw new RoutingError(`Command "${command ?? ''}" not found`);
|
|
1463
|
-
const runtime = getCommandRuntime(existingCommand);
|
|
1464
|
-
return generateHelp(existingCommand, commandObj, { ...prefs, format: prefs?.format ?? runtime.format });
|
|
1465
|
-
},
|
|
1466
|
-
|
|
1467
|
-
async completion(shell) {
|
|
1468
|
-
const { generateCompletionOutput } = await import('./completion.ts');
|
|
1469
|
-
return generateCompletionOutput(existingCommand, shell as ShellType | undefined);
|
|
1470
|
-
},
|
|
1471
|
-
|
|
1472
|
-
'~types': {} as any,
|
|
1473
|
-
|
|
1474
|
-
[commandSymbol]: existingCommand,
|
|
1475
|
-
} satisfies AnyPadroneProgram & { [commandSymbol]: AnyPadroneCommand } as any;
|
|
1476
|
-
return builder as TBuilder & { [commandSymbol]: AnyPadroneCommand };
|
|
1477
|
-
}
|