@alcyone-labs/arg-parser 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/LICENSE +21 -0
- package/README.md +584 -0
- package/dist/ArgParser.d.ts +118 -0
- package/dist/ArgParser.d.ts.map +1 -0
- package/dist/FlagManager.d.ts +16 -0
- package/dist/FlagManager.d.ts.map +1 -0
- package/dist/index.cjs +1192 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.min.mjs +819 -0
- package/dist/index.min.mjs.map +1 -0
- package/dist/index.mjs +1192 -0
- package/dist/index.mjs.map +1 -0
- package/dist/types.d.ts +91 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +69 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1192 @@
|
|
|
1
|
+
var __typeError = (msg) => {
|
|
2
|
+
throw TypeError(msg);
|
|
3
|
+
};
|
|
4
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
5
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
6
|
+
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
7
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
8
|
+
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
9
|
+
var __flags, _throwForDuplicateFlags, _appName, _appCommandName, _subCommandName, _parameters, _handler, _throwForDuplicateFlags2, _description, _handleErrors, _parentParser, _lastParseResult, _inheritParentFlags, _subCommands, _flagManager, _ArgParser_instances, _identifyCommandChainAndParsers_fn, _handleGlobalChecks_fn, _validateMandatoryFlags_fn, _applyDefaultValues_fn, _prepareAndExecuteHandler_fn, parseFlags_fn, displayErrorAndExit_fn, _printRecursiveToConsole_fn, _buildRecursiveString_fn, _buildRecursiveJson_fn;
|
|
10
|
+
import chalk from "chalk";
|
|
11
|
+
import { createRegExp, anyOf, oneOrMore, char } from "magic-regexp";
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
const path = {};
|
|
14
|
+
const zodFlagSchema = z.object({
|
|
15
|
+
name: z.string().min(1, "Flag name cannot be empty").describe(
|
|
16
|
+
"The output property name, used as a return key `{name: value}`. Must be unique."
|
|
17
|
+
),
|
|
18
|
+
allowLigature: z.boolean().default(true).describe(
|
|
19
|
+
"Enable both forms of flag input, e.g., `./script.js -f=value` and `-f value`."
|
|
20
|
+
),
|
|
21
|
+
allowMultiple: z.boolean().default(false).describe(
|
|
22
|
+
"Allow passing the same flag multiple times, e.g., `-f val1 -f val2` results in an array."
|
|
23
|
+
),
|
|
24
|
+
description: z.union([z.string(), z.array(z.string())]).describe("Textual description for help messages."),
|
|
25
|
+
options: z.array(z.string().min(1)).min(1, "Flag must have at least one option (e.g., ['-f', '--flag'])").describe("Array of option strings, e.g., ['-f', '--flag']."),
|
|
26
|
+
defaultValue: z.any().optional().describe("Default value if the flag is not provided."),
|
|
27
|
+
type: z.union([
|
|
28
|
+
z.any().refine((val) => val === String, {
|
|
29
|
+
message: "Must be String constructor"
|
|
30
|
+
}),
|
|
31
|
+
z.any().refine((val) => val === Number, {
|
|
32
|
+
message: "Must be Number constructor"
|
|
33
|
+
}),
|
|
34
|
+
z.any().refine((val) => val === Boolean, {
|
|
35
|
+
message: "Must be Boolean constructor"
|
|
36
|
+
}),
|
|
37
|
+
z.any().refine((val) => val === Array, {
|
|
38
|
+
message: "Must be Array constructor"
|
|
39
|
+
}),
|
|
40
|
+
z.any().refine((val) => val === Object, {
|
|
41
|
+
message: "Must be Object constructor"
|
|
42
|
+
}),
|
|
43
|
+
z.function().args(z.string()).returns(z.any()),
|
|
44
|
+
// Custom parser function
|
|
45
|
+
z.string().refine(
|
|
46
|
+
(value) => ["boolean", "string", "number", "array", "object"].includes(
|
|
47
|
+
value.toLowerCase()
|
|
48
|
+
),
|
|
49
|
+
{
|
|
50
|
+
message: "Invalid type string. Must be one of 'boolean', 'string', 'number', 'array', 'object'."
|
|
51
|
+
}
|
|
52
|
+
)
|
|
53
|
+
]).default("string").describe(
|
|
54
|
+
"Expected data type or a custom parser function. Defaults to 'string'."
|
|
55
|
+
),
|
|
56
|
+
mandatory: z.union([z.boolean(), z.function().args(z.any()).returns(z.boolean())]).optional().describe(
|
|
57
|
+
"Makes the flag mandatory, can be a boolean or a function conditional on other args."
|
|
58
|
+
),
|
|
59
|
+
flagOnly: z.boolean().default(false).describe(
|
|
60
|
+
"If true, the flag's presence is noted (true/false), and any subsequent value is not consumed by this flag."
|
|
61
|
+
),
|
|
62
|
+
validate: z.function().args(z.any().optional(), z.any().optional()).returns(
|
|
63
|
+
z.union([
|
|
64
|
+
z.boolean(),
|
|
65
|
+
z.string(),
|
|
66
|
+
z.void(),
|
|
67
|
+
z.promise(z.union([z.boolean(), z.string(), z.void()]))
|
|
68
|
+
])
|
|
69
|
+
).optional().describe(
|
|
70
|
+
"Custom validation function for the flag's value (receives value, parsedArgs)."
|
|
71
|
+
),
|
|
72
|
+
enum: z.array(z.any()).optional().describe("Array of allowed values for the flag.")
|
|
73
|
+
}).passthrough().transform((obj) => {
|
|
74
|
+
const newObj = { ...obj };
|
|
75
|
+
if ("default" in newObj && newObj["default"] !== void 0 && !("defaultValue" in newObj)) {
|
|
76
|
+
newObj["defaultValue"] = newObj["default"];
|
|
77
|
+
}
|
|
78
|
+
if ("required" in newObj && newObj["required"] !== void 0 && !("mandatory" in newObj)) {
|
|
79
|
+
newObj["mandatory"] = newObj["required"];
|
|
80
|
+
}
|
|
81
|
+
return newObj;
|
|
82
|
+
});
|
|
83
|
+
const _FlagManager = class _FlagManager {
|
|
84
|
+
constructor(options = {}, initialFlags = []) {
|
|
85
|
+
__privateAdd(this, __flags, /* @__PURE__ */ new Map());
|
|
86
|
+
__privateAdd(this, _throwForDuplicateFlags);
|
|
87
|
+
__privateSet(this, _throwForDuplicateFlags, options.throwForDuplicateFlags ?? false);
|
|
88
|
+
this.addFlags(initialFlags);
|
|
89
|
+
}
|
|
90
|
+
static _safeFlag(flag) {
|
|
91
|
+
const parsedFromZod = zodFlagSchema.parse(flag);
|
|
92
|
+
let resolvedType;
|
|
93
|
+
const inputTypeFromZod = parsedFromZod["type"];
|
|
94
|
+
if (typeof inputTypeFromZod === "string") {
|
|
95
|
+
switch (inputTypeFromZod.toLowerCase()) {
|
|
96
|
+
case "boolean":
|
|
97
|
+
resolvedType = Boolean;
|
|
98
|
+
break;
|
|
99
|
+
case "string":
|
|
100
|
+
resolvedType = String;
|
|
101
|
+
break;
|
|
102
|
+
case "number":
|
|
103
|
+
resolvedType = Number;
|
|
104
|
+
break;
|
|
105
|
+
case "array":
|
|
106
|
+
resolvedType = Array;
|
|
107
|
+
break;
|
|
108
|
+
case "object":
|
|
109
|
+
resolvedType = Object;
|
|
110
|
+
break;
|
|
111
|
+
default:
|
|
112
|
+
throw new Error(`Invalid type string: ${inputTypeFromZod}`);
|
|
113
|
+
}
|
|
114
|
+
} else {
|
|
115
|
+
resolvedType = inputTypeFromZod;
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
...parsedFromZod,
|
|
119
|
+
options: parsedFromZod["options"],
|
|
120
|
+
type: resolvedType,
|
|
121
|
+
validate: parsedFromZod["validate"],
|
|
122
|
+
enum: parsedFromZod["enum"],
|
|
123
|
+
mandatory: parsedFromZod["mandatory"]
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
addFlag(flag) {
|
|
127
|
+
const safeFlag = _FlagManager._safeFlag(flag);
|
|
128
|
+
if (__privateGet(this, __flags).has(safeFlag["name"])) {
|
|
129
|
+
if (__privateGet(this, _throwForDuplicateFlags)) {
|
|
130
|
+
throw new Error(
|
|
131
|
+
`FlagManager: Flag '${safeFlag["name"]}' already exists.`
|
|
132
|
+
);
|
|
133
|
+
} else {
|
|
134
|
+
console.warn(
|
|
135
|
+
`Warning: FlagManager: Flag '${safeFlag["name"]}' already exists. Duplicate not added.`
|
|
136
|
+
);
|
|
137
|
+
return this;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
__privateGet(this, __flags).set(safeFlag["name"], safeFlag);
|
|
141
|
+
return this;
|
|
142
|
+
}
|
|
143
|
+
_setProcessedFlagForInheritance(processedFlag) {
|
|
144
|
+
if (__privateGet(this, __flags).has(processedFlag["name"])) {
|
|
145
|
+
return this;
|
|
146
|
+
}
|
|
147
|
+
__privateGet(this, __flags).set(processedFlag["name"], processedFlag);
|
|
148
|
+
return this;
|
|
149
|
+
}
|
|
150
|
+
addFlags(flags) {
|
|
151
|
+
for (const flag of flags) {
|
|
152
|
+
this.addFlag(flag);
|
|
153
|
+
}
|
|
154
|
+
return this;
|
|
155
|
+
}
|
|
156
|
+
hasFlag(name) {
|
|
157
|
+
return __privateGet(this, __flags).has(name);
|
|
158
|
+
}
|
|
159
|
+
getFlag(name) {
|
|
160
|
+
return __privateGet(this, __flags).get(name);
|
|
161
|
+
}
|
|
162
|
+
get flags() {
|
|
163
|
+
return Array.from(__privateGet(this, __flags).values());
|
|
164
|
+
}
|
|
165
|
+
get flagNames() {
|
|
166
|
+
return Array.from(__privateGet(this, __flags).values()).map((flag) => flag["name"]);
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
__flags = new WeakMap();
|
|
170
|
+
_throwForDuplicateFlags = new WeakMap();
|
|
171
|
+
let FlagManager = _FlagManager;
|
|
172
|
+
class ArgParserError extends Error {
|
|
173
|
+
constructor(message, cmdChain = []) {
|
|
174
|
+
super(message);
|
|
175
|
+
this.cmdChain = cmdChain;
|
|
176
|
+
this.name = "ArgParserError";
|
|
177
|
+
this.commandChain = cmdChain;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const _ArgParser = class _ArgParser {
|
|
181
|
+
constructor(options = {}, initialFlags) {
|
|
182
|
+
__privateAdd(this, _ArgParser_instances);
|
|
183
|
+
__privateAdd(this, _appName, "Argument Parser");
|
|
184
|
+
__privateAdd(this, _appCommandName);
|
|
185
|
+
__privateAdd(this, _subCommandName, "");
|
|
186
|
+
__privateAdd(this, _parameters, {
|
|
187
|
+
extraNewLine: true,
|
|
188
|
+
wrapAtWidth: 50,
|
|
189
|
+
blankSpaceWidth: 30,
|
|
190
|
+
mandatoryCharacter: "*"
|
|
191
|
+
});
|
|
192
|
+
__privateAdd(this, _handler);
|
|
193
|
+
__privateAdd(this, _throwForDuplicateFlags2, false);
|
|
194
|
+
__privateAdd(this, _description);
|
|
195
|
+
__privateAdd(this, _handleErrors, true);
|
|
196
|
+
__privateAdd(this, _parentParser);
|
|
197
|
+
__privateAdd(this, _lastParseResult, {});
|
|
198
|
+
__privateAdd(this, _inheritParentFlags, false);
|
|
199
|
+
__privateAdd(this, _subCommands, /* @__PURE__ */ new Map());
|
|
200
|
+
__privateAdd(this, _flagManager);
|
|
201
|
+
__privateSet(this, _appName, options.appName || "app");
|
|
202
|
+
if (options.blankSpaceWidth && !isNaN(Number(options.blankSpaceWidth)) && Number(options.blankSpaceWidth) > 20)
|
|
203
|
+
__privateGet(this, _parameters).blankSpaceWidth = Number(options.blankSpaceWidth);
|
|
204
|
+
if (options.wrapAtWidth && !isNaN(Number(options.wrapAtWidth)) && Number(options.wrapAtWidth) > 30)
|
|
205
|
+
__privateGet(this, _parameters).wrapAtWidth = Number(options.wrapAtWidth);
|
|
206
|
+
if (typeof options.extraNewLine === "boolean")
|
|
207
|
+
__privateGet(this, _parameters).extraNewLine = Boolean(options.extraNewLine);
|
|
208
|
+
if (typeof options.mandatoryCharacter === "string")
|
|
209
|
+
__privateGet(this, _parameters).mandatoryCharacter = options.mandatoryCharacter;
|
|
210
|
+
if (typeof options.throwForDuplicateFlags === "boolean")
|
|
211
|
+
__privateSet(this, _throwForDuplicateFlags2, options.throwForDuplicateFlags);
|
|
212
|
+
__privateSet(this, _flagManager, new FlagManager(
|
|
213
|
+
{
|
|
214
|
+
throwForDuplicateFlags: __privateGet(this, _throwForDuplicateFlags2)
|
|
215
|
+
},
|
|
216
|
+
initialFlags || []
|
|
217
|
+
));
|
|
218
|
+
__privateSet(this, _handleErrors, options.handleErrors ?? true);
|
|
219
|
+
__privateSet(this, _inheritParentFlags, options.inheritParentFlags ?? false);
|
|
220
|
+
__privateSet(this, _description, options.description);
|
|
221
|
+
__privateSet(this, _handler, options.handler);
|
|
222
|
+
__privateSet(this, _appCommandName, options.appCommandName);
|
|
223
|
+
const helpFlag = {
|
|
224
|
+
name: "help",
|
|
225
|
+
description: "Display this help message and exits",
|
|
226
|
+
mandatory: false,
|
|
227
|
+
type: Boolean,
|
|
228
|
+
options: ["-h", "--help"],
|
|
229
|
+
defaultValue: void 0,
|
|
230
|
+
allowLigature: false,
|
|
231
|
+
allowMultiple: false,
|
|
232
|
+
flagOnly: true,
|
|
233
|
+
enum: [],
|
|
234
|
+
validate: (_value, _parsedArgs) => true
|
|
235
|
+
// Ensure signature matches Zod schema for .args()
|
|
236
|
+
};
|
|
237
|
+
__privateGet(this, _flagManager).addFlag(helpFlag);
|
|
238
|
+
if (options.subCommands) {
|
|
239
|
+
for (const sub of options.subCommands) {
|
|
240
|
+
this.addSubCommand(sub);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
get flags() {
|
|
245
|
+
return __privateGet(this, _flagManager).flags;
|
|
246
|
+
}
|
|
247
|
+
get flagNames() {
|
|
248
|
+
return __privateGet(this, _flagManager).flagNames;
|
|
249
|
+
}
|
|
250
|
+
_addToOutput(flag, arg, output, _parseOptions) {
|
|
251
|
+
let value = arg;
|
|
252
|
+
if (flag.type === Boolean) {
|
|
253
|
+
if (typeof arg === "boolean") {
|
|
254
|
+
value = arg;
|
|
255
|
+
} else if (typeof arg === "string") {
|
|
256
|
+
value = /(true|yes|1)/i.test(arg);
|
|
257
|
+
} else {
|
|
258
|
+
value = new flag["type"](value);
|
|
259
|
+
}
|
|
260
|
+
} else if (typeof flag["type"] === "function") {
|
|
261
|
+
value = flag["type"](value);
|
|
262
|
+
} else if (typeof flag["type"] === "object") {
|
|
263
|
+
value = new flag["type"](value);
|
|
264
|
+
}
|
|
265
|
+
if (flag["enum"] && flag["enum"].length > 0) {
|
|
266
|
+
const allowedValues = flag["enum"].map((v) => typeof v === "string" ? `'${v}'` : v).join(", ");
|
|
267
|
+
if (!flag["enum"].includes(value)) {
|
|
268
|
+
throw new ArgParserError(
|
|
269
|
+
`Invalid value '${value}' for flag '${chalk.yellow(flag["name"])}'. Allowed values: ${allowedValues}`,
|
|
270
|
+
this.getCommandChain()
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (flag["validate"]) {
|
|
275
|
+
const validationResult = flag["validate"](value, output);
|
|
276
|
+
if (validationResult === false) {
|
|
277
|
+
throw new ArgParserError(
|
|
278
|
+
`Validation failed for flag '${chalk.yellow(flag["name"])}' with value '${value}'`,
|
|
279
|
+
this.getCommandChain()
|
|
280
|
+
);
|
|
281
|
+
} else if (typeof validationResult === "string") {
|
|
282
|
+
throw new ArgParserError(validationResult, this.getCommandChain());
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (flag["allowMultiple"] && !Array.isArray(output[flag["name"]])) {
|
|
286
|
+
output[flag["name"]] = [];
|
|
287
|
+
}
|
|
288
|
+
return flag["allowMultiple"] ? output[flag["name"]].push(value) : output[flag["name"]] = value;
|
|
289
|
+
}
|
|
290
|
+
addFlags(flags) {
|
|
291
|
+
__privateGet(this, _flagManager).addFlags(flags);
|
|
292
|
+
return this;
|
|
293
|
+
}
|
|
294
|
+
addFlag(flag) {
|
|
295
|
+
__privateGet(this, _flagManager).addFlag(flag);
|
|
296
|
+
return this;
|
|
297
|
+
}
|
|
298
|
+
addSubCommand(subCommandConfig) {
|
|
299
|
+
if (__privateGet(this, _subCommands).has(subCommandConfig.name)) {
|
|
300
|
+
throw new Error(`Sub-command '${subCommandConfig.name}' already exists`);
|
|
301
|
+
}
|
|
302
|
+
const subParser = subCommandConfig.parser;
|
|
303
|
+
if (!(subParser instanceof _ArgParser)) {
|
|
304
|
+
throw new Error(
|
|
305
|
+
`Parser for subcommand '${subCommandConfig.name}' is not an instance of ArgParser. Please provide 'new ArgParser(...)' for the 'parser' property of an ISubCommand.`
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
__privateSet(subParser, _parentParser, this);
|
|
309
|
+
__privateSet(subParser, _subCommandName, subCommandConfig.name);
|
|
310
|
+
if (!__privateGet(subParser, _appCommandName) && __privateGet(this, _appCommandName)) {
|
|
311
|
+
__privateSet(subParser, _appCommandName, __privateGet(this, _appCommandName));
|
|
312
|
+
}
|
|
313
|
+
if (__privateGet(subParser, _inheritParentFlags)) {
|
|
314
|
+
const parentFlags = __privateGet(this, _flagManager).flags;
|
|
315
|
+
for (const parentFlag of parentFlags) {
|
|
316
|
+
if (!__privateGet(subParser, _flagManager).hasFlag(parentFlag["name"])) {
|
|
317
|
+
__privateGet(subParser, _flagManager)._setProcessedFlagForInheritance(parentFlag);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
__privateGet(this, _subCommands).set(subCommandConfig.name, subCommandConfig);
|
|
322
|
+
if (subCommandConfig.handler) {
|
|
323
|
+
subParser.setHandler(subCommandConfig.handler);
|
|
324
|
+
}
|
|
325
|
+
return this;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Sets the handler function for this specific parser instance.
|
|
329
|
+
* This handler will be executed if this parser is the final one
|
|
330
|
+
* in the command chain and `executeHandlers` is enabled on the root parser.
|
|
331
|
+
*
|
|
332
|
+
* @param handler - The function to execute.
|
|
333
|
+
* @returns The ArgParser instance for chaining.
|
|
334
|
+
*/
|
|
335
|
+
setHandler(handler) {
|
|
336
|
+
__privateSet(this, _handler, handler);
|
|
337
|
+
return this;
|
|
338
|
+
}
|
|
339
|
+
printAll(filePath) {
|
|
340
|
+
if (filePath) {
|
|
341
|
+
try {
|
|
342
|
+
const dir = path.dirname(filePath);
|
|
343
|
+
if (!path.existsSync(dir)) {
|
|
344
|
+
path.mkdirSync(dir, { recursive: true });
|
|
345
|
+
}
|
|
346
|
+
if (filePath.toLowerCase().endsWith(".json")) {
|
|
347
|
+
const outputObject = __privateMethod(this, _ArgParser_instances, _buildRecursiveJson_fn).call(this, this);
|
|
348
|
+
const jsonString = JSON.stringify(outputObject, null, 2);
|
|
349
|
+
path.writeFileSync(filePath, jsonString);
|
|
350
|
+
console.log(`ArgParser configuration JSON dumped to: ${filePath}`);
|
|
351
|
+
} else {
|
|
352
|
+
const outputString = __privateMethod(this, _ArgParser_instances, _buildRecursiveString_fn).call(this, this, 0);
|
|
353
|
+
const plainText = outputString.replace(
|
|
354
|
+
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
|
|
355
|
+
""
|
|
356
|
+
);
|
|
357
|
+
path.writeFileSync(filePath, plainText);
|
|
358
|
+
console.log(`ArgParser configuration text dumped to: ${filePath}`);
|
|
359
|
+
}
|
|
360
|
+
} catch (error) {
|
|
361
|
+
console.error(
|
|
362
|
+
`Error writing ArgParser configuration to file '${filePath}':`,
|
|
363
|
+
error
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
} else {
|
|
367
|
+
console.log("\n--- ArgParser Configuration Dump ---");
|
|
368
|
+
__privateMethod(this, _ArgParser_instances, _printRecursiveToConsole_fn).call(this, this, 0);
|
|
369
|
+
console.log("--- End Configuration Dump ---\\n");
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
parse(processArgs, options) {
|
|
373
|
+
if (__privateMethod(this, _ArgParser_instances, _handleGlobalChecks_fn).call(this, processArgs, options)) {
|
|
374
|
+
return {};
|
|
375
|
+
}
|
|
376
|
+
try {
|
|
377
|
+
const {
|
|
378
|
+
finalParser: identifiedFinalParser,
|
|
379
|
+
commandChain: identifiedCommandChain,
|
|
380
|
+
parserChain: identifiedParserChain
|
|
381
|
+
} = __privateMethod(this, _ArgParser_instances, _identifyCommandChainAndParsers_fn).call(this, processArgs, this, [], [this]);
|
|
382
|
+
const { finalArgs, handlerToExecute } = this._parseRecursive(
|
|
383
|
+
processArgs,
|
|
384
|
+
this,
|
|
385
|
+
{},
|
|
386
|
+
[],
|
|
387
|
+
options
|
|
388
|
+
);
|
|
389
|
+
if (identifiedCommandChain.length > 0) {
|
|
390
|
+
finalArgs.$commandChain = identifiedCommandChain;
|
|
391
|
+
}
|
|
392
|
+
__privateMethod(this, _ArgParser_instances, _validateMandatoryFlags_fn).call(this, finalArgs, identifiedParserChain, identifiedCommandChain);
|
|
393
|
+
__privateMethod(this, _ArgParser_instances, _applyDefaultValues_fn).call(this, finalArgs, identifiedFinalParser);
|
|
394
|
+
__privateMethod(this, _ArgParser_instances, _prepareAndExecuteHandler_fn).call(this, handlerToExecute, finalArgs, (options == null ? void 0 : options.skipHandlers) ?? false);
|
|
395
|
+
return finalArgs;
|
|
396
|
+
} catch (error) {
|
|
397
|
+
if (error instanceof ArgParserError) {
|
|
398
|
+
if (__privateGet(this, _handleErrors)) {
|
|
399
|
+
__privateMethod(this, _ArgParser_instances, displayErrorAndExit_fn).call(this, error);
|
|
400
|
+
return {};
|
|
401
|
+
} else {
|
|
402
|
+
throw error;
|
|
403
|
+
}
|
|
404
|
+
} else {
|
|
405
|
+
throw error;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Recursive helper for parsing arguments and handling sub-commands.
|
|
411
|
+
* This method assumes the global help check has already been performed in `parse`.
|
|
412
|
+
*/
|
|
413
|
+
_parseRecursive(argsToParse, currentParser, accumulatedParentArgs, commandChainSoFar, options) {
|
|
414
|
+
var _a, _b;
|
|
415
|
+
let subCommandIndex = -1;
|
|
416
|
+
let subCommandName = null;
|
|
417
|
+
for (let i = 0; i < argsToParse.length; i++) {
|
|
418
|
+
const potentialSubCommand = argsToParse[i];
|
|
419
|
+
if (__privateGet(currentParser, _subCommands).has(potentialSubCommand)) {
|
|
420
|
+
subCommandIndex = i;
|
|
421
|
+
subCommandName = potentialSubCommand;
|
|
422
|
+
break;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
const argsForCurrentLevel = subCommandIndex === -1 ? argsToParse : argsToParse.slice(0, subCommandIndex);
|
|
426
|
+
const { parsedArgs: currentLevelArgs, firstUnconsumedIndex } = __privateMethod(_a = currentParser, _ArgParser_instances, parseFlags_fn).call(_a, argsForCurrentLevel, options);
|
|
427
|
+
__privateMethod(_b = currentParser, _ArgParser_instances, _applyDefaultValues_fn).call(_b, currentLevelArgs, currentParser);
|
|
428
|
+
const combinedArgsFromThisAndParents = {
|
|
429
|
+
...accumulatedParentArgs,
|
|
430
|
+
...currentLevelArgs
|
|
431
|
+
};
|
|
432
|
+
if (subCommandIndex === -1 || subCommandName === null) {
|
|
433
|
+
if (firstUnconsumedIndex < argsForCurrentLevel.length) {
|
|
434
|
+
const unknownCommand = argsForCurrentLevel[firstUnconsumedIndex];
|
|
435
|
+
throw new ArgParserError(
|
|
436
|
+
`Unknown command: '${chalk.yellow(unknownCommand)}'`,
|
|
437
|
+
commandChainSoFar
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
const finalParseResultArgs = { ...combinedArgsFromThisAndParents };
|
|
441
|
+
if (commandChainSoFar.length > 0) {
|
|
442
|
+
finalParseResultArgs["$commandChain"] = commandChainSoFar;
|
|
443
|
+
}
|
|
444
|
+
let handlerToExecute = void 0;
|
|
445
|
+
if (__privateGet(currentParser, _handler)) {
|
|
446
|
+
handlerToExecute = {
|
|
447
|
+
handler: __privateGet(currentParser, _handler),
|
|
448
|
+
context: {
|
|
449
|
+
args: currentLevelArgs,
|
|
450
|
+
parentArgs: accumulatedParentArgs,
|
|
451
|
+
commandChain: commandChainSoFar,
|
|
452
|
+
parser: currentParser
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
return { finalArgs: finalParseResultArgs, handlerToExecute };
|
|
457
|
+
}
|
|
458
|
+
if (firstUnconsumedIndex < argsForCurrentLevel.length) {
|
|
459
|
+
const unknownCommand = argsForCurrentLevel[firstUnconsumedIndex];
|
|
460
|
+
throw new ArgParserError(
|
|
461
|
+
`Unknown command: '${chalk.yellow(unknownCommand)}'`,
|
|
462
|
+
commandChainSoFar
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
const subCommandConfig = __privateGet(currentParser, _subCommands).get(subCommandName);
|
|
466
|
+
if (!subCommandConfig || !(subCommandConfig.parser instanceof _ArgParser)) {
|
|
467
|
+
throw new ArgParserError(
|
|
468
|
+
`Internal error: Subcommand '${subCommandName}' is misconfigured or its parser is not a valid ArgParser instance.`,
|
|
469
|
+
commandChainSoFar
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
const nextParser = subCommandConfig.parser;
|
|
473
|
+
const nextArgs = argsToParse.slice(subCommandIndex + 1);
|
|
474
|
+
const nextCommandChain = [...commandChainSoFar, subCommandName];
|
|
475
|
+
const combinedArgsForNextLevel = {
|
|
476
|
+
...accumulatedParentArgs,
|
|
477
|
+
...currentLevelArgs
|
|
478
|
+
};
|
|
479
|
+
return this._parseRecursive(
|
|
480
|
+
nextArgs,
|
|
481
|
+
nextParser,
|
|
482
|
+
combinedArgsForNextLevel,
|
|
483
|
+
nextCommandChain,
|
|
484
|
+
options
|
|
485
|
+
);
|
|
486
|
+
}
|
|
487
|
+
helpText() {
|
|
488
|
+
const cyan = chalk.cyan;
|
|
489
|
+
const green = chalk.green;
|
|
490
|
+
const white = chalk.white;
|
|
491
|
+
const red = chalk.red;
|
|
492
|
+
const dim = chalk.dim;
|
|
493
|
+
let rootAppName = __privateGet(this, _appName);
|
|
494
|
+
let current = this;
|
|
495
|
+
while (__privateGet(current, _parentParser)) {
|
|
496
|
+
current = __privateGet(current, _parentParser);
|
|
497
|
+
}
|
|
498
|
+
if (current) {
|
|
499
|
+
rootAppName = __privateGet(current, _appName);
|
|
500
|
+
}
|
|
501
|
+
const helpTitle = __privateGet(this, _subCommandName) ? `${rootAppName} ${__privateGet(this, _subCommandName)}` : rootAppName;
|
|
502
|
+
let help = `${cyan(`${helpTitle} Help`)} (${__privateGet(this, _parameters).mandatoryCharacter} = Mandatory fields):
|
|
503
|
+
|
|
504
|
+
`;
|
|
505
|
+
if (__privateGet(this, _description)) {
|
|
506
|
+
help += `${white(__privateGet(this, _description))}
|
|
507
|
+
|
|
508
|
+
`;
|
|
509
|
+
}
|
|
510
|
+
const indent = (level = 1) => " ".repeat(level);
|
|
511
|
+
if (__privateGet(this, _subCommands).size > 0) {
|
|
512
|
+
help += `${cyan("Available sub-commands:")}
|
|
513
|
+
`;
|
|
514
|
+
help += Array.from(__privateGet(this, _subCommands).entries()).sort(([nameA], [nameB]) => nameA.localeCompare(nameB)).map(([name, subCommandConfig]) => {
|
|
515
|
+
const actualSubParserInstance = subCommandConfig.parser;
|
|
516
|
+
if (!(actualSubParserInstance instanceof _ArgParser)) {
|
|
517
|
+
return `${indent()}${green(name.padEnd(20))} [Error: Subcommand '${name}' has an invalid parser configuration]`;
|
|
518
|
+
}
|
|
519
|
+
let subHelp = `${indent()}${green(name.padEnd(20))} ${white(__privateGet(actualSubParserInstance, _description) || "")}`;
|
|
520
|
+
const flagsFromSubManager = actualSubParserInstance && __privateGet(actualSubParserInstance, _flagManager) ? __privateGet(actualSubParserInstance, _flagManager).flags : void 0;
|
|
521
|
+
const subFlags = (flagsFromSubManager || []).filter(
|
|
522
|
+
(f) => f["name"] !== "help"
|
|
523
|
+
);
|
|
524
|
+
if (subFlags.length > 0) {
|
|
525
|
+
subHelp += `
|
|
526
|
+
${indent(2)}${dim("Flags:")}`;
|
|
527
|
+
subFlags.sort(
|
|
528
|
+
(a, b) => a["name"].localeCompare(b["name"])
|
|
529
|
+
).forEach((f) => {
|
|
530
|
+
const flagOptions = f["options"].map((opt) => green(opt)).join(", ");
|
|
531
|
+
const flagDesc = Array.isArray(f["description"]) ? f["description"][0] : f["description"];
|
|
532
|
+
subHelp += `
|
|
533
|
+
${indent(3)}${flagOptions} - ${dim(flagDesc)}`;
|
|
534
|
+
});
|
|
535
|
+
} else {
|
|
536
|
+
subHelp += `
|
|
537
|
+
${indent(2)}${dim("Flags:")} none`;
|
|
538
|
+
}
|
|
539
|
+
const subSubCommandNames = Array.from(
|
|
540
|
+
__privateGet(actualSubParserInstance, _subCommands).keys()
|
|
541
|
+
);
|
|
542
|
+
if (subSubCommandNames.length > 0) {
|
|
543
|
+
subHelp += `
|
|
544
|
+
${indent(2)}${dim("Sub-commands:")} ${subSubCommandNames.join(", ")}`;
|
|
545
|
+
} else {
|
|
546
|
+
subHelp += `
|
|
547
|
+
${indent(2)}${dim("Sub-commands:")} none`;
|
|
548
|
+
}
|
|
549
|
+
return subHelp;
|
|
550
|
+
}).join("\n\n");
|
|
551
|
+
help += "\n";
|
|
552
|
+
}
|
|
553
|
+
help += `
|
|
554
|
+
${cyan("Flags:")}
|
|
555
|
+
`;
|
|
556
|
+
const localFlags = __privateGet(this, _flagManager).flags;
|
|
557
|
+
if (localFlags.length > 0) {
|
|
558
|
+
help += localFlags.sort((flagA, flagB) => flagA["name"].localeCompare(flagB["name"])).map((flag) => {
|
|
559
|
+
const optionsText = flag["options"].toSorted((a, b) => a.length - b.length).map((opt) => green(opt)).join(", ");
|
|
560
|
+
const isMandatory = typeof flag.mandatory === "function" ? "dynamic" : flag.mandatory;
|
|
561
|
+
const mandatoryIndicator = isMandatory === true ? ` ${red(__privateGet(this, _parameters).mandatoryCharacter)}` : isMandatory === "dynamic" ? ` ${dim("(conditionally mandatory)")}` : "";
|
|
562
|
+
const descriptionLines = Array.isArray(flag["description"]) ? flag["description"] : [flag["description"]];
|
|
563
|
+
const metaLines = [];
|
|
564
|
+
let typeName = "unknown";
|
|
565
|
+
if (typeof flag["type"] === "function") {
|
|
566
|
+
typeName = flag["type"].name || "custom function";
|
|
567
|
+
if (typeName === "Boolean") typeName = "boolean";
|
|
568
|
+
if (typeName === "String") typeName = "string";
|
|
569
|
+
if (typeName === "Number") typeName = "number";
|
|
570
|
+
if (typeName === "Array") typeName = "array";
|
|
571
|
+
if (typeName === "Object") typeName = "object";
|
|
572
|
+
} else if (typeof flag["type"] === "string") {
|
|
573
|
+
typeName = flag["type"];
|
|
574
|
+
}
|
|
575
|
+
metaLines.push(`Type: ${typeName}`);
|
|
576
|
+
if (flag["flagOnly"]) {
|
|
577
|
+
metaLines.push("Flag only (no value expected)");
|
|
578
|
+
}
|
|
579
|
+
if (flag["defaultValue"] !== void 0 && flag["defaultValue"] !== null) {
|
|
580
|
+
metaLines.push(`Default: ${JSON.stringify(flag["defaultValue"])}`);
|
|
581
|
+
}
|
|
582
|
+
if (flag["enum"] && flag["enum"].length > 0) {
|
|
583
|
+
metaLines.push(
|
|
584
|
+
`Allowed values: ${flag["enum"].map((v) => `'${v}'`).join(", ")}`
|
|
585
|
+
);
|
|
586
|
+
}
|
|
587
|
+
const maxOptionLength = Math.max(
|
|
588
|
+
...localFlags.map(
|
|
589
|
+
(f) => f["options"].join(", ").length
|
|
590
|
+
),
|
|
591
|
+
0
|
|
592
|
+
);
|
|
593
|
+
const formattedOptions = optionsText.padEnd(maxOptionLength + 5) + mandatoryIndicator;
|
|
594
|
+
return `
|
|
595
|
+
${indent()}${formattedOptions}
|
|
596
|
+
${indent(2)}${white(descriptionLines[0])}
|
|
597
|
+
${metaLines.map((line) => `${indent(3)}${dim(line)}`).join("\n")}
|
|
598
|
+
${descriptionLines.slice(1).map((line) => `
|
|
599
|
+
${indent(2)}${white(line)}`).join("")}
|
|
600
|
+
`.trim();
|
|
601
|
+
}).join("\n\n");
|
|
602
|
+
} else {
|
|
603
|
+
help += `${indent()}${dim("none")}`;
|
|
604
|
+
}
|
|
605
|
+
return help;
|
|
606
|
+
}
|
|
607
|
+
getSubCommand(name) {
|
|
608
|
+
return __privateGet(this, _subCommands).get(name);
|
|
609
|
+
}
|
|
610
|
+
hasFlag(name) {
|
|
611
|
+
return __privateGet(this, _flagManager).hasFlag(name);
|
|
612
|
+
}
|
|
613
|
+
getCommandChain() {
|
|
614
|
+
const chain = [];
|
|
615
|
+
let currentParser = this;
|
|
616
|
+
while (currentParser && __privateGet(currentParser, _parentParser)) {
|
|
617
|
+
chain.unshift(__privateGet(currentParser, _subCommandName));
|
|
618
|
+
currentParser = __privateGet(currentParser, _parentParser);
|
|
619
|
+
}
|
|
620
|
+
return chain;
|
|
621
|
+
}
|
|
622
|
+
getLastParseResult() {
|
|
623
|
+
return __privateGet(this, _lastParseResult);
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
_appName = new WeakMap();
|
|
627
|
+
_appCommandName = new WeakMap();
|
|
628
|
+
_subCommandName = new WeakMap();
|
|
629
|
+
_parameters = new WeakMap();
|
|
630
|
+
_handler = new WeakMap();
|
|
631
|
+
_throwForDuplicateFlags2 = new WeakMap();
|
|
632
|
+
_description = new WeakMap();
|
|
633
|
+
_handleErrors = new WeakMap();
|
|
634
|
+
_parentParser = new WeakMap();
|
|
635
|
+
_lastParseResult = new WeakMap();
|
|
636
|
+
_inheritParentFlags = new WeakMap();
|
|
637
|
+
_subCommands = new WeakMap();
|
|
638
|
+
_flagManager = new WeakMap();
|
|
639
|
+
_ArgParser_instances = new WeakSet();
|
|
640
|
+
_identifyCommandChainAndParsers_fn = function(argsToParse, currentParser, commandChainSoFar, parserChainSoFar) {
|
|
641
|
+
let subCommandIndex = -1;
|
|
642
|
+
let subCommandName = null;
|
|
643
|
+
for (let i = 0; i < argsToParse.length; i++) {
|
|
644
|
+
const potentialSubCommand = argsToParse[i];
|
|
645
|
+
if (__privateGet(currentParser, _subCommands).has(potentialSubCommand)) {
|
|
646
|
+
subCommandIndex = i;
|
|
647
|
+
subCommandName = potentialSubCommand;
|
|
648
|
+
break;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
if (subCommandIndex === -1 || subCommandName === null) {
|
|
652
|
+
return {
|
|
653
|
+
finalParser: currentParser,
|
|
654
|
+
commandChain: commandChainSoFar,
|
|
655
|
+
parserChain: parserChainSoFar,
|
|
656
|
+
remainingArgs: argsToParse
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
const subCommandConfig = __privateGet(currentParser, _subCommands).get(subCommandName);
|
|
660
|
+
if (!subCommandConfig || !(subCommandConfig.parser instanceof _ArgParser)) {
|
|
661
|
+
throw new Error(
|
|
662
|
+
`Internal error: Subcommand '${subCommandName}' configuration is invalid or parser is missing.`
|
|
663
|
+
);
|
|
664
|
+
}
|
|
665
|
+
const nextParser = subCommandConfig.parser;
|
|
666
|
+
const nextArgs = argsToParse.slice(subCommandIndex + 1);
|
|
667
|
+
const nextCommandChain = [...commandChainSoFar, subCommandName];
|
|
668
|
+
const nextParserChain = [...parserChainSoFar, nextParser];
|
|
669
|
+
return __privateMethod(this, _ArgParser_instances, _identifyCommandChainAndParsers_fn).call(this, nextArgs, nextParser, nextCommandChain, nextParserChain);
|
|
670
|
+
};
|
|
671
|
+
_handleGlobalChecks_fn = function(processArgs, options) {
|
|
672
|
+
var _a, _b, _c, _d;
|
|
673
|
+
if (processArgs.length === 0 && !__privateGet(this, _parentParser) && !__privateGet(this, _handler)) {
|
|
674
|
+
console.log(this.helpText());
|
|
675
|
+
if (typeof process === "object" && typeof process.exit === "function") {
|
|
676
|
+
process.exit(0);
|
|
677
|
+
}
|
|
678
|
+
return true;
|
|
679
|
+
}
|
|
680
|
+
if (processArgs.includes("--LIB-debug-print")) {
|
|
681
|
+
this.printAll("ArgParser.full.json");
|
|
682
|
+
if (typeof process === "object" && typeof process.exit === "function") {
|
|
683
|
+
process.exit(0);
|
|
684
|
+
}
|
|
685
|
+
return true;
|
|
686
|
+
}
|
|
687
|
+
const { finalParser: identifiedFinalParser } = __privateMethod(this, _ArgParser_instances, _identifyCommandChainAndParsers_fn).call(this, processArgs, this, [], [this]);
|
|
688
|
+
if (processArgs.includes("--LIB-debug")) {
|
|
689
|
+
console.log(
|
|
690
|
+
chalk.yellow.bold("\n--- ArgParser --LIB-debug Runtime Context ---")
|
|
691
|
+
);
|
|
692
|
+
const {
|
|
693
|
+
commandChain: identifiedCommandChain,
|
|
694
|
+
parserChain: _identifiedParserChain
|
|
695
|
+
} = __privateMethod(this, _ArgParser_instances, _identifyCommandChainAndParsers_fn).call(this, processArgs, this, [], [this]);
|
|
696
|
+
console.log(
|
|
697
|
+
`Identified Command Chain: ${chalk.cyan(identifiedCommandChain.join(" -> ") || "(root)")}`
|
|
698
|
+
);
|
|
699
|
+
console.log(
|
|
700
|
+
`Identified Final Parser: ${chalk.cyan(__privateGet(identifiedFinalParser, _subCommandName) || __privateGet(identifiedFinalParser, _appName))}`
|
|
701
|
+
);
|
|
702
|
+
let currentParser = this;
|
|
703
|
+
let remainingArgs = [...processArgs];
|
|
704
|
+
let accumulatedArgs = {};
|
|
705
|
+
const parsingSteps = [];
|
|
706
|
+
const rootSubCommandIndex = remainingArgs.findIndex(
|
|
707
|
+
(arg) => __privateGet(currentParser, _subCommands).has(arg)
|
|
708
|
+
);
|
|
709
|
+
const rootArgsSlice = rootSubCommandIndex === -1 ? remainingArgs : remainingArgs.slice(0, rootSubCommandIndex);
|
|
710
|
+
parsingSteps.push({ level: "(root)", argsSlice: rootArgsSlice });
|
|
711
|
+
try {
|
|
712
|
+
const { parsedArgs: rootParsedArgs } = __privateMethod(_a = currentParser, _ArgParser_instances, parseFlags_fn).call(_a, rootArgsSlice, { skipHelpHandling: true });
|
|
713
|
+
parsingSteps[0].parsed = rootParsedArgs;
|
|
714
|
+
accumulatedArgs = { ...accumulatedArgs, ...rootParsedArgs };
|
|
715
|
+
} catch (e) {
|
|
716
|
+
parsingSteps[0].error = e.message;
|
|
717
|
+
}
|
|
718
|
+
remainingArgs = rootSubCommandIndex === -1 ? [] : remainingArgs.slice(rootSubCommandIndex);
|
|
719
|
+
for (let i = 0; i < identifiedCommandChain.length; i++) {
|
|
720
|
+
const subCommandName = identifiedCommandChain[i];
|
|
721
|
+
if (!__privateGet(currentParser, _subCommands).has(subCommandName)) {
|
|
722
|
+
parsingSteps.push({
|
|
723
|
+
level: `Error`,
|
|
724
|
+
argsSlice: [],
|
|
725
|
+
error: `Could not find sub-command parser for '${subCommandName}'`
|
|
726
|
+
});
|
|
727
|
+
break;
|
|
728
|
+
}
|
|
729
|
+
currentParser = (_b = __privateGet(currentParser, _subCommands).get(subCommandName)) == null ? void 0 : _b.parser;
|
|
730
|
+
remainingArgs = remainingArgs.slice(1);
|
|
731
|
+
const nextSubCommandIndex = remainingArgs.findIndex(
|
|
732
|
+
(arg) => __privateGet(currentParser, _subCommands).has(arg)
|
|
733
|
+
);
|
|
734
|
+
const currentLevelArgsSlice = nextSubCommandIndex === -1 ? remainingArgs : remainingArgs.slice(0, nextSubCommandIndex);
|
|
735
|
+
const stepInfo = {
|
|
736
|
+
level: subCommandName,
|
|
737
|
+
argsSlice: currentLevelArgsSlice
|
|
738
|
+
};
|
|
739
|
+
parsingSteps.push(stepInfo);
|
|
740
|
+
try {
|
|
741
|
+
const { parsedArgs: currentLevelParsedArgs } = __privateMethod(_c = currentParser, _ArgParser_instances, parseFlags_fn).call(_c, currentLevelArgsSlice, {
|
|
742
|
+
skipHelpHandling: true
|
|
743
|
+
});
|
|
744
|
+
stepInfo.parsed = currentLevelParsedArgs;
|
|
745
|
+
accumulatedArgs = { ...accumulatedArgs, ...currentLevelParsedArgs };
|
|
746
|
+
} catch (e) {
|
|
747
|
+
stepInfo.error = e.message;
|
|
748
|
+
}
|
|
749
|
+
remainingArgs = nextSubCommandIndex === -1 ? [] : remainingArgs.slice(nextSubCommandIndex);
|
|
750
|
+
}
|
|
751
|
+
console.log(chalk.yellow("\nParsing Simulation Steps:"));
|
|
752
|
+
parsingSteps.forEach((step) => {
|
|
753
|
+
console.log(` Level: ${chalk.cyan(step.level)}`);
|
|
754
|
+
console.log(
|
|
755
|
+
` Args Slice Considered: ${JSON.stringify(step.argsSlice)}`
|
|
756
|
+
);
|
|
757
|
+
if (step.parsed) {
|
|
758
|
+
console.log(
|
|
759
|
+
` Parsed Args at this Level: ${JSON.stringify(step.parsed)}`
|
|
760
|
+
);
|
|
761
|
+
}
|
|
762
|
+
if (step.error) {
|
|
763
|
+
console.log(
|
|
764
|
+
` ${chalk.red("Error during parse simulation:")} ${step.error}`
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
});
|
|
768
|
+
console.log(
|
|
769
|
+
chalk.yellow(
|
|
770
|
+
"\nFinal Accumulated Args State (before final validation):"
|
|
771
|
+
)
|
|
772
|
+
);
|
|
773
|
+
console.log(JSON.stringify(accumulatedArgs, null, 2));
|
|
774
|
+
console.log(chalk.yellow("\nArguments Remaining After Simulation:"));
|
|
775
|
+
console.log(JSON.stringify(remainingArgs, null, 2));
|
|
776
|
+
console.log(
|
|
777
|
+
chalk.yellow.bold(
|
|
778
|
+
"\n--- ArgParser Static Configuration (Final Parser) ---"
|
|
779
|
+
)
|
|
780
|
+
);
|
|
781
|
+
identifiedFinalParser.printAll();
|
|
782
|
+
console.log(chalk.yellow.bold("--- End ArgParser --LIB-debug ---"));
|
|
783
|
+
if (typeof process === "object" && typeof process.exit === "function") {
|
|
784
|
+
process.exit(0);
|
|
785
|
+
}
|
|
786
|
+
return true;
|
|
787
|
+
}
|
|
788
|
+
let parserNameForLog = "undefined_parser";
|
|
789
|
+
if (identifiedFinalParser instanceof _ArgParser) {
|
|
790
|
+
parserNameForLog = identifiedFinalParser["#subCommandName"] || identifiedFinalParser["#appName"];
|
|
791
|
+
} else if (identifiedFinalParser) {
|
|
792
|
+
parserNameForLog = identifiedFinalParser.name || identifiedFinalParser.appName || "unknown_type";
|
|
793
|
+
}
|
|
794
|
+
if (!(identifiedFinalParser instanceof _ArgParser)) {
|
|
795
|
+
console.error(
|
|
796
|
+
`[ArgParser #_handleGlobalChecks Critical Error] identifiedFinalParser is not an instance of ArgParser. Cannot process help. Name: ${parserNameForLog}, Constructor: ${identifiedFinalParser ? (_d = identifiedFinalParser.constructor) == null ? void 0 : _d.name : "undefined"}`
|
|
797
|
+
);
|
|
798
|
+
return false;
|
|
799
|
+
}
|
|
800
|
+
const helpFlagDefinition = __privateGet(identifiedFinalParser, _flagManager).getFlag("help");
|
|
801
|
+
if (helpFlagDefinition && !(options == null ? void 0 : options.skipHelpHandling)) {
|
|
802
|
+
const helpOptions = helpFlagDefinition["options"];
|
|
803
|
+
const helpRequested = processArgs.some(
|
|
804
|
+
(arg) => helpOptions.includes(arg)
|
|
805
|
+
);
|
|
806
|
+
if (helpRequested) {
|
|
807
|
+
console.log(identifiedFinalParser.helpText());
|
|
808
|
+
if (typeof process === "object" && typeof process.exit === "function") {
|
|
809
|
+
process.exit(0);
|
|
810
|
+
}
|
|
811
|
+
return true;
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
return false;
|
|
815
|
+
};
|
|
816
|
+
_validateMandatoryFlags_fn = function(finalArgs, parserChain, commandChain) {
|
|
817
|
+
const finalMandatoryFlagsMissing = [];
|
|
818
|
+
const checkedFlagNames = /* @__PURE__ */ new Set();
|
|
819
|
+
for (const parser of parserChain) {
|
|
820
|
+
const currentCommandChain = parser.getCommandChain();
|
|
821
|
+
for (const flag of __privateGet(parser, _flagManager).flags) {
|
|
822
|
+
if (flag["name"] === "help" || checkedFlagNames.has(flag["name"]))
|
|
823
|
+
continue;
|
|
824
|
+
const isMandatory = typeof flag["mandatory"] === "function" ? flag["mandatory"](finalArgs) : flag["mandatory"];
|
|
825
|
+
if (!isMandatory) continue;
|
|
826
|
+
const value = finalArgs[flag["name"]];
|
|
827
|
+
let currentFlagIsMissing = false;
|
|
828
|
+
if (flag["allowMultiple"]) {
|
|
829
|
+
if (value === void 0 || Array.isArray(value) && value.length === 0) {
|
|
830
|
+
currentFlagIsMissing = true;
|
|
831
|
+
}
|
|
832
|
+
} else {
|
|
833
|
+
if (value === void 0) {
|
|
834
|
+
currentFlagIsMissing = true;
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
if (currentFlagIsMissing) {
|
|
838
|
+
if (!checkedFlagNames.has(flag["name"])) {
|
|
839
|
+
finalMandatoryFlagsMissing.push({
|
|
840
|
+
name: flag["name"],
|
|
841
|
+
parserName: __privateGet(parser, _subCommandName) || __privateGet(parser, _appName),
|
|
842
|
+
commandChain: currentCommandChain
|
|
843
|
+
});
|
|
844
|
+
checkedFlagNames.add(flag["name"]);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
if (finalMandatoryFlagsMissing.length > 0) {
|
|
850
|
+
throw new ArgParserError(
|
|
851
|
+
`Missing mandatory flags: ${finalMandatoryFlagsMissing.map((flag) => chalk.yellow(flag["name"])).join(", ")}`,
|
|
852
|
+
commandChain
|
|
853
|
+
);
|
|
854
|
+
}
|
|
855
|
+
};
|
|
856
|
+
_applyDefaultValues_fn = function(finalArgs, finalParser) {
|
|
857
|
+
for (const flag of __privateGet(finalParser, _flagManager).flags) {
|
|
858
|
+
const flagName = flag["name"];
|
|
859
|
+
if (finalArgs[flagName] === void 0 && flag["defaultValue"] !== void 0) {
|
|
860
|
+
if (flag["allowMultiple"]) {
|
|
861
|
+
finalArgs[flagName] = Array.isArray(flag["defaultValue"]) ? flag["defaultValue"] : [flag["defaultValue"]];
|
|
862
|
+
} else {
|
|
863
|
+
finalArgs[flagName] = flag["defaultValue"];
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
};
|
|
868
|
+
_prepareAndExecuteHandler_fn = function(handlerToExecute, finalArgs, skipHandlers) {
|
|
869
|
+
if (skipHandlers || !handlerToExecute) {
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
const finalParserWhoseHandlerWillRun = handlerToExecute.context.parser;
|
|
873
|
+
const finalParserFlags = __privateGet(finalParserWhoseHandlerWillRun, _flagManager).flags;
|
|
874
|
+
const handlerArgs = handlerToExecute.context.args;
|
|
875
|
+
for (const flag of finalParserFlags) {
|
|
876
|
+
const flagName = flag["name"];
|
|
877
|
+
if (finalArgs.hasOwnProperty(flagName)) {
|
|
878
|
+
handlerArgs[flagName] = finalArgs[flagName];
|
|
879
|
+
} else if (flag["allowMultiple"] && !handlerArgs.hasOwnProperty(flagName)) {
|
|
880
|
+
handlerArgs[flagName] = [];
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
handlerToExecute.context.args = handlerArgs;
|
|
884
|
+
handlerToExecute.handler(handlerToExecute.context);
|
|
885
|
+
};
|
|
886
|
+
parseFlags_fn = function(args, options) {
|
|
887
|
+
var _a, _b;
|
|
888
|
+
const flags = __privateGet(this, _flagManager).flags;
|
|
889
|
+
const output = Object.fromEntries(
|
|
890
|
+
flags.map((flag) => [
|
|
891
|
+
flag["name"],
|
|
892
|
+
flag["allowMultiple"] ? [] : void 0
|
|
893
|
+
])
|
|
894
|
+
);
|
|
895
|
+
let consumedIndices = /* @__PURE__ */ new Set();
|
|
896
|
+
for (const flagToCheck of flags) {
|
|
897
|
+
if (flagToCheck["allowLigature"] && !flagToCheck["flagOnly"]) {
|
|
898
|
+
const regex = createRegExp(
|
|
899
|
+
anyOf(
|
|
900
|
+
...flagToCheck["options"].map((option) => `${option}=`)
|
|
901
|
+
),
|
|
902
|
+
oneOrMore(char).groupedAs("arg")
|
|
903
|
+
);
|
|
904
|
+
for (let i = 0; i < args.length; i++) {
|
|
905
|
+
if (consumedIndices.has(i)) continue;
|
|
906
|
+
const itemToCheck = args[i];
|
|
907
|
+
const matches = regex.exec(`${itemToCheck}`);
|
|
908
|
+
if ((_a = matches == null ? void 0 : matches.groups) == null ? void 0 : _a["arg"]) {
|
|
909
|
+
this._addToOutput(
|
|
910
|
+
flagToCheck,
|
|
911
|
+
(_b = matches == null ? void 0 : matches.groups) == null ? void 0 : _b["arg"],
|
|
912
|
+
output,
|
|
913
|
+
options
|
|
914
|
+
);
|
|
915
|
+
consumedIndices.add(i);
|
|
916
|
+
if (!flagToCheck["allowMultiple"]) break;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
for (const flagToCheck of flags) {
|
|
922
|
+
for (let index = 0; index < args.length; index++) {
|
|
923
|
+
if (consumedIndices.has(index)) continue;
|
|
924
|
+
const value = args[index];
|
|
925
|
+
const nextIndex = index + 1;
|
|
926
|
+
const nextValueExists = nextIndex < args.length;
|
|
927
|
+
const nextValue = nextValueExists ? args[nextIndex] : void 0;
|
|
928
|
+
const nextValueIsFlag = typeof nextValue === "string" && nextValue.startsWith("-");
|
|
929
|
+
if (flagToCheck["options"].includes(value)) {
|
|
930
|
+
consumedIndices.add(index);
|
|
931
|
+
if (flagToCheck["flagOnly"]) {
|
|
932
|
+
this._addToOutput(flagToCheck, true, output, options);
|
|
933
|
+
} else if (nextValueExists && !nextValueIsFlag) {
|
|
934
|
+
this._addToOutput(flagToCheck, nextValue, output, options);
|
|
935
|
+
consumedIndices.add(nextIndex);
|
|
936
|
+
} else if (flagToCheck["type"] === Boolean) {
|
|
937
|
+
this._addToOutput(flagToCheck, true, output, options);
|
|
938
|
+
}
|
|
939
|
+
if (!flagToCheck["allowMultiple"]) break;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
let firstUnconsumedIndex = args.length;
|
|
944
|
+
for (let i = 0; i < args.length; i++) {
|
|
945
|
+
if (!consumedIndices.has(i)) {
|
|
946
|
+
firstUnconsumedIndex = i;
|
|
947
|
+
break;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
return { parsedArgs: output, firstUnconsumedIndex };
|
|
951
|
+
};
|
|
952
|
+
displayErrorAndExit_fn = function(error) {
|
|
953
|
+
let commandNameToSuggest = "your-script";
|
|
954
|
+
if (__privateGet(this, _appCommandName)) {
|
|
955
|
+
commandNameToSuggest = __privateGet(this, _appCommandName);
|
|
956
|
+
} else if (__privateGet(this, _appName) && __privateGet(this, _appName) !== "Argument Parser") {
|
|
957
|
+
commandNameToSuggest = __privateGet(this, _appName);
|
|
958
|
+
} else if (typeof process !== "undefined" && process.argv && process.argv[1]) {
|
|
959
|
+
try {
|
|
960
|
+
commandNameToSuggest = path.basename(process.argv[1]);
|
|
961
|
+
} catch {
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
const commandPath = [
|
|
965
|
+
commandNameToSuggest,
|
|
966
|
+
...error.commandChain || []
|
|
967
|
+
].join(" ");
|
|
968
|
+
console.error(`
|
|
969
|
+
${chalk.red.bold("Error:")} ${error.message}`);
|
|
970
|
+
console.error(
|
|
971
|
+
`
|
|
972
|
+
${chalk.dim(`Try '${commandPath} --help' for usage details.`)}`
|
|
973
|
+
);
|
|
974
|
+
if (typeof process === "object" && typeof process.exit === "function") {
|
|
975
|
+
process.exit(1);
|
|
976
|
+
} else {
|
|
977
|
+
throw error;
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
_printRecursiveToConsole_fn = function(parser, level, visited = /* @__PURE__ */ new Set()) {
|
|
981
|
+
const indent = " ".repeat(level);
|
|
982
|
+
const subIndent = " ".repeat(level + 1);
|
|
983
|
+
const flagIndent = " ".repeat(level + 2);
|
|
984
|
+
console.log(
|
|
985
|
+
`${indent}Parser: ${chalk.blueBright(__privateGet(parser, _subCommandName) || __privateGet(parser, _appName))}`
|
|
986
|
+
);
|
|
987
|
+
if (__privateGet(parser, _description)) {
|
|
988
|
+
console.log(`${subIndent}Description: ${__privateGet(parser, _description)}`);
|
|
989
|
+
}
|
|
990
|
+
console.log(`${subIndent}Options:`);
|
|
991
|
+
console.log(`${flagIndent}appName: ${__privateGet(parser, _appName)}`);
|
|
992
|
+
console.log(
|
|
993
|
+
`${flagIndent}appCommandName: ${__privateGet(parser, _appCommandName) ?? chalk.dim("undefined")}`
|
|
994
|
+
);
|
|
995
|
+
console.log(`${flagIndent}handleErrors: ${__privateGet(parser, _handleErrors)}`);
|
|
996
|
+
console.log(
|
|
997
|
+
`${flagIndent}throwForDuplicateFlags: ${__privateGet(parser, _throwForDuplicateFlags2)}`
|
|
998
|
+
);
|
|
999
|
+
console.log(
|
|
1000
|
+
`${flagIndent}inheritParentFlags: ${__privateGet(parser, _inheritParentFlags)}`
|
|
1001
|
+
);
|
|
1002
|
+
console.log(`${flagIndent}Handler Defined: ${!!__privateGet(parser, _handler)}`);
|
|
1003
|
+
console.log(
|
|
1004
|
+
`${subIndent}Internal Params: ${JSON.stringify(__privateGet(parser, _parameters))}`
|
|
1005
|
+
);
|
|
1006
|
+
const flags = __privateGet(parser, _flagManager).flags;
|
|
1007
|
+
if (flags.length > 0) {
|
|
1008
|
+
console.log(`${subIndent}Flags (${flags.length}):`);
|
|
1009
|
+
flags.forEach((flag) => {
|
|
1010
|
+
console.log(`${flagIndent}* ${chalk.green(flag["name"])}:`);
|
|
1011
|
+
console.log(`${flagIndent} Options: ${flag["options"].join(", ")}`);
|
|
1012
|
+
console.log(
|
|
1013
|
+
`${flagIndent} Description: ${Array.isArray(flag["description"]) ? flag["description"].join(" | ") : flag["description"]}`
|
|
1014
|
+
);
|
|
1015
|
+
console.log(
|
|
1016
|
+
`${flagIndent} Type: ${typeof flag["type"] === "function" ? flag["type"].name || "custom function" : flag["type"]}`
|
|
1017
|
+
);
|
|
1018
|
+
console.log(
|
|
1019
|
+
`${flagIndent} Mandatory: ${typeof flag["mandatory"] === "function" ? "dynamic" : flag["mandatory"] ?? false}`
|
|
1020
|
+
);
|
|
1021
|
+
console.log(
|
|
1022
|
+
`${flagIndent} Default: ${JSON.stringify(flag["defaultValue"])}`
|
|
1023
|
+
);
|
|
1024
|
+
console.log(`${flagIndent} Flag Only: ${flag["flagOnly"]}`);
|
|
1025
|
+
console.log(`${flagIndent} Allow Multiple: ${flag["allowMultiple"]}`);
|
|
1026
|
+
console.log(`${flagIndent} Allow Ligature: ${flag["allowLigature"]}`);
|
|
1027
|
+
console.log(
|
|
1028
|
+
`${flagIndent} Enum: ${flag["enum"] && flag["enum"].length > 0 ? flag["enum"].join(", ") : "none"}`
|
|
1029
|
+
);
|
|
1030
|
+
console.log(`${flagIndent} Validator Defined: ${!!flag["validate"]}`);
|
|
1031
|
+
});
|
|
1032
|
+
} else {
|
|
1033
|
+
console.log(`${subIndent}Flags: ${chalk.dim("none")}`);
|
|
1034
|
+
}
|
|
1035
|
+
const subCommandParsers = Array.from(__privateGet(parser, _subCommands).values());
|
|
1036
|
+
if (subCommandParsers.length > 0) {
|
|
1037
|
+
console.log(`${subIndent}Sub-Commands (${subCommandParsers.length}):`);
|
|
1038
|
+
subCommandParsers.forEach((subCommand) => {
|
|
1039
|
+
__privateMethod(this, _ArgParser_instances, _printRecursiveToConsole_fn).call(this, subCommand.parser, level + 1, visited);
|
|
1040
|
+
});
|
|
1041
|
+
} else {
|
|
1042
|
+
console.log(`${subIndent}Sub-Commands: ${chalk.dim("none")}`);
|
|
1043
|
+
}
|
|
1044
|
+
};
|
|
1045
|
+
_buildRecursiveString_fn = function(parser, level, visited = /* @__PURE__ */ new Set()) {
|
|
1046
|
+
if (visited.has(parser)) return "";
|
|
1047
|
+
visited.add(parser);
|
|
1048
|
+
let output = "";
|
|
1049
|
+
const indent = " ".repeat(level);
|
|
1050
|
+
const subIndent = " ".repeat(level + 1);
|
|
1051
|
+
const flagIndent = " ".repeat(level + 2);
|
|
1052
|
+
const addLine = (line) => {
|
|
1053
|
+
output += line + "\\n";
|
|
1054
|
+
};
|
|
1055
|
+
addLine(
|
|
1056
|
+
`${indent}Parser: ${__privateGet(parser, _subCommandName) || __privateGet(parser, _appName)}`
|
|
1057
|
+
// #appName is guaranteed
|
|
1058
|
+
);
|
|
1059
|
+
if (__privateGet(parser, _description)) {
|
|
1060
|
+
addLine(`${subIndent}Description: ${__privateGet(parser, _description)}`);
|
|
1061
|
+
}
|
|
1062
|
+
addLine(`${subIndent}Options:`);
|
|
1063
|
+
addLine(`${flagIndent}appName: ${__privateGet(parser, _appName)}`);
|
|
1064
|
+
addLine(
|
|
1065
|
+
`${flagIndent}appCommandName: ${__privateGet(parser, _appCommandName) ?? "undefined"}`
|
|
1066
|
+
);
|
|
1067
|
+
addLine(`${flagIndent}handleErrors: ${__privateGet(parser, _handleErrors)}`);
|
|
1068
|
+
addLine(
|
|
1069
|
+
`${flagIndent}throwForDuplicateFlags: ${__privateGet(parser, _throwForDuplicateFlags2)}`
|
|
1070
|
+
);
|
|
1071
|
+
addLine(`${flagIndent}inheritParentFlags: ${__privateGet(parser, _inheritParentFlags)}`);
|
|
1072
|
+
addLine(`${flagIndent}Handler Defined: ${!!__privateGet(parser, _handler)}`);
|
|
1073
|
+
addLine(
|
|
1074
|
+
`${subIndent}Internal Params: ${JSON.stringify(__privateGet(parser, _parameters))}`
|
|
1075
|
+
);
|
|
1076
|
+
const flags = __privateGet(parser, _flagManager).flags;
|
|
1077
|
+
if (flags.length > 0) {
|
|
1078
|
+
addLine(`${subIndent}Flags (${flags.length}):`);
|
|
1079
|
+
flags.forEach((flag) => {
|
|
1080
|
+
var _a;
|
|
1081
|
+
addLine(`${flagIndent}* ${flag["name"]}:`);
|
|
1082
|
+
addLine(`${flagIndent} Options: ${flag["options"].join(", ")}`);
|
|
1083
|
+
addLine(
|
|
1084
|
+
`${flagIndent} Description: ${Array.isArray(flag["description"]) ? flag["description"].join(" | ") : flag["description"]}`
|
|
1085
|
+
);
|
|
1086
|
+
let typeName = "unknown";
|
|
1087
|
+
if (typeof flag["type"] === "function") {
|
|
1088
|
+
typeName = flag["type"].name || "custom function";
|
|
1089
|
+
} else if (typeof flag["type"] === "string") {
|
|
1090
|
+
typeName = flag["type"];
|
|
1091
|
+
} else if (typeof flag["type"] === "object" && flag["type"]) {
|
|
1092
|
+
try {
|
|
1093
|
+
typeName = ((_a = flag["type"].constructor) == null ? void 0 : _a.name) || "object";
|
|
1094
|
+
} catch {
|
|
1095
|
+
typeName = "object";
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
addLine(`${flagIndent} Type: ${typeName}`);
|
|
1099
|
+
addLine(
|
|
1100
|
+
`${flagIndent} Mandatory: ${typeof flag["mandatory"] === "function" ? "dynamic" : flag["mandatory"] ?? false}`
|
|
1101
|
+
);
|
|
1102
|
+
addLine(
|
|
1103
|
+
`${flagIndent} Default: ${JSON.stringify(flag["defaultValue"])}`
|
|
1104
|
+
);
|
|
1105
|
+
addLine(`${flagIndent} Flag Only: ${flag["flagOnly"]}`);
|
|
1106
|
+
addLine(`${flagIndent} Allow Multiple: ${flag["allowMultiple"]}`);
|
|
1107
|
+
addLine(`${flagIndent} Allow Ligature: ${flag["allowLigature"]}`);
|
|
1108
|
+
addLine(
|
|
1109
|
+
`${flagIndent} Enum: ${flag["enum"] && flag["enum"].length > 0 ? flag["enum"].join(", ") : "none"}`
|
|
1110
|
+
);
|
|
1111
|
+
addLine(`${flagIndent} Validator Defined: ${!!flag["validate"]}`);
|
|
1112
|
+
});
|
|
1113
|
+
} else {
|
|
1114
|
+
addLine(`${subIndent}Flags: none`);
|
|
1115
|
+
}
|
|
1116
|
+
const subCommandParsers = Array.from(__privateGet(parser, _subCommands).values());
|
|
1117
|
+
if (subCommandParsers.length > 0) {
|
|
1118
|
+
addLine(`${subIndent}Sub-Commands (${subCommandParsers.length}):`);
|
|
1119
|
+
subCommandParsers.forEach((subCommand) => {
|
|
1120
|
+
output += __privateMethod(this, _ArgParser_instances, _buildRecursiveString_fn).call(this, subCommand.parser, level + 1, visited);
|
|
1121
|
+
});
|
|
1122
|
+
} else {
|
|
1123
|
+
addLine(`${subIndent}Sub-Commands: none`);
|
|
1124
|
+
}
|
|
1125
|
+
return output;
|
|
1126
|
+
};
|
|
1127
|
+
_buildRecursiveJson_fn = function(parser, visited = /* @__PURE__ */ new Set()) {
|
|
1128
|
+
if (visited.has(parser))
|
|
1129
|
+
return {
|
|
1130
|
+
note: `Reference to already processed parser: ${__privateGet(parser, _subCommandName) || __privateGet(parser, _appName)}`
|
|
1131
|
+
};
|
|
1132
|
+
visited.add(parser);
|
|
1133
|
+
const config = {
|
|
1134
|
+
parserName: __privateGet(parser, _subCommandName) || __privateGet(parser, _appName),
|
|
1135
|
+
// #appName is guaranteed
|
|
1136
|
+
description: __privateGet(parser, _description),
|
|
1137
|
+
options: {
|
|
1138
|
+
appName: __privateGet(parser, _appName),
|
|
1139
|
+
appCommandName: __privateGet(parser, _appCommandName) ?? void 0,
|
|
1140
|
+
handleErrors: __privateGet(parser, _handleErrors),
|
|
1141
|
+
throwForDuplicateFlags: __privateGet(parser, _throwForDuplicateFlags2),
|
|
1142
|
+
inheritParentFlags: __privateGet(parser, _inheritParentFlags)
|
|
1143
|
+
},
|
|
1144
|
+
handlerDefined: !!__privateGet(parser, _handler),
|
|
1145
|
+
internalParams: __privateGet(parser, _parameters),
|
|
1146
|
+
flags: [],
|
|
1147
|
+
subCommands: {}
|
|
1148
|
+
// Will be an object where keys are sub-command names
|
|
1149
|
+
};
|
|
1150
|
+
const flags = __privateGet(parser, _flagManager).flags;
|
|
1151
|
+
config.flags = flags.map((flag) => {
|
|
1152
|
+
var _a;
|
|
1153
|
+
let typeName = "unknown";
|
|
1154
|
+
if (typeof flag["type"] === "function") {
|
|
1155
|
+
typeName = flag["type"].name || "custom function";
|
|
1156
|
+
} else if (typeof flag["type"] === "string") {
|
|
1157
|
+
typeName = flag["type"];
|
|
1158
|
+
} else if (typeof flag["type"] === "object" && flag["type"]) {
|
|
1159
|
+
try {
|
|
1160
|
+
typeName = ((_a = flag["type"].constructor) == null ? void 0 : _a.name) || "object";
|
|
1161
|
+
} catch {
|
|
1162
|
+
typeName = "object";
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
return {
|
|
1166
|
+
name: flag["name"],
|
|
1167
|
+
options: flag["options"],
|
|
1168
|
+
description: flag["description"],
|
|
1169
|
+
type: typeName,
|
|
1170
|
+
mandatory: typeof flag["mandatory"] === "function" ? "dynamic" : flag["mandatory"] ?? false,
|
|
1171
|
+
defaultValue: flag["defaultValue"],
|
|
1172
|
+
flagOnly: flag["flagOnly"],
|
|
1173
|
+
allowMultiple: flag["allowMultiple"],
|
|
1174
|
+
allowLigature: flag["allowLigature"],
|
|
1175
|
+
enum: flag["enum"],
|
|
1176
|
+
validatorDefined: !!flag["validate"]
|
|
1177
|
+
};
|
|
1178
|
+
});
|
|
1179
|
+
const subCommands = Array.from(__privateGet(parser, _subCommands).values());
|
|
1180
|
+
if (subCommands.length > 0) {
|
|
1181
|
+
subCommands.forEach((sub) => {
|
|
1182
|
+
config.subCommands[sub.name] = __privateMethod(this, _ArgParser_instances, _buildRecursiveJson_fn).call(this, sub.parser, visited);
|
|
1183
|
+
});
|
|
1184
|
+
}
|
|
1185
|
+
return config;
|
|
1186
|
+
};
|
|
1187
|
+
let ArgParser = _ArgParser;
|
|
1188
|
+
export {
|
|
1189
|
+
ArgParser,
|
|
1190
|
+
ArgParserError
|
|
1191
|
+
};
|
|
1192
|
+
//# sourceMappingURL=index.mjs.map
|